获取谷歌API的访问令牌

时间:2017-05-19 07:27:16

标签: php curl google-api

我希望通过客户端ID和客户端密钥从谷歌API访问令牌。 但它显示出以下错误。我在这里传递grant_type参数,如果我在这里打印数组,它也会显示grant_type。

我也启用了 API访问

错误: -

{
  "error" : "invalid_request",
  "error_description" : "Required parameter is missing: grant_type"
}

代码: -

$url = "https://accounts.google.com/o/oauth2/token";
// $headers = array('Content-Type:Content-Type' => 'application/json');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded'    
));

curl_setopt($ch, CURLOPT_POST, true);

$client_id = "asdasdasdsadadasd.apps.googleusercontent.com";
$client_secret = "Wasdadsasdadasd";
$redirect_uri = "http://localhost/test/google_drive.php";
$code = "asdasdsad";

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
  'grant_type' => "authorization_code",
  'code' => $code,
  'client_id' => $client_id,
  'client_secret' => $client_secret,
  'redirect_uri' => $redirect_uri
));

$output = curl_exec($ch);
curl_close($ch);

如果我直接使用curl,那么它也会向我显示此错误。

curl -d "code=AUHROISATON_CODE&client_id=CLIENT_ID.apps.googleusercontent.com&client_secret=CLINET_SECRET&redirect_uri=http://www.example.com&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token

2 个答案:

答案 0 :(得分:2)

将数组传递给CURLOPT_POSTFIELDS表示内容类型变为multipart/form-data - 不确定是否使用CURLOPT_HTTPHEADER正确覆盖了该数组。

尝试删除该标头,然后将http_build_query(array(…))传递给CURLOPT_POSTFIELDS

是的,code参数只能换一次令牌。

答案 1 :(得分:0)

这可能有帮助。看一下这个。这对我有用。

mysql> SELECT @@optimizer_switch\G