在curl php中传递access_token时Amadeus Flight搜索API出现错误

我正在集成 amadeus 航班搜索 api,但在使用 access_token 时出现错误。我猜问题出在检索访问令牌?


{ "errors": [ { "code": "38191", "title": "Invalid HTTP header", "detail": "Missing or invalid format for mandatory Authorization header", "status": "401" } ] }

我需要获取从出发地到目的地的所有航班及其价格详细信息。


$curls = curl_init();

curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v1/security/oauth2/token'); 

curl_setopt($curls, CURLOPT_POST, true);

curl_setopt($curls, CURLOPT_POSTFIELDS, "grant_type=client_credentials&client_id=$secretid&client_secret=$secretkey");

curl_setopt($curls, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

$token = curl_exec($curls);

$data = json_decode($token,true);


curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=SYD&destinationLocationCode=BKK&departureDate=2020-10-01&returnDate=2020-08-05&adults=2&includedAirlineCodes=TG&max=3');


curl_setopt($curls, CURLOPT_HTTPHEADER, array('Authorization: Bearer' .$data['access_token']));

$result = curl_exec($curls);

    if (curl_errno($curls)) {

        echo 'Error:' . curl_error($curls);

    }

//print_r ($result);

curl_close ($curls);


动漫人物
浏览 149回答 1
1回答

慕勒3428872

我在您的代码中发现了一些错误并修复了它以使其正常工作:对于您使用的 PHP 版本,您需要添加curl_setopt($curls, CURLOPT_RETURNTRANSFER, true);以确保它不仅打印 API 响应而且还返回它您需要在 Bearer 和访问令牌之间留一个空格:array('Authorization: Bearer ' .$data['access_token']));您尝试调用的示例是错误的,返回日期早于出发日期。我将其更改为一个更简单的示例:https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=EWR&destinationLocationCode=MIA&departureDate=2020-09-10&returnDate=2020-09-17&adults=1&max=1。在进行 API 调用之前,您需要将 更改CURLOPT_POST为 false (因为您尝试调用的 API 是 a GET)下面是完整的示例:$curls = curl_init();curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v1/security/oauth2/token');curl_setopt($curls, CURLOPT_POST, true);curl_setopt($curls, CURLOPT_POSTFIELDS, "grant_type=client_credentials&client_id=$secretid&client_secret=$secretkey");curl_setopt($curls, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));curl_setopt($curls, CURLOPT_RETURNTRANSFER, true);$token = curl_exec($curls);$data = json_decode($token,true);curl_setopt($curls, CURLOPT_URL, 'https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=EWR&destinationLocationCode=MIA&departureDate=2020-09-10&returnDate=2020-09-17&adults=1&max=1');curl_setopt($curls, CURLOPT_POST, false);curl_setopt($curls, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' .$data['access_token']));$result = curl_exec($curls);    if (curl_errno($curls)) {        echo 'Error:' . curl_error($curls);    }print_r ($result);curl_close ($curls);注意:我不是 PHP 专家,我确信代码可以改进。
打开App,查看更多内容
随时随地看视频慕课网APP