如何在curl调用

时间:2017-05-21 08:55:57

标签: php json curl oauth-2.0 uber-api

我从Uber API获取一个访问令牌,它作为以下代码的json输出返回。我面临的问题是我只需要存储在变量中的访问令牌,我需要传递给其他API调用。

我的代码:

<?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);
?>

输出:

{"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 :

我可以看到访问令牌是在json响应中生成的,但我无法将其存储在变量中。

我需要在其他curl调用中传递Access Token,如下所示:

$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);

1 个答案:

答案 0 :(得分:2)

您错过了这个,您需要添加此CURLOPT_RETURNTRANSFER选项,如果您不应用此选项,那么您的$result将导致为空。

curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

所以你的整个代码就像这样

$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);