Error in Fedex Rates API Implementation in PHP

148 Views Asked by At

I've following code in PHP for "Fedex Rates and Transit Times API" using file_get_contents() function. I'm using valid access token value and valid account ID and it is working fine in Postman, but when I implement in PHP code, I get the following error:

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

There are 1 best solutions below

4
PHP Developer On

As per PHP official manual, you should join all header values with \r\n instead of comma. For example:

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

screenshot here

You can learn more from PHP official manual:

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

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