Google REST-ful call + Guzzle: setting an authorization token

I am new to Guzzle and I am trying to call him in the Google API. I tried so hard: the PHP + guzzle, sending an authorization key in the title

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 always get this answer:

"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 tried the same call with PHP curl and I get the correct answer, but I would like to use Guzzle in this project.

What is the right way to do this? array ( CURLOPT_HTTPHEADER => array( 'Authorization: Bearer ' . $accessToken ))using guzzle?

+4
source share
1 answer

The problem you are facing is that the Google Analytics API Request is sent as Get. Adding a header is used for POST.

$request->addHeader('authorization', $accessToken);

accessToken Get .

$query->set('oauth_token', $accessToken);
+4

All Articles