在PHP中使用CURL的POST会产生无效的请求错误

vis*_*hah 4 php post curl oauth google-api

我在使用curl的谷歌帐户下面使用post post方法,但它给了我invalid_request错误.

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf&
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
client_secret=CENSORED&
redirect_uri=http://localhost/oauth2callback&
grant_type=authorization_code
Run Code Online (Sandbox Code Playgroud)

这是我的curl PHP代码

$text ='test';

$URL = "https://accounts.google.com/o/oauth2/token";

$header = array(
"POST /o/oauth2/token HTTP/1.1",
"Host: accounts.google.com",
"Content-type: application/atom+xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache", 
"code=[my_code]&client_id=[my_client_id]&client_secret=[my_client_secret]& redirect_uri=http://localhost/curl_resp.php&grant_type=authorization_code",
"Content-length: ".strlen($text),
);


 $xml_do = curl_init();
 curl_setopt($xml_do, CURLOPT_URL, $URL);
 curl_setopt($xml_do, CURLOPT_CONNECTTIMEOUT, 10);
 curl_setopt($xml_do, CURLOPT_TIMEOUT, 10);
 curl_setopt($xml_do, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($xml_do, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($xml_do, CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($xml_do, CURLOPT_POST, false);
 curl_setopt($xml_do, CURLOPT_POSTFIELDS, $text);
 curl_setopt($xml_do, CURLOPT_HTTPHEADER, $header);
Run Code Online (Sandbox Code Playgroud)

我的请求错误无效

Tra*_*ty3 6

我不知道使用谷歌的OAuth API什么,但从我看过到目前为止的例子中,它看起来像你都应该传递值(即code,client_id在后场中,等),而不是直接HTTP标头.

以下示例仍然无法完全发挥作用,但invalid_request它不会出现错误,而是为您提供invalid_grant.我认为除了我提到的内容之外还有其他问题(也许你需要谷歌或其他东西的新凭据),但这可能会让你更近一步,至少:

$post = array(
    "grant_type" => "authorization_code", 
    "code" => "your_code", 
    "client_id" => "your_client_id", 
    "client_secret" => "your_client_secret", 
    "redirect_uri" => "http://localhost/curl_resp.php"
);

$postText = http_build_query($post);

$url = "https://accounts.google.com/o/oauth2/token";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postText); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($ch);
var_dump($result);    // gets an error, "invalid_grant"
Run Code Online (Sandbox Code Playgroud)

  • 只是为了澄清,通常"invalid_grant"是因为代码:your_code已过期,已撤销或已用于授予access_token(您可以使用它一次);) (2认同)