Search code examples
phpcurloauth-2.0fitbitphp-curl

PHP cURL grant type invalid / unsupported


I'm trying to use php and cURL to make requests to the Fitbit oauth 2.0 api. I can get my authorisation code but cannot manage to exchange the code for a token. The Fitbit api docs say (https://dev.fitbit.com/docs/oauth2/#access-token-request) that I need to post code, client id, redirect uri and grant type set to 'authorization_code'.

Howver, I keep getting an error when I print the response.

"errorType":"unsupported_grant_type","message":"The authorization grant_type is not supported. Visit https://dev.fitbit.com/docs/oauth2 for more information on the Fitbit Web API authorization process."}],"success":false}

For the life of me I cannot work out what I am doing wrong with the below code. Any suggestions?

$code = $_GET['code'];
$url = 'https://api.fitbit.com/oauth2/token';

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
 'code=' . $code . '&' .
 'client_id=' . $oauth2_client_id . '&' .
 'redirect_uri=' . $oauth2_redirect . '&' .
 'grant_type=authorization_code'
                                            )
  );

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Authorization: Basic '. base64_encode($oauth2_client_id.':'.$oauth2_secret),
    'Content-Type: application/x-www-form-urlencoded'
));
$response = curl_exec($curl);
print_r($response);

Solution

  • You're concatenating the POST arguments in to a single string and then include it in an array but they should be individually presented; that can be done in as follows:

    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
     'code' => $code,
     'client_id' => $oauth2_client_id,
     'redirect_uri' => $oauth2_redirect,
     'grant_type' => 'authorization_code'
    )));
    

    See: curl POST format for CURLOPT_POSTFIELDS