PHP 中的 Fedex Rates API 实现错误

问题描述 投票:0回答:1

我使用 file_get_contents() 函数在 PHP 中跟踪了“Fedex 费率和运输时间 API”的代码。 我使用有效的访问令牌值和有效的帐户 ID,它在 Postman 中工作正常,但是当我在 PHP 代码中实现时,出现以下错误:

 *Warning: file_get_contents(https://apis-sandbox.fedex.com/rate/v1/rates/quotes): Failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized*

<?php
$url = "https://apis-sandbox.fedex.com/rate/v1/rates/quotes";

    

    $rawdatajson = '{
  "accountNumber": {
    "value": "XXXXX7020"
  },
  "requestedShipment": {
    "shipper": {
      "address": {
        "postalCode": 65247,
        "countryCode": "US"
      }
    },
    "recipient": {
      "address": {
        "postalCode": 75063,
        "countryCode": "US"
      }
    },
    "pickupType": "DROPOFF_AT_FEDEX_LOCATION",
    "serviceType": "FEDEX_2_DAY",
    "rateRequestType": [
      "PREFERRED"
    ],
    "preferredCurrency": "CAD",
    "requestedPackageLineItems": [
      {
        "weight": {
          "units": "LB",
          "value": 10
        }
      }
    ]
  }
}';

    $data = json_decode($rawdatajson);


    $options = array('http' => array('header' => 'Authorization: Bearer ACESS_TOKEN_HERE', 
        'Content-type: application/x-www-form-urlencoded', 
        'x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281490',
        'x-locale: en_US', 
        'method' => 'POST', 
        'content' => http_build_query($data)
                            ));

    $context = stream_context_create($options);

    $resp_json = file_get_contents($url, false, $context);

    $response_data = json_decode($resp_json);


    var_dump($response_data);
?>
php json api file-get-contents fedex
1个回答
0
投票

根据 PHP 官方手册,您应该使用

header
而不是逗号来连接所有
\r\n
值。例如:

$options = array("http" => array("header" => "Authorization: Bearer ACESS_TOKEN_HERE\r\n" .
        "Content-type: application/x-www-form-urlencoded\r\n" . 
        "x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281490\r\n" .
        "x-locale: en_US", 
        "method" => "POST", 
        "content" => http_build_query($data)
                            ));

您可以通过PHP官方手册了解更多信息:

https://www.php.net/manual/en/function.file-get-contents.php

https://www.php.net/manual/en/function.stream-context-create.php

© www.soinside.com 2019 - 2024. All rights reserved.