无法授权使用OAuth(Google API)

时间:2015-07-02 23:33:10

标签: curl oauth oauth-2.0 google-oauth google-analytics-api

我尝试使用Curl来授权使用Oauth,但我没有得到"必需参数:grant_type"来自Google的回复。谁能告诉我我的代码有什么问题?

$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: www.googleapis.com', 'Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('client_id' => 'xxxxxxxxxxx.apps.googleusercontent.com', 'client_secret' => 'xxxxxxxxxx', 'refresh_token' => $auth->refresh_token, 'grant_type' => 'refresh_token'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

1 个答案:

答案 0 :(得分:1)

您将数组传递给CURLOPT_POSTFIELDS,这会导致内容类型设置为multipart/form-data,因为它是在CURLOPT_HTTPHEADER选项之后应用的。您需要首先将http_build_query应用于数组,这将导致内容类型为application/x-www-form-urlencoded。所以使用:

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('client_id' => 'xxxxxxxxxxx.apps.googleusercontent.com', 'client_secret' => 'xxxxxxxxxx', 'refresh_token' => $auth->refresh_token, 'grant_type' => 'refresh_token')));