通过PHP获取上个月的Adsense利润



这个问题在这个网站上以各种形式提出(没有太具体),我想一劳永逸地构建一个解决方案,试图克服许多令人困惑的步骤。

大声说道:我需要提取上个月的总广告收入,以便与我的网站一起使用。

  1. 我意识到这将需要Adsense API
  2. 我意识到我需要提供凭据

许多现有的问答;关于这件事的A指的是谷歌AdSense界面的早期版本。我想在2017年的基础上做这件事。

问题:

请有人提供一个准确、循序渐进甚至过于解释性的指导,说明如何完成这项工作,以及哪些API是必要的,以及它们的配置?

我已经尝试过多次的动作,但我所得到的(当我足够幸运地实现了服务器/服务器握手时)只是一个错误,表明JSON输出中"必须登录"。

我已经阅读了一些关于"解决方案"的信息,但无法判断它们是否不起作用,或者我启用的API是否不正确(或配置错误)。

您应该从下载包含AdSense PHP示例的Google API PHP客户端库

https://developers.google.com/api-client-library/php/start/installation

点击GitHub链接,您将进入此页面

https://github.com/goog`le/google-api-php-client

你会得到一个名为"google-api-php-client-2.1.1"的文件夹,你必须将其上传到yur服务器。

单击绿色按钮"克隆或下载"。然后从这里下载一些AD-SENSE的例子

https://github.com/googleads/googleads-adsense-examples

查看文件googleads-adsense-examples-master/php-clientlib-1.x/v1.x/adsense-sample.php在此文件中,将常量STORE_On_DISK设置为true。更好的是,你可以在下面查看我自己的adsense-sample.php的代码。

编辑文件googleads-adsense-examples-master/php-clientlib-1.x/v1.x/client_secrets.json使用您可以从Google AdSense帐户获得的凭据从获取您的客户ID

https://console.developers.google.com/apis/credentials

文件googleads-adsense-examples-master/php-clientlib-1.x/v1.x/client_secrets.json的内容应该看起来像

{
"web":
{
"client_id":"youridblablabla.apps.googleusercontent.com",
"project_id":"yournameproject",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"blablabla",
"redirect_uris":["http://yourdomain.com/thepathtoyoursamplephpfile"],
"javascript_origins":["http://yourdomain.com/","http://yourdomain.com/"]
}
}

从这里获取您的出版商IDhttps://www.google.com/adsense/,然后转到"设置/帐户信息"面板

--

这是我修改示例代码并使其工作的方式。将api文件夹google-api-php-client-2.1.1放在包含此php文件的文件夹中(请参阅下面的php代码)。在文件夹"google-api-php-client-2.2.1.1"中创建一个文件夹AdSense_Report复制所有示例文件(CollateReportData.php、FillMissingDatesInReport.php、GenerateReport.php…)在文件夹AdSense_Report中。因此,您可以通过以下方式包含示例文件:

require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAccounts.php';

重命名my_project_client_secrets.json并将其放在文件夹"AdSense_Report"中。请确保文件my_project_client_secrets.json不能被其他人读取,而只能被这个php读取。这是我的php代码。我评论了一些不需要的功能。

function UserBannerRevenueReportGoogle()
{
define('MAX_LIST_PAGE_SIZE', 50, true);
define('MAX_REPORT_PAGE_SIZE', 50, true);
define('STORE_ON_DISK', true, true);
define('TOKEN_FILENAME', 'google-api-php-client-2.1.1/AdSense_Report/google_adsense_tokens.dat', true);
define('CLIENT_SECRET_JSON_PATH', 'google-api-php-client-2.1.1/AdSense_Report/my_project_client_secrets.json', true);
require_once 'google-api-php-client-2.1.1/vendor/autoload.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/templates/base.php';
session_start();
/*
// In case of trouble, reset the token by activating these lines, call the script, then comment these lines back.
unset($_SESSION['access_token']);
@unlink(TOKEN_FILENAME);
return;
*/
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setAuthConfig(CLIENT_SECRET_JSON_PATH);

$service= new Google_Service_AdSense($client);
// If we're logging out we just need to clear our local access token.
// Note that this only logs you out of the session. If STORE_ON_DISK is
// enabled and you want to remove stored data, delete the file.
if(isset($_REQUEST['logout']))
{
unset($_SESSION['access_token']);
@unlink(TOKEN_FILENAME);
}
// If we have a code back from the OAuth 2.0 flow, we need to exchange that
// with the authenticate() function. We store the resultant access token
// bundle in the session (and disk, if enabled), and redirect to this page.
if(isset($_GET['code']))
{
$client->authenticate($_GET['code']);
// Note that "getAccessToken" actually retrieves both the access and refresh
// tokens, assuming both are available.
$_SESSION['access_token'] = $client->getAccessToken();
if(STORE_ON_DISK){
file_put_contents(TOKEN_FILENAME, $_SESSION['access_token']);
}
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ."?ta=54";
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
exit;
}
// If we have an access token, we can make requests, else we generate an authentication URL.
if(isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
else if(STORE_ON_DISK && file_exists(TOKEN_FILENAME) && filesize(TOKEN_FILENAME) > 0)
{
// Note that "setAccessToken" actually sets both the access and refresh token,
// assuming both were saved.
$client->setAccessToken(file_get_contents(TOKEN_FILENAME));
$_SESSION['access_token'] = $client->getAccessToken();
}
else
{
// If we're doing disk storage, generate a URL that forces user approval.
// This is the only way to guarantee we get back a refresh token.
if(STORE_ON_DISK){
$client->setApprovalPrompt('force');
}
$authUrl = $client->createAuthUrl();
}

echo pageHeader('AdSense Management API sample');
echo '<div><div class="request">';
if(isset($authUrl))
{
echo '<a class="login" href="' . $authUrl . '">Connect Me!</a>';
}
else
{
echo '<a class="logout" href="?ta=54&logout">Logout</a>';
}
echo '</div>';

if($client->getAccessToken())
{
echo '<pre class="result">';
// Now we're signed in, we can make our requests.
UserBannerRevenueReportGoogleGet($service);
// Note that we re-store the access_token bundle, just in case anything
// changed during the request - the main thing that might happen here is the
// access token itself is refreshed if the application has offline access.
$_SESSION['access_token'] = $client->getAccessToken();
echo '</pre>';
}
echo '</div>';
echo pageFooter(__FILE__);
}

function UserBannerRevenueReportGoogleGet($service)
{
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAccounts.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAccountTree.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAdClients.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAdUnits.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllCustomChannelsForAdUnit.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllCustomChannels.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllUrlChannels.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GenerateReport.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GenerateReportWithPaging.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/FillMissingDatesInReport.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/CollateReportData.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllSavedReports.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GenerateSavedReport.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllSavedAdStyles.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAlerts.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllDimensions.php';
require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllMetrics.php';
$accounts = new GetAllAccounts;
print "n";
$accounts = GetAllAccounts::run($service, MAX_LIST_PAGE_SIZE);
if(isset($accounts) && !empty($accounts))
{
// Get an example account ID, so we can run the following sample.
$exampleAccountId = $accounts[0]['id'];
//GetAccountTree::run($service, $exampleAccountId);
$adClients = GetAllAdClients::run($service, $exampleAccountId, MAX_LIST_PAGE_SIZE);
$bullets = str_repeat('#', 80) . "n";
if(isset($adClients) && !empty($adClients))
{
foreach($adClients as $exampleAdClient)
{
// Get an ad client ID (the last one), so we can run the rest of the samples.
//$exampleAdClient = end($adClients); // to get the first ID use: $adClients[0];
$exampleAdClientId = $exampleAdClient['id'];
print $bullets;
print "AdClient: ".$exampleAdClientId." - ".$exampleAdClient['productCode']."n";
print $bullets;
$adUnits = GetAllAdUnits::run($service, $exampleAccountId, $exampleAdClientId, MAX_LIST_PAGE_SIZE);
if(isset($adUnits) && !empty($adUnits))
{
// Get an example ad unit ID, so we can run the following sample.
//$exampleAdUnitId = $adUnits[0]['id'];
//GetAllCustomChannelsForAdUnit::run($service, $exampleAccountId, $exampleAdClientId, $exampleAdUnitId, MAX_LIST_PAGE_SIZE);
}
else{
print 'No ad units found, unable to run dependant example.n';
}

/*
$customChannels = GetAllCustomChannels::run($service, $exampleAccountId, $exampleAdClientId, MAX_LIST_PAGE_SIZE);
if(isset($customChannels) && !empty($customChannels))
{
// Get an example ad unit ID, so we can run the following sample.
$exampleCustomChannelId = $customChannels[0]['id'];
GetAllAdUnitsForCustomChannel::run($service, $exampleAccountId, $exampleAdClientId, $exampleCustomChannelId, MAX_LIST_PAGE_SIZE);
}
else{
print 'No custom channels found, unable to run dependant example.n';
}
*/
//GetAllUrlChannels::run($service, $exampleAccountId, $exampleAdClientId, MAX_LIST_PAGE_SIZE);
GenerateReport::run($service, $exampleAccountId, $exampleAdClientId);
//GenerateReportWithPaging::run($service, $exampleAccountId, $exampleAdClientId, MAX_REPORT_PAGE_SIZE);
//FillMissingDatesInReport::run($service, $exampleAccountId, $exampleAdClientId);
//CollateReportData::run($service, $exampleAccountId, $exampleAdClientId);
}
}
else{
print 'No ad clients found, unable to run dependant examples.n';
}
print $bullets;
print $bullets;
$savedReports = GetAllSavedReports::run($service, $exampleAccountId, MAX_LIST_PAGE_SIZE);
if(isset($savedReports) && !empty($savedReports))
{
// Get an example saved report ID, so we can run the following sample.
$exampleSavedReportId = $savedReports[0]['id'];
GenerateSavedReport::run($service, $exampleAccountId, $exampleSavedReportId);
}
else{
print 'No saved reports found, unable to run dependant example.<br>';
}
//GetAllSavedAdStyles::run($service, $exampleAccountId, MAX_LIST_PAGE_SIZE);
GetAllAlerts::run($service, $exampleAccountId);
}
else{
print 'No accounts found, unable to run dependant examples.n';
}
GetAllDimensions::run($service);
GetAllMetrics::run($service);
}

最新更新