Google REST-ful call + Guzzle: Setting Authorization Token - php

I'm new with Guzzle and I'm trying to make a call to Google API with it. I tried in this way with no luck: PHP + Guzzle, Sending Authorization Key in Header
Here is my code:
$client = new Client();
try {
$request = $client->get ( 'https://www.googleapis.com/analytics/v3/data/ga' );
/*setting Authorization token*/
$request->addHeader('authorization', $accessToken);
$query = $request->getQuery();
$query->set('ids', $profileId);
$query->set('start-date', $startDate);
$query->set('end-date', $endDate);
$query->set('metrics', $metrics);
$response = $request->send();
$response = $response->json();
var_dump($response);
} catch (ClientErrorResponseException $e) {
var_dump($e->getMessage ());
}
I'm always getting this response:
"Client error response
[status code] 401
[reason phrase] Unauthorized
[url] https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3AXXXXXX&start-date=2014-07-01&end-date=2014-07-01&metrics=ga%3Asessions"
I've tried the same call using PHP curl and I'm getting the correct response, but I'd like to use Guzzle in this project.
What is the correct way to do this
array ( CURLOPT_HTTPHEADER => array( 'Authorization: Bearer ' . $accessToken )) with Guzzle?

The problem you are having is that a Request to the Google Analytics API is sent as a Get. Adding a header is used for a POST.
$request->addHeader('authorization', $accessToken);
The following will add the accessToken as part of the Get in your request.
$query->set('oauth_token', $accessToken);

Related

How to change PHP Guzzle from postman to Laravel Guzzle format

I'm struggling to change the code from PHP-Guzzle format that i get from postman to Laravel-Guzzle format.
So i want to use this PHP - Guzzle from Postman.
$client = new Client();
$headers = [
'Authorization' => 'OAuth realm="xxx",oauth_consumer_key="xxx",oauth_token="xxx",oauth_signature_method="HMAC-SHA256",oauth_timestamp="123",oauth_nonce="xxx",oauth_version="1.0",oauth_signature="xxx"',
'Cookie' => 'NS_ROUTING_VERSION=LAGGING'
];
$request = new Request('GET', 'https://domainname.com/record/1234', $headers);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();
from above code. i need to convert to laravel format. and here is what i've done
use GuzzleHttp\Client;
$guzzle = new Client;
$header = [
'Authorization' => 'OAuth realm="xxx",oauth_consumer_key="xxx",oauth_token="xxx",oauth_signature_method="HMAC-SHA256",oauth_timestamp="123",oauth_nonce="xxx", oauth_version="1.0", oauth_signature="xxx"',
'Cookie' => 'NS_ROUTING_VERSION=LAGGING'
];
$response = $guzzle->request('GET', 'https://domainname.com/record/1234', $header);
dd($response->getBody());
but i got error
Client error: `GET https://domainname.com/record/1234` resulted in a `401 Unauthorized` response: {"type":"https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2","title":"Unauthorized","status":401,"o:error (truncated...)
i tried to solve it but cannot. please help how to make it work on laravel.
401 Unauthorized mean you are missing something like: token. That's mean your connection have been made but your credencials is't right. So nothing wrong with your code.

PHP: How to make an api call with api key authorization using Guzzle?

I'm trying to create a client to connect an IBM-Watson bot service using Guzzle for an application constructed in Laravel, but it fails when attempting to create a new session of the service, I got the error 401: Unauthorized. I'm not using basic authorization, instead I'm trying to connect by api-key authorization.
function start_bot_session() {
//Api Key de Watson.
$api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//ID bot (Watson).
$assistant_id = '9c1c426d-cd33-49ec-a3bc-f0835c3264b5';
//URL service.
$url = 'https://gateway.watsonplatform.net/assistant/api/v2/assistants/';
//Method for start a new session.
$method = $assistant_id.'/sessions?version=2019-02-28';
$client = new \GuzzleHttp\Client(["base_uri" => $url]);
$response = $client->request('POST', $method, [
'headers' => [
'Authorization:' => $api_key
]
]);
return response;
}
Is there any way I can fix this?
Can you tell me some alternatives to make api call instead of using Guzzle?

Google create enterprise 403 error on get signup url request

I am trying to create new enterprise in my emm provider.
here is code
error_reporting(0);
$projectId = "api-7288506515928753288-19357";
$callbackUrl = url('emm/create/enterprise');
$callbackUrl = str_replace('http://', 'https://', $callbackUrl);
$authFile = storage_path('app/key/dv-505f70dd1be9.json');
putenv("GOOGLE_APPLICATION_CREDENTIALS={$authFile}");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/androidenterprise');
// returns a Guzzle HTTP Client
$httpClient = $client->authorize();
$response = $httpClient->post("https://www.googleapis.com/androidenterprise/v1/enterprises/signupUrl?callbackUrl={$callbackUrl}");
$response = json_decode( $response->getBody()->getContents() );
// $request->session()->put('signupUrlName', $response->name);
// $request->session()->put('signupUrl', $response->url);
return json_encode( $response );
I got below responce
{
error: {
errors: [
{
domain: "androidenterprise",
reason: "forbiddenNotAnMdm",
message: "The caller is not registered as an MDM."
}
],
code: 403,
message: "The caller is not registered as an MDM."
}
}
I already checked on https://content-androidmanagement.googleapis.com/v1/signupUrls api.
This api is working right .
in short authentication is right with proper scope . But can t able to figure out responce.
To use the Google Play EMM API you need to be registered in the EMM Community.
But you shouldn't need to use this API anymore, instead you should use the new Android Management API that gives the same capabilities, and more.

401 Unauthorized using Guzzle but works from curl

I'm trying to fetch orders data on my InfusionSoft account. I can do it using the command line but the Guzzle code gives me 401 Unathorized. I suppose I'm doing something wrong and not able to pass the params correctly. Can someone help?
Here's what works from the command line:
curl -G --data "access_token=abcdefgh12345678" https://api.infusionsoft.com/crm/rest/v1/orders?limit=1&offset=100&order_by=id
And here's the (supposedly) equivalent code from PHP:
$token = 'abcdefgh12345678';
$requestBody = array('access_token' => $token);
$url = 'https://api.infusionsoft.com/crm/rest/v1/orders?limit=1&offset=100&order_by=id';
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $url, array(
'form_params' => $requestBody
));
$response = (string) $response->getBody();
You are sending a GET request, and a GET request cannot contain a body.
curl uses --data according to the request method, so for GET it adds the access token to the URL as a GET-parameter. So should you.

How to use Rest API and PHP

Very beginner question but simply do not know where to begin. I am trying to obtain a response with this API using PHP but cannot get anything to work.
I know the problem has something to do with HTTP Components but I'm a total beginner and very stuck.
Any help would be great or perhaps if there's another (cleaner and easier) way to do this would be great as well.
I am trying to get the response in json format
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://services.last10k.com/v1/company/{ticker}/ratios');
$url = $request->getUrl();
$headers = array(
// Request headers
'Ocp-Apim-Subscription-Key' => '{subscription key}',
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_GET);
// Request body
$request->setBody("{body}");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>

Categories