Skip to content

Instantly share code, notes, and snippets.

@pankpan
Last active October 15, 2021 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pankpan/b15b386bc124b4752f5a22af0780a0b1 to your computer and use it in GitHub Desktop.
Save pankpan/b15b386bc124b4752f5a22af0780a0b1 to your computer and use it in GitHub Desktop.
PHP Adsnese API v2
<?php
require __DIR__ . '/vendor/autoload.php';
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Adsense PHP Client');
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAuthConfig('/usr/local/etc/adsense-credentials.json'); // client secret json file (OAuth 2.0 client ID) download from Google
$tokenPath = '/usr/local/etc/adsense-token.json'; // refresh token saved here
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
$client=getClient();
$service = new Google_Service_Adsense($client);
$account = 'accounts/pub-xxxx'; // adsense account here
$optParams=["currencyCode"=>"USD","dateRange"=>"TODAY","dimensions"=>"DATE","metrics"=>"TOTAL_EARNINGS","metrics"=>"CLICKS",
"prettyPrint"=>"true","alt"=>"json"];
$result = $service->accounts_reports->generate($account,$optParams);
print_r($result);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment