OAuth 2.0 in php using curl

前端 未结 1 1196
野性不改
野性不改 2021-01-01 00:23

I need to get my access_token and refresh_token for OAuth 2.0 to Access Google APIs, the php script below should return a json with access_token, refresh_token like this:

相关标签:
1条回答
  • 2021-01-01 01:15

    Wow, stupid mistake, I should have a rest.

    The variables names don't match. I defined:

        $client_id = '###.apps.googleusercontent.com';
        $client_secret = '###';
    

    But here I used an non-existing clientID and clientSecret :

        curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'code' => $code,
        'client_id' => $clientID,
        'client_secret' => $clientSecret,
        'redirect_uri' => $redirect_uri,
        'grant_type' => 'authorization_code'
        ));
    

    Fixed and working PHP script

        $client_id = '###.apps.googleusercontent.com';
        $redirect_uri = 'http://localhost/phpConnectToDB/csv/refreshFusionTable.php';
        $client_secret = '###';
    
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
        
        curl_setopt($ch, CURLOPT_POST, TRUE);
        
        $code = $_REQUEST['code'];
    
        // This option is set to TRUE so that the response
        // doesnot get printed and is stored directly in
        // the variable
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'code' => $code,
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri' => $redirect_uri,
        'grant_type' => 'authorization_code'
        ));
    
        $data = curl_exec($ch);
        
        var_dump($data);
    

    But I have to say that google provides a little misleading error message here, because I hadn't defined client_id nor client_secret and the error message was:

        {
        "error" : "invalid_request",
        "error_description" : "Client must specify either client_id or client_assertion, not both"
        }
    
    0 讨论(0)
提交回复
热议问题