【发布时间】:2020-03-24 13:05:35
【问题描述】:
我正在开发用于从谷歌分析帐户获取额外数据的模块。要获取此数据,Google 需要 access_token。 这就是我到目前为止所管理的
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" => "559825975819-881lg83vs8feo70v5unqa8kfoijuvfnn.apps.googleusercontent.com",
"client_secret" => "vj4UNNItAJocX4RkNaD_3DQ4",
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"access_type" => "offline",
"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);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$data = (json_decode($output, true));
$access_token_var = $data['access_token'];
echo $access_token_var;
} else {
$url = "https://accounts.google.com/o/oauth2/auth";
$params = array(
"response_type" => "code",
"client_id" => "559825975819-881lg83vs8feo70v5unqa8kfoijuvfnn.apps.googleusercontent.com",
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"scope" => "https://www.googleapis.com/auth/analytics",
"access_type" => "offline",
"approval_prompt" => "force"
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
我得到了 access_token,它在需要的变量中回显。但是我想在后台获取分析附加数据(例如,当客户下订单并点击订单按钮时),但每次我需要新的access_token时,我都需要用我的google帐户授权,因此,网站上的每个客户都需要为此,尽管我设置了“access_type”=>“offline”。怎么了?还是我的 API 应用有问题?
【问题讨论】:
-
可能是 Google 仅在用户第一次授予应用程序访问他的帐户时才返回刷新令牌。您可以尝试撤销批准(在您的 Google 帐户中),然后再次批准申请。
标签: php google-analytics access-token