Can anyone help me with my problem, i'm trying to use Guzzle in Laravel 5 and trying to retrieve a data from Rest API. i always get this when I dd().
Stream {#287 ▼
-stream: :stream {#11 ▶}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
and here's my controller, not sure if i'm integrating with guzzle properly.
<?php namespace App\Http\Controllers;
class SampleController extends \SleepingOwl\Admin\Controllers\AdminController {
public function getIndex() {
$client = new \GuzzleHttp\Client();
$response = $client->get('http://httpbin.org/get');
$body = $response->getBody();
dd($body);
//return \View::make('samplerest')->with('tests',$body);
}
}
You can also use $response->json(); like this :
$client = new \GuzzleHttp\Client();
$response = $client->get('http://httpbin.org/get');
$json = $response->json();
Note that it'll throw an Exception if the response is not well formatted.
Related
I have a problem on an API call with the Guzzle 7.4.3 library to PATCH severals produced on Akeneo 5.0.50
By following the documentation below:
https://api.akeneo.com/api-reference.html#patch_products
I first tested the api via Postman here is the result:
Res Postman
However with the guzzle code this one doesn't work and returns a null body with a 200 code.
Here is the code:
public function patchProductGlobalAkeneo(string $token_akeneo, string $data_products): object
{
try {
$request = $this->client->request('PATCH', $_ENV["AKENEO_API_URL"] . $_ENV["AKENEO_API_URL_PRODUCTS"], [
'headers' => [
'Authorization' => 'Bearer ' . $token_akeneo,
'Content-Type' => 'application/vnd.akeneo.collection+json'
],
'json' => json_decode('{"identifier":"01750003001400","values":{"stock":[{"data":"10","locale":null,"scope":null}]}}
{"identifier":"01750003001400","values":{"stock":[{"data":"10","locale":null,"scope":null}]}}')
]);
} catch (RequestException $e) {
$res = new stdClass();
$res->content = json_decode($e->getResponse()->getBody()->getContents());
$res->status_res = $e->getResponse()->getStatusCode();
var_dump($res->status_res);
var_dump("ERROR");
return $res;
}
$res = new stdClass();
$res->content = json_decode($request->getBody()->getContents());
$res->status_res = $request->getStatusCode();
var_dump($res->content);
var_dump($res->status_res);
var_dump("GOOD");
return $res;
}
The result of the var_dump : Res Var_dump
I want to use PDO with my Slim php application. When I use a simple select query and send json data to Twig page. But I keep getting this error : Slim Application Error
This is my code :
<?php
require __DIR__ . '/vendor/autoload.php';
$app = new Slim\App;
$container = $app->getContainer();
$container['view'] = function ($container) {
$templates = __DIR__ . '/templates/';
$cache = __DIR__ . '/tmp/views/';
$view = new Slim\Views\Twig($templates, array('cache' => false));
return $view;
};
$container['db'] = function ($container) {
$pdo = new PDO("mysql:host=localhost;DBName=dbsat", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
$app->get('/', function ($request, $response) {
$sth = $this->db->prepare("SELECT * from client where id=:id");
$sth->bindParam("id", 1);
$sth->execute();
$todos = json_encode($sth->fetchAll());
$data = ['user' => $todos];
return $this->view->render($response, 'home.twig', $data);
});
$app->get('/login', function ($request, $response) {
return $this->view->render($response, 'login.twig');
});
$app->run();
?>
The problem appears at this line :
$sth = $this->db->prepare("SELECT * from client where id=:id");
Problem solved. It was caused by binding param
Message: Cannot pass parameter 2 by reference
By knowing the error I have fixed it. Thank you all.
Iam using oriceon/oauth-5-laravel for connecting with instagram.I authenticated and i got my name and id by through this request
$result = json_decode($instagramService->request('users/self'), true);
Now i want to follow a person by using this oriceon/oauth-5-laravel.
How i could post the request to follow a person by using this .
**NOTE:**dont refer the instagram developer page.I reffred it a lot.But i couldnt put a post request for ORICEON/laravel oauth wrapper for instagram.
HELP ME.TYSM in advance
try this .Copy this method to your controller and do proper routing.
public function followWithInstagram(Request $request)
{
$instagram_id='id of the user that you want to follow';
$code = $request->get('code');
$instagramService = \OAuth::consumer('Instagram');
if ( ! is_null($code))
{
$state = isset($_GET['state']) ? $_GET['state'] : null;
$instagramService->requestAccessToken($code, $state);
$linkData = [
'action' =>'follow',
];
$result =json_decode($instagramService->request('https://api.instagram.com/v1/users/'.$instagram_id.'/relationship','POST',$linkData),true);
if(!$result){
return ("Failed");
}
else {
return ("SUCCESS");
}
} else {
$url = $instagramService->getAuthorizationUri();
return redirect((string)$url);
}
}
I have a Module called "Backend" and in this module I want to check for valid authentication on all pages except the backend_login page. How do I do this? I tried to add it to the onBootstrap in the Backend/Module.php , but it turns out that is called in my other modules as well... which is of course not what I want.
So how do I do this?
Thanks in advance!
To get clear information about zf2 authentication you can follow:
ZF2 authentication
adapter auth
database table auth
LDAP auth
digest auth....These all are different methods here is an example of database table auth:
in every controller's action, where you need user auth something should like this:
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
public function login($credential)
{
$bcrypt = new Bcrypt();
$user = new User();
$auth = new AuthenticationService();
$user->exchangeArray($credential);
$password = $user->password;
$data = $this->getUserTable()->selectUser($user->username);
if (!$data){
$message = 'Username or password is not correct!';
}
elseif($auth->getIdentity() == $user->username){
$message = 'You have already logged in';
}
elseif($bcrypt->verify($password, $data->password)){
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter(
$dbAdapter,
'user',
'username',
'password'
);
$authAdapter -> setIdentity($user->username) -> setCredential($data->password);
$result = $auth->authenticate($authAdapter);
$message = "Login succesfull.Welcome ".$result->getIdentity();
} else {
$message = 'Username or password is not correct';
}
return new ViewModel(array("message" =>$message));
}
Like this in every action you can check whether it is authenticated or not
if($auth -> hasIdentity()){
//your stuff
}
else{
//redirected to your login route;
}
I had once a similar problem and figured it out within my Module.php in the onBootstrap() function. Try this, it worked for me:
class Module {
// white list to access with being non-authenticated
//the list may contain action names, controller names as well as route names
protected $whitelist = array('login');
//....
public function onBootstrap($e){
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$list = $this->whitelist;
$auth = new AuthenticationService();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
$match = $e->getRouteMatch();
// No route match, this is a 404
if (!$match instanceof RouteMatch) {
return;
}
// Route is whitelisted
$action = $match->getParam('action');
if (in_array($action, $list) ) {
return;
}
// User is authenticated
if ($auth->hasIdentity()){
return;
}
// the user isn't authenticated
// redirect to the user login page, as an example
$router = $e->getRouter();
$url = $router->assemble(array(
'controller' => 'auth',
'action'=>'login'
), array(
'name' => 'route_name',
));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
}
Or you may see bjyauthorize.
I have implemented the google plus api on development server and it works fine. I used the same code on production server. But after requesting the permission it takes a long time to return to my site and login.
Can anyone please let me know what might be the cause. I have used oauth2.
Below is the code I am using
<?php
session_start();
require_once 'googleplus/src/Google_Client.php';
require_once 'googleplus/src/contrib/Google_Oauth2Service.php';
class Webpage_UserGPlusLogin extends Webpage
{
public function __construct()
{
$temp_redirect = $_SESSION['RETURN_URL_AFTERLOGIN'];
$this->title = 'User Account';
$client = new Google_Client();
$client->setApplicationName(WEBSITE_NAME);
$client->setClientId(GOOGLE_PLUS_CLIENT_ID); // Client Id
$client->setClientSecret(GOOGLE_PLUS_CLIENT_SECRET); // Client Secret
$client->setRedirectUri(GOOGLE_PLUS_REDIRECT_URI); // Redirect Uri set while creating API account
$client->setDeveloperKey(GOOGLE_PLUS_DEVELOPER_KEY); // Developer Key
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = GOOGLE_PLUS_REDIRECT_URI;
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); // Redirects to same page
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if(!isset($_SESSION['email_address_user_account'])) // Check if user is already logged in or not
{
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get(); // Google API call to get current user information
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$img = filter_var($user['picture'], FILTER_VALIDATE_URL);
$googleuserid = $user['id'];
$given_name = $user['given_name'];
$family_name = $user['family_name'];
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
// If email address is present in DB return user data else insert user info in DB
$this->result = UserAccount::gplus_sign_up($email, $googleuserid, $given_name, $family_name);
// Create new user object.
$this->user_account = new UserAccount($this->result['id'],$this->result['email_address'],$this->result['password'],$this->result['confirmation_code'],$this->result['is_confirmed'], $this->result['first_name'], $this->result['last_name']);
$_SESSION['gplus_email_address'] = $email;
$_SESSION['gplus_first_name'] = $given_name;
$_SESSION['gplus_last_name'] = $family_name;
$_SESSION['gplus_id'] = $googleuserid;
$_SESSION['gplus_profile_pic'] = $img;
$_SESSION['email_address_user_account'] = $email;
} else {
$authUrl = $client->createAuthUrl();
}
}
if(isset($temp_redirect))
header("Location:".$temp_redirect);
else
header("Location:/");
}
}
Thanks in advance
Try this
use following code
$temp = json_decode($_SESSION['token']);
$request = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$request);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_TIMEOUT,30);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Authorization: OAuth '.$temp->access_token));
$response = trim(curl_exec($curl));
$info = curl_getinfo($curl);
$request_header_info = curl_getinfo($curl, CURLINFO_HEADER_OUT);
//var_dump($info);
//var_dump($request_header_info);
curl_close($curl);
echo "<pre>";
print_r(json_decode($response));
instade of
$user = $oauth2->userinfo->get(); // Google API call to get current user information`enter code here`
Hope this will help you .. :)