为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
动漫人物 2023-10-22 21:46:51
我正在集成 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);
查看完整描述

1 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

我在您的代码中发现了一些错误并修复了它以使其正常工作:

  1. 对于您使用的 PHP 版本,您需要添加curl_setopt($curls, CURLOPT_RETURNTRANSFER, true);以确保它不仅打印 API 响应而且还返回它

  2. 您需要在 Bearer 和访问令牌之间留一个空格:array('Authorization: Bearer ' .$data['access_token']));

  3. 您尝试调用的示例是错误的,返回日期早于出发日期。我将其更改为一个更简单的示例: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

  4. 在进行 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 专家,我确信代码可以改进。


查看完整回答
反对 回复 2023-10-22
  • 1 回答
  • 0 关注
  • 148 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信