通过AdSense API获取广告收益报告并推送到微信/Telegram

本站挂谷歌广告Adsense已经有一段时间了,广告收益不多,有时懒得爬墙上去看报告但心里总是想看一眼,特别在手机上更觉得麻烦,之前想找有没一款app或其他插件能看到收益报告的但没有找到,最近就想研究一下API。
通过搜索找到了Adsense官方API文档(Link),和官方给出的样例(Link),多种语言的都有。尝试了php版的,搭建后只获取了账号ID、客户ID,其他收益报告都没显示出来,一脸懵逼的不知道怎么改。之后在一位博主的文章了找了一段PHP代码(Link),尝试后还是各种报错了。还好博主写得比较明白指明了每个步骤,自己跟着做,多次翻官方文档后猜测是API更新2.0之后很多代码都改了,自己改了一下勉强能自己用的,下面记录一下方法和php代码。
文末晒一下博客2021年的Adsense收入。
前期准备
一个开通了Google AdSense的账号
一个网站服务器和域名
能看一点点看懂基本逻辑的能力,Ctrl C+V的能力,会使用搜索引擎。
1.申請 Google APIs 凭据
首先要先到 Google Cloud Platform 中启用 AdSense Management API。(第一次使用的,要先创建项目)
然后创建凭据(凭据——创建凭据——OAuth客户端ID——类型Web——名称随意——重定向URI填写等下你要搭建的网站域名)。
之后下载密钥(名字client_secret_xxxxxx.json)备用。




2.创建PHP项目
本人使用宝塔,所以在宝塔上演示。
1)安装PHP(需要5.6+,我这里用的5.6),禁用函数里面找到putenv删了(使用composer需要)

2)新建网站,,把官方在github上的PHP样例(Link)上传到网站根目录



3)把第一步在Google Cloud Platform下载的client_secret_xxxxxx.json里面内容复制到client_secrets.json里面
打开宝塔终端,使用 Composer 安装Google APIs 客戶端工具.
/www/server/php/56/bin/php /usr/bin/composer install


4)根目录新建index.php文件
内容填写如下(后面段开始请求是自己瞎编研究半天才终于获取到的数据,只能说能用,不要在意其他格式/语法等等)
打开你的网站,在网页绑定账号即可。
ps:可以考虑给网站添加密码访问,在宝塔面板——网站设置——网站目录里面打开密码访问。
<?php
require_once './vendor/autoload.php';
define('TOKEN_FILENAME', './TOKENFILE.dat', true);
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAuthConfig('./client_secrets.json');
$auth = "";
$access_token = "";
$refresh_token = "";
$service = new Google_Service_Adsense($client);
function gapp_refresh_token($client, $auth) {
$params = array(
"client_id" => $client->getClientId(),
"client_secret" => $client->getClientSecret(),
"refresh_token" => $auth['refresh_token'],
"grant_type" => "refresh_token",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$r = curl_exec($ch);
curl_close($ch);
$g_res = json_decode($r, true);
$access_token = $g_res['access_token'];
$expires_in = $g_res['expires_in'];
$scope = $g_res['scope'];
$auth['access_token']['access_token'] = $access_token;
$auth['access_token']['created'] = time();
$auth['expires_time'] = intval($expires_in) + time() - 30;
file_put_contents(TOKEN_FILENAME, json_encode($auth));
$client->setAccessToken($auth['access_token']);
return $client;
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$refresh_token = $client->getRefreshToken();
file_put_contents(TOKEN_FILENAME, json_encode(array(
'access_token' => $access_token,
'refresh_token' => $refresh_token,
'expires_time' => intval($access_token['expires_in']) + intval($access_token['created']) - 30,
)));
}
if (file_exists(TOKEN_FILENAME) && filesize(TOKEN_FILENAME) > 0) {
$auth = json_decode(file_get_contents(TOKEN_FILENAME), true);
//還沒過期
if (time() < $auth['expires_time']) {
$client->setAccessToken($auth['access_token']);
$access_token = $client->getAccessToken();
} else {
//過期了去刷過
if (isset($auth['refresh_token']) && !empty($auth['refresh_token'])) {
$client = gapp_refresh_token($client, $auth);
} else {
echo '<a class="login" href="' . $client->createAuthUrl() . '">綁定</a>';
exit;
}
}
} else {
echo '<a class="login" href="' . $client->createAuthUrl() . '">綁定</a>';
exit;
}
//到這邊就是授權狀態中,可以開始請求
if (isset($_GET['t'])||isset($_GET['end'])) {
if (isset($_GET['t'])){
$t = $_GET['t'];
}else {
$t = $_GET['end'];
}
} else {
$t = date('Ymd', time());;
}
$Y0 = $Y1 = substr($t,0,4);
$m0 = $m1 = substr($t,4,2);
$d0 = $d1 = substr($t,-2);
if (isset($_GET['from'])) {
$from = $_GET['from'];
$Y1 = substr($from,0,4);
$m1 = substr($from,4,2);
$d1 = substr($from,-2);
}
$optParams = array(
'pageSize' => 5,
'pageToken' => null);
$accounts = $service->accounts->listAccounts($optParams);
$accountId = $accounts[0]['name'];
$optParams = array(
'startDate.year' => $Y1,
'startDate.month' => $m1,
'startDate.day' => $d1,
'endDate.year' => $Y0,
'endDate.month' => $m0,
'endDate.day' => $d0,
"languageCode" => 'zh-cn',
'dimensions' => array('DOMAIN_NAME'),
'orderBy' => '-ESTIMATED_EARNINGS',
'metrics' => array(
'ESTIMATED_EARNINGS', 'PAGE_VIEWS', 'IMPRESSIONS', 'IMPRESSIONS_RPM', 'CLICKS', 'COST_PER_CLICK', 'PAGE_VIEWS_CTR'),
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $optParams);
$dm='';
foreach($report['rows'] as $row) {
$dm = $dm."
<div>------".$row['cells'][0]['value']."------<br>
估算收入:".$row['cells'][1]['value']."<br>
网页浏览量:".$row['cells'][2]['value']."<br>
展示次数:".$row['cells'][3]['value']."<br>
每千次展示收入:".$row['cells'][4]['value']."<br>
点击次数:".$row['cells'][5]['value']."<br>
每次点击费用:".$row['cells'][6]['value']."<br>
网页点击率:".$row['cells'][7]['value']."<br></div>";
};
$html = "<h2>Adsense统计</h2>
时间:".$from."至".$t."<br>
<br>--------------总计--------------<br>
估算收入:".$report['totals']['cells'][1]['value']."<br>
网页浏览量:".$report['totals']['cells'][2]['value']."<br>
展示次数:".$report['totals']['cells'][3]['value']."<br>
每千次展示收入:".$report['totals']['cells'][4]['value']."<br>
点击次数:".$report['totals']['cells'][5]['value']."<br>
每次点击费用:".$report['totals']['cells'][6]['value']."<br>
网页点击率:".$report['totals']['cells'][7]['value']."<br>
<br>----------------详情----------------<br>
".$dm;
echo "<style>div{display: inline-flex; width: 220px; margin: 10px;}</style>";
echo $html;
print "<br>-------------End---666-------------<br>";

5)打开默认是当天收益报告,其他参数
t -- 指定某天的数据 from -- 指定从某天的开始的数据,默认是当天 end -- 指定到某天的结束的数据,默认是当天 如: https://ads.xxx.xxxx/?t=20211001,2021年10月1日的收益报告。 https://ads.xxx.xxxx/?from=20211001,2021年10月1日到今天的收益报告。 https://ads.xxx.xxxx/?from=20211001&end=20211101,2021年10月1日到2021年11月1日的收益报告。
6)代码获取的指标和参数仅按我需求写的,如需添加其他指标,可以文档参考
https://developers.google.com/adsense/management/reference/rest/v2/accounts.reports/generate
使用页面在线调试(Try this API)
然后在修改代码里面的$optParams
$optParams = array(
'startDate.year' => $Y1,
'startDate.month' => $m1,
'startDate.day' => $d1,
'endDate.year' => $Y0,
'endDate.month' => $m0,
'endDate.day' => $d0,
'dimensions' => array('DOMAIN_NAME'),
'orderBy' => '-ESTIMATED_EARNINGS',
'metrics' => array(
'ESTIMATED_EARNINGS', 'PAGE_VIEWS', 'IMPRESSIONS', 'IMPRESSIONS_RPM', 'CLICKS', 'COST_PER_CLICK', 'PAGE_VIEWS_CTR'),
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $optParams);3.将报告推送到微信、Telegram
推送微信这里选择pushplus,微信登录后获取到token
Telegram也准备好bot token(Telegram相关学习https://blog.jialezi.net/?post=168)
新建一个corn.php,填写下面代码。
宝塔计划任务新建一个访问url任务(按自己填写)
或手动添加
58 23 * * * /usr/bin/curl "https://ads.xxxx.xxxx/corn.php?pass=123" > /dev/null 2>&1

<?php
//cron.php页
if ($_GET['pass']!='123') { //设置密码
header('HTTP/1.1 403 Forbidden');
exit();
}else{
require('index.php');
function push($url,$params){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result ;
}
//TG
$tgapi='https://api.telegram.org/bot1545138812:AAGroid6uSJFbQxRM2f8X6KHlsnDReHUkvE/sendMessage'; //修改成自己的Token
$code = array("<br>", "</div>", "<div>", "<h2>", "</h2>");
$text = str_replace($code,'',$html);
$tgparams=[
'chat_id'=> '1138220708', //接收的tg账号id
'text'=>$text,
];
//推送到tg,不需要就注释了
push($tgapi,$tgparams);
//pushplus
$pushplus='http://www.pushplus.plus/send';
$params=[
'token'=> '90fc33xxxxxxxxxx', //修改成自己pushplus的Token
'title'=>'Adsense报告', //标题
'content'=>$html,
];
//推送到wx
push($pushplus,$params);
}

4.2021年本博客的Adsense收入
虽然没多少,但能承担服务和域名的费用,足够了。

10月1日到今天

参考:
https://github.com/googleads/googleads-adsense-examples
https://developers.google.com/adsense/management/reference/rest
.



匿名
现在需要加这一句来获取刷新令牌哦
匿名
匿名
crazypeace
昵称获取失败
昵称获取失败