php对接谷歌admob广告收益reporting api分享

今天收到需求,需要对接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,这里我们用到的是美元,
大家根据自己的需要修改一下

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/535902.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的危险物品检测系统(深度学习模型+PySide6界面+训练数据集+Python代码)

摘要:本文深入介绍了一个采用深度学习技术的危险物品识别系统,该系统融合了最新的YOLOv8算法,并对比了YOLOv7、YOLOv6、YOLOv5等早期版本的性能。该系统在处理图像、视频、实时视频流及批量文件时,能够准确识别和分类各种危险物品…

聊聊测试左移到开发阶段

这是鼎叔的第九十一篇原创文章。行业大牛和刚毕业的小白,都可以进来聊聊。 欢迎关注本公众号《敏捷测试转型》,星标收藏,大量原创思考文章陆续推出。本人新书《无测试组织-测试团队的敏捷转型》已出版(机械工业出版社&#xff09…

两个笔记本如何将一个笔记本作为另一个笔记本的拓展屏

需求是有两个笔记本,一个笔记本闲置,另一个笔记本是主力本。想将另一个闲置的笔记本连接到主力本上作为拓展屏使用。网上搜了好久,有一些人提到了,也有一些视频但是文章比较少。简单总结一下吧 上述需求有两种方式 第一种&#x…

2024.3.13

1、 #include <iostream>using namespace std; class Per { private:string name;int age;double *hight;double *weight; public:void show(){cout << "姓名&#xff1a;" << name << endl;cout << "年龄&#xff1a;" &l…

改进沙猫群优化的BP神经网络ISCSO-BP(时序预测)的Matlab实现

改进沙猫群优化的BP神经网络&#xff08;ISCSO-BP&#xff09;是一种结合了改进的沙猫群优化算法&#xff08;Improved Sand Cat Swarm Optimization, ISCSO&#xff09;和反向传播&#xff08;Back Propagation, BP&#xff09;神经网络的模型&#xff0c;旨在提高时序预测的准…

python的函数与类的定义

目录 1.函数 1.函数的定义 2.输入参数与输出参数的类型 3.输入和输出多个参数 1.普通参数 2.含有任意数量的参数 3.关键字参数 4.普通参数与多个参数的结合 2.类 1.类的定义 2.类的实例化 3.继承 1.函数 1.函数的定义 def 函数名(输入参数): 文档字符串 函数体 …

brew安装node和nvm切换和管理node版本

Homebrew是一款Mac OS平台下的软件包管理工具&#xff0c;拥有安装、卸载、更新、查看、搜索等很多实用的功能。简单的一条指令&#xff0c;就可以实现包管理&#xff0c;而不用你关心各种依赖和文件路径的情况&#xff0c;十分方便快捷。简单来说&#xff0c;Homebrew提供 App…

C#无法给PLC写入数据原因分析

一、背景 1.1 概述 C#中无法给PLC写入数据的原因有很多&#xff0c;这里分享网络端口号被占用导致无法写入的确认方法 1.2 环境 ①使用三菱PLC ②C#通过网口与PLC进行通讯 二、现象 1.1 代码 通过HslCommunication连接PLC时&#xff0c;连接返回成功&#xff0c;写入返回失败 …

(003)SlickEdit Unity的补全

文章目录 步骤XML知识点 附录 步骤 1.下载 unity 源码。 2.将自定义文件 MonoBehaviour.cs 放到解压后的项目里面&#xff1a; using System;namespace UnityEngine {public partial class MonoBehaviour{public virtual void Awake(){throw new NotImplementedException();…

AI知识库也太方便了吧,中小型企业都要知道它!

生活在这个信息爆炸的时代&#xff0c;信息的获取变得前所未有的方便&#xff0c;但随之而来的却是信息筛选和管理的难题。对于中小型企业来说&#xff0c;如何有效运用自身积累的各类信息&#xff0c;直接影响着企业的运营效率和市场竞争力。而这&#xff0c;正是AI知识库可以…

Java毕业设计-基于spring boot开发的实习管理系统-毕业论文+答辩ppt(附源代码+演示视频)

文章目录 前言一、毕设成果演示&#xff08;源代码在文末&#xff09;二、毕设摘要展示1.开发说明2.需求分析3、系统功能结构 三、系统实现展示1、前台功能模块2、后台功能模块2.1 管理员功能2.2 教师功能2.3 学生功能2.4 实习单位功能 四、毕设内容和源代码获取总结 Java毕业设…

30天学会QT(进阶)--------------第二天(创建项目)

1、如何规范的创建一个项目 由于本人也是从其他的项目上学来的&#xff0c;所以也不算是业界规范&#xff0c;每个公司或者个人都有自己的方式去创建项目&#xff0c;项目的创建是本着简洁&#xff0c;明了&#xff0c;方便而言的&#xff0c;所以对于我来说&#xff0c;不繁琐…