努力存储AdSense API令牌

时间:2017-05-25 04:40:47

标签: google-api google-api-php-client adsense google-api-client adsense-api

我已成功设法连接到AdSense API并运行报告。但是,每次运行它都需要登录,因此它不会作为cron作业运行。

我发现了一些与此相关的问题。有些人建议使用服务帐户,而其他人则指出服务帐户不适用于AdSense。建议的解决方案是在我的服务器上存储令牌,但我一直在努力让它工作。这是我到目前为止的代码(有效,但需要手动登录):

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApplicationName('My Application name');
$client->setClientId(' MY ID ');
$client->setClientSecret(' MY SECRET ');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(' MY KEY '); // API key

$accountId = " MY ACCOUNT " ;
$adClientId = " MY CLIENT " ;


// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

$startDate = '2015-11-01';
$endDate = 'today';
$optParams = array(
  'metric' => array(
    'EARNINGS'),
  'dimension' => array('DATE'),
  'sort' => '+DATE',
  'filter' => array(
    'CUSTOM_CHANNEL_NAME==Mega Seating Plan'
  )
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $startDate,
    $endDate, $optParams);
if (isset($report) && isset($report['rows'])) {


  // Get results.
  foreach($report['rows'] as $row) {

    $date = $row[0] ;
    $earnings[$date] = $row[1] ;  


  }
} else {
  print "No rows returned.\n";
}

有人可以告诉我如何将令牌存储合并到上面的代码中吗?

1 个答案:

答案 0 :(得分:1)

感谢@ jkns.co的上一个答案here,这有助于我让它发挥作用。

这是我的最终代码:

$scriptUri = "I HAD TO PUT MY ABSOLUTE URL HERE, OTHERWISE THE CRON JOB WOULD LOOK IN THE WRONG PLACE" ;

$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");  // This line had to be added to force the approval prompt and request a new token
$client->setApplicationName('My Application name');
$client->setClientId('BLAH');
$client->setClientSecret('BLAH');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('BLAH'); // API key

$accountId = "BLAH" ;
$adClientId = "BLAH" ;


// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();

    // If it successfully authenticates, I request the refresh token
    $refreshToken = $client->getRefreshToken();

    storeRefreshToken($refreshToken) ;  // This function stores the token in MySQL
}

else {      // Otherwise it loads the refresh token from MySQL


    $refreshToken = getRefreshToken() ;



    $client->refreshToken($refreshToken);
    $_SESSION['token'] = $client->getAccessToken();

}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);


}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}