user3687833
user3687833

Reputation: 1

Google_Auth_Exception When trying to get OAuth 2.0 Service Account Authentication

This is my code:


    session_start();
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    require_once 'Google/Client.php';
    require_once 'Google/Service/AdExchangeSeller.php';

    $scriptUri = "http://example.com/some_seller_api.php";

    $client_id = 'XXXXXX.apps.googleusercontent.com';
    $service_account_name = '[email protected]';
    $key_file_location = '/XXXXX/privatekey.p12';

    $client = new Google_Client();
    $client->setApplicationName("Example_app");

    if (isset($_SESSION['service_token'])) {
      $client->setAccessToken($_SESSION['service_token']);
    }

    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials(
        $service_account_name,
        array('https://www.googleapis.com/auth/adexchange.seller.readonly'),
        $key
    );

    $client->setAssertionCredentials($cred);

    if($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $_SESSION['service_token'] = $client->getAccessToken();

    $service = new Google_Service_AdExchangeSeller($client);
    $acc = $service->adclients->listAdclients();

I do everything like in official manual and example from https://github.com/google/google-api-php-client/blob/master/examples/service-account.php

And i've got an error:

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }''

What am I doing wrong?

Upvotes: 0

Views: 1276

Answers (1)

svpino
svpino

Reputation: 1994

It appears that you haven't authorized your application with the target service. One of the OAuth2 steps is that your application (the one that's going to be accessing the service) needs to be "registered" (or authorized) with the target service. This is the way you will register what's the callback URL, etc.

Per your code, you are accessing the Ad Exchange Seller REST API. Open the following link and follow the step by step guide in order to fix the issue you are having:

https://developers.google.com/ad-exchange/seller-rest/getting_started#auth

Upvotes: 0

Related Questions