How can i reach Google Ads campaigns with Google Login

79 views
Skip to first unread message

ma...@sumer.me

unread,
Dec 10, 2018, 2:34:37 AM12/10/18
to AdWords API and Google Ads API Forum
Hi,

I want to access any client's Google ad account using PHP. I tried this but I'm getting the error:

require 'autoload.php';
use Google\Auth\OAuth2;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

session_start();
$oauth2 = new OAuth2([
     'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
     'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
     'redirectUri' => 'XXXXX',
     'clientId' => 'XXXXXX',
     'clientSecret' => 'XXXXX,
     'scope' => 'https://www.googleapis.com/auth/adwords',
     'refresh_token' => 'XXXXX'
]);
if(!isset($_GET['code'])){
     $oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
     $_SESSION['oauth2state'] = $oauth2->getState();
     $config = [

                   'access_type' => 'offline',
        'prompt' => 'consent',
     ];
     header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
     exit;
 
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])){
 
          unset($_SESSION['oauth2state']);
          exit('Invalid state.');
 
} else {
     $oauth2->setCode($_GET['code']);
     $authToken = $oauth2->fetchAuthToken();
     $refreshToken = $authToken['refresh_token'];

           $path = "/home/XXXXXXXX/adsapi_php.ini";
     $session = (new AdWordsSessionBuilder())
           ->fromFile($path)
           ->withOAuth2Credential($oauth2)
                        ->build();

           $adWordsServices = new AdWordsServices();
     $campaignService = $adWordsServices->get($session, CampaignService::class);
     print_r($campaignService);
}

Error:

Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `POST https://www.googleapis.com/oauth2/v4/token` resulted in a `400 Bad Request` response: { "error": "invalid_grant", "error_description": "Bad Request" } ' in /home/XXXXXXX..................

Dannison Yao (AdWords API Team)

unread,
Dec 10, 2018, 3:45:51 AM12/10/18
to AdWords API and Google Ads API Forum
Hi Mahir,

The invalid_grant error normally occurs due to expired refreshToken. To resolve this issue, you may try to regenerate the refreshToken and the OAuth2 credentials using an email address which has currently access to your AdWords account and then retry the request again. 

Should the issue persists, could you provide which email address you used when you generated your credentials and your clientCustomerId via Reply privately to author so I can further investigate?

Regards,
Dannison
AdWords API Team
Reply all
Reply to author
Forward
0 new messages