我无法通过Google登录到客户的AdWords帐户

时间:2020-10-21 09:40:20

标签: google-ads-api google-login

我想将任何客户的Google AdWords帐户与Google登录名相关联。 (如Wordstream)

我准备了代码,但是某个地方有问题,我无法运行它。

当客户按下连接按钮时,出现屏幕。上面写着“ XXX要访问您的Google帐户”,它已获得批准,但我无法接收数据。

我如何从客户的帐户中获取数据?

代码:

require 'google-api/vendor/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' => 'https://xxxxx.xxxxxx',
    'clientId' => 'xxxxxxxxx.apps.googleusercontent.com',
    'clientSecret' => 'xxxxxxxxxxx',
    'scope' => 'https://www.googleapis.com/auth/adwords',
    'refresh_token' => 'xxxxxxxxxx'
]);

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 = "xxxxx/google-api/vendor/adsapi_php.ini";

    $session = (new AdWordsSessionBuilder())
        ->fromFile($path)
        ->withOAuth2Credential($oauth2)
        ->build();
    
    $adWordsServices = new AdWordsServices();
    
    $campaignService = $adWordsServices->get($session, CampaignService::class);
    
    print_r($campaignService);

}

enter image description here

0 个答案:

没有答案