POST using CURL in PHP gives invalid request Error

后端 未结 5 607
花落未央
花落未央 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-20 00:01

    I was also having the same problem, where google returns an "invalid_xxx".

    After much researching and troubleshooting, the problem lies with the encoding of the form itself! Do not use function 'http_builder_query', as it messses up the string and google cannot 'recognise' it. Example :

    http_builder_query Output : "code=4%252FYYUT71KJ6..."

    compared to

    just a normal string : "code=4/YYUT71KJ6..."

    Here is my working code, where i have placed 'x' in the locations that needs your own data (taken and modified from google oauth authentication)

        $code_from_user_login = "4/YYUT71KJ6....";
        $ch = curl_init();
    
            curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    
    
            $post_params = "code=" . $code_from_user_login . "&";
            $post_params .= "redirect_uri=http://www.x.com/&";
            $post_params .= "client_id=x.apps.googleusercontent.com&";
            $post_params .= "client_secret=x&";
            $post_params .= "grant_type=authorization_code&";
    
    
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
            $result = curl_exec($ch);
            print($result);
    

    The result will be like :

      '{
      "access_token" : "ya29.AHES6ZSwJSHpTZ1t....",
      "token_type" : "Bearer",
      "expires_in" : 3599,
      "id_token" : "eyJhbGciOiJSUzI1NiIsImtpZCI6IjU0MDQxOTZlMmQzOGNjYTA2MW...."
    }'
    

    Once you have the 'access_token', access the profile data with this url : https://www.googleapis.com/oauth2/v1/userinfo?access_token=YOUR_ACCESS_TOKEN_HERE

    ~ end ~

提交回复
热议问题