Diana R.
Diana R.

Reputation: 315

Google REST-ful call + Guzzle: Setting Authorization Token

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?

Upvotes: 6

Views: 5242

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117301

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);

Upvotes: 4

Related Questions