我一直在遵循 https://developers.google.com/+/web/signin/server-side-flow 的指引,直到我收到授权码发送到我的服务器。然后在 PHP 中,我尝试使用以下代码获取访问令牌:
编辑:似乎当请求令牌是通过服务器端生成而不是通过谷歌按钮生成时,完全相同的PHP代码可以正常工作。
$data = "code=".urlencode(trim($access_code)).
"&grant_type=authorization_code".
"&client_id=".urlencode($this->client_id).
"&client_secret=".urlencode($this->client_secret).
"&redirect_uri=".urlencode(trim($redirect_uri));
$curl = curl_init("https://accounts.google.com/o/oauth2/token");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
return $result;
在PHP中,redirect_uri与Google开发控制台中的redirect uris完全相同,但调用始终返回:
array(1) { ["error"]=> string(21) "redirect_uri_mismatch" }
我做错了什么?
供参考,这是我的 Google API 设置:
http://such-nom.com
http://www.such-nom.com
并且变量作为$redirect_uri传递:
$redir = 'http://such-nom.com';
编辑:似乎当请求令牌是通过服务器端生成而不是通过谷歌按钮生成时,完全相同的PHP代码可以正常工作。
http_build_query
)-否则可能会产生问题,特别是如果这些值包含具有特殊含义的字符,如&
。 - CBroe