我该如何卷曲这篇文章?

时间:2015-07-09 11:53:38

标签: php curl google-api access-token

我正在尝试使用以下代码从谷歌api获取访问令牌,

$grant = urlencode("urn:ietf:params:oauth:grant-type:jwt-bearer") . "&assertion=" . $jwtSign;
$postfields = array('Host' => 'www.googleapis.com', 'Content-Type' => 'application/x-www-form-urlencoded', 'POST' => '/oauth2/v3/token HTTP/1.1', 'grant_type' => $grant);

$headers = array(
    "Content-Type: application/x-www-form-urlencoded"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
$result = curl_exec($ch);

但我收到错误说。请帮我解决错误

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

1 个答案:

答案 0 :(得分:0)

grant_type参数的值现在已成为urn:..:jwt-bearer和断言的串联。它们应作为对令牌端点的调用中的单独参数提供。

您还要混合设置标题字段并提供POST参数。

最后,为CURLOPT_POSTFIELDS设置提供数组会使Content-Type更改为multipart/form-data

而是使用:

    $postfields = array(
      'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      'assertion' => $jwtSign
    ); 

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
    $result = curl_exec($ch);