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);
?>
As per PHP official manual, you should join all
headervalues with\r\ninstead of comma. For example: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