POST using CURL in PHP gives invalid request Error

后端 未结 5 626
花落未央
花落未央 2021-01-19 23:37

I am using below post method for google account using curl but it gives me invalid_request error.

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Con         


        
5条回答
  •  生来不讨喜
    2021-01-19 23:54

    I don't know anything about using Google's oAuth API, but from the examples that I have looked at so far, it looks like you are supposed to pass the values (i.e. code, client_id, etc.) in the post fields, not directly in the HTTP header.

    The following example still doesn't work completely, but instead of getting a invalid_request error, it gives you invalid_grant. I think there is something else wrong in addition to what I've mentioned (perhaps you need new credentials from Google or something), but this might get you one step closer, at least:

    $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"
    

提交回复
热议问题