Sandy505 Sandy505 -4 years ago 165
JSON Question

How to access the Uber API OAuth 2.0 bearer token in curl calls

I am getting a Access Token from the Uber API which is returned as json output of the below code. The problem i am facing is i need only the access token stored in variable which i need to pass on my other API calls.

My Code :

<?php
$fields_string = '';
$fields = array(
'client_secret' => 'xxxxxxxxxxx',
'client_id' => 'xxxxxxxxxx',
'grant_type' => 'authorization_code',
'redirect_uri' => "xxxxxxxxx",
'code' => $_GET['code']
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, "https://login.uber.com/oauth/v2/token");
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

$result = curl_exec($ch);
$responseData = json_decode($result , TRUE);
$access_token = $responseData["access_token"];
echo "Access Token :" . $access_token ;
curl_close($ch);
?>


Output:

{"last_authenticated":0,"access_token":"QW.eyJ2FD6546754GGF6IktmczloQWo2VDJpb1gwWHVjUWVTdEE9PSIsImV4cGlyZXNfYXQiOjE0OTc5NDgwMTksInBpcGVsaW5lX2tleV9pZCI6Ik1RPT0iLCJwaXBlbGluZV9pZCI6MX0.v95QyTqyK0PPEpG1MlBtYq8-hYU44TX#GFGFGFGEUuFI","expires_in":2592000,"token_type":"Bearer","scope":"history history_lite places profile ride_widgets","refresh_token":"#$HGHG.CAESEBhoHMvuTUNUu3QXwd9hJ_kiATEoATIBMQ.aqfiFhkCA21MCOmhf92kqj_pIlMNcyKHMQ-2fImMdWI.w_s3tB3xnxpq826UXUtUsmuneDh1bvcEfdfdvC5JXU"}Access Token :


I can see the Access Token is generated in the json response but i am unable to store it in a variable.

I need to pass the Access Token in other curl call as below :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.uber.com/v1.2/history");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization', 'OAuth '+$atoken));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$curl_response = curl_exec($ch);
print_r($curl_response);
curl_close($ch);

Answer Source

You are missing this, You need to add this CURLOPT_RETURNTRANSFER option, If you do not apply this then your $result will result in null.

curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

So your whole code will be like this

$ch = curl_init();   
curl_setopt($ch,CURLOPT_URL, "https://login.uber.com/oauth/v2/token");
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);//add this to your code.

$result = curl_exec($ch);
$responseData = json_decode($result , TRUE);
$access_token = $responseData["access_token"];
echo "Access Token :" . $access_token ;
curl_close($ch);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download