![](/img/trans.png)
[英]Google Ads API - How to get the access and referesh token using PHP
[英]Google API Access Token PHP
我正在验证Google Analytics(分析)帐户并成功检索数据。 但是,我想每周运行一次cronjob以从经过身份验证的帐户获取数据,但是访问令牌无效。
我已经阅读了有关刷新令牌的一些内容,但不确定如何使用它们。 我应该在我的数据库中存储什么数据以随时访问经过身份验证的帐户?
要获取访问令牌和刷新令牌,请首先创建一个包含以下代码的文件:
<?php
if (isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token';
$params = array(
"code" => $code,
"client_id" => YOUR_CLIENT_ID,
"client_secret" => YOUR_CLIENT_SECRET,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] === 200) {
header('Content-Type: ' . $info['content_type']);
return $output;
} else {
return 'An error happened';
}
} else {
$url = "https://accounts.google.com/o/oauth2/auth";
$params = array(
"response_type" => "code",
"client_id" => YOUR_CLIENT_ID,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"scope" => "https://www.googleapis.com/auth/plus.me"
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
然后,用您的客户ID和客户密码替换YOUR_CLIENT_ID
和YOUR_CLIENT_SECRET
。
确保您的范围正确。 例如,如果要访问Analytics(分析),则应为https://www.googleapis.com/auth/analytics
。
如果运行此代码,则应获得OAuth2批准屏幕。 现在,按Accept
,您将得到如下所示的结果:
{
"access_token" : YOUR_ACCESS_TOKEN,
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : YOUR_REFRESH_TOKEN
}
结果可能包含其他字段,具体取决于您要申请的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.