今天收到需求,需要对接reporting api接口,拉取广告收益回来。网上找到文档开始对接,对接完成了,今天分享给大家一些心得
文档地址:https://developers.google.com/admob/api/v1/reporting?hl=zh-cn#php-client-library
因为接口使用的google OAuth 2.0 授权,所以首先我们要去开发者后台创建一条数据,拿到ClientId,ClientSecret 并下载client_secret.json文件,然后可以开始接入了,下面是示例代码:
#主要是获取accessToken
// Create an AdMob Client.
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/admob.readonly');
$client->setApplicationName('AdMob API PHP Quickstart');
$client->setAccessType('offline');// Be sure to replace the content of client_secrets.json with your developer
// credentials.
$client->setAuthConfig('client_secrets.json');// Create the URL for the authorization prompt.
$authUrl = $client->createAuthUrl();// Once the authorization prompt has been accepted, exchange the
// authorization code for an access and refresh token.
$client->authenticate($_GET['code']);
$client->getAccessToken();
这里有个问题,就是虽然这样可以获取到access_token,但是这里是需要在网页打开authUrl,然后google账号
授权之后,进行一个302跳转之后拿到code,最后在获取到access_token,但是我是想通过脚本去定时获取收益,
所以不可能每次手动去授权,所以这里我们要找到另一个办法获取这个access_token,因为之前接入过google
登录支付,知道有个方法,就是利用refresh_token去拿取access_token,所以现在的问题就是先拿到refresh_token
如何拿取refresh_token?
最常见的一个方法就是利用postman或者curl,或者你熟悉的http工具,创建http请求
地址:https://accounts.google.com/o/oauth2/token
请求方式:post
参数:
grant_type=authorization_code
code=获取到的code(需要看看code中是否有%号,如果有需要urldecode)
client_id=创建api项目是的clientId(客户端ID)
client_secret=创建api项目时的clientSecret(客户端密钥)
这里的参数唯一每次变的就是code这个值,这个值怎么拿呢,我们打印上一步的$authUrl = $client->createAuthUrl();
然后在浏览器访问这个链接,它会进行一次跳转,跳转之后参数里面会有一个code参数,我们拿到之后就可以请求了,
记住首次请求才会返回refresh_token,这个时候我们需要记住保存,如果忘记保存,也有办法,这个可自行查阅
通过refresh_token 换取access_token
拿到这个值之后,那我们就可以通过它去拿到access_token了
$post_data = ['refresh_token' => self::RefreshToken,'client_id' => self::ClientId,'client_secret' => self::ClientSecret,'grant_type' => 'refresh_token',];$request_uri = 'https://www.googleapis.com/oauth2/v4/token';$client = new Client();$response = $client->request('POST', $request_uri, ['json' => $post_data]);$result = json_decode($response->getBody()->getContents(), true);Redis::setex('google_api_access_token', 3600, $result['access_token']);$access_token = $result['access_token'];
获取广告收益
参数都有了,现在我们就可以拿取广告收益了
$client = new \Google_Client();$client->addScope(['https://www.googleapis.com/auth/admob.readonly', 'https://www.googleapis.com/auth/admob.report']);$json_file = dirname(__FILE__) . '/lib/admob/client_secret.json';#$client->setAccessType('offline');$client->setAuthConfig($json_file);#自己封装一个获取token方法$access_token = $this->get_access_token();$client->setAccessToken($access_token);$service = new \Google_Service_AdMob($client);$now_time = strtotime($date);#设置日期$startDate = new \Google_Service_AdMob_Date();$startDate->setYear(date('Y', $now_time));$startDate->setMonth(date('m', $now_time));$startDate->setDay(date('d', $now_time));$endDate = new \Google_Service_AdMob_Date();$endDate->setYear(date('Y', $now_time));$endDate->setMonth(date('m', $now_time));$endDate->setDay(date('d', $now_time));#AccountName 是后台的项目ID 能通过一个获取所有的$result = get_object_vars(self::run($service, self::AccountName, $startDate, $endDate));
public static function run($service, $accountName, $startDate, $endDate){// Generate mediation report.$mediationReportRequest = self::createMediationReportRequest($startDate, $endDate);$mediationReportResponse = $service->accounts_mediationReport->generate($accountName,$mediationReportRequest);// Convert mediation report response to a simple object.$mediationReportResponse = $mediationReportResponse->tosimpleObject();// Print each record in the report.return $mediationReportResponse ?: [];}/*** 这个方法主要是设置我们的一些配置和一些维度的参数等等* Generates a mediation report request.*/public static function createMediationReportRequest($startDate, $endDate){/** AdMob API only supports the account default timezone and* "America/Los_Angeles", see* https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.mediationReport/generate* for more information.*/// Specify date range.$dateRange = new \Google_Service_AdMob_DateRange();$dateRange->setStartDate($startDate);$dateRange->setEndDate($endDate);$localization = new \Google_Service_AdMob_LocalizationSettings();$localization->setCurrencyCode('USD');$reportSpec = new \Google_Service_AdMob_MediationReportSpec();$reportSpec->setMetrics(['CLICKS', 'AD_REQUESTS', 'ESTIMATED_EARNINGS', 'IMPRESSIONS', 'MATCHED_REQUESTS']);$reportSpec->setDimensions(['APP', 'PLATFORM', 'AD_SOURCE', 'DATE', 'FORMAT']);$reportSpec->setDateRange($dateRange);$reportSpec->setLocalizationSettings($localization);// Create mediation report request.$mediationReportRequest = new \Google_Service_AdMob_GenerateMediationReportRequest();$mediationReportRequest->setReportSpec($reportSpec);return $mediationReportRequest;}
最后获取到返回的信息之后,因为收益他的单位不一样,我们需要将它转成我们需要到金额$metricValues[‘ESTIMATED_EARNINGS’][‘microsValue’] / 1000000,这里我们用到的是美元,
大家根据自己的需要修改一下