How to use FedEx API with PHP Examples
Feb 16, 2023ProgrammingComments (5)
Here's a guide on how to get set up with the FedEx API and start making requests. I've included PHP code examples for retrieving tracking data using the Track API, but it can be adapted to any language and other FedEx APIs. This guide assumes you have decent knowledge on handling JSON objects and making HTTP requests.

Create a FedEx Project


You must first sign in at the FedEx Developer site here:
https://developer.fedex.com/api/en-us/home.html

Once signed in, go to My Projects and create a new project. You'll have to indicate what APIs you want to use and accept a few agreements. It may or may not require that you have a FedEx Account Number. For the examples below you should choose the Track API.

With the project created, click the Production Key tab, then follow the prompts to create new API keys. Once done, it will show you the API Key and Secret Key. Save these.

PHP Code Samples


For all the requests I'll be using this basic PHP cURL function:

function fedexRequest($endpoint, $post, $header = null) {
$ch = curl_init('https://apis.fedex.com/' . $endpoint);
curl_setopt_array($ch, [
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_POSTFIELDS => $post,
]);
if ($header) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
return curl_exec($ch);
}

And these will be the keys used (be sure to insert yours):

$apiKey = 'YOUR_API_KEY';
$secret = 'YOUR_SECRET_KEY';


OAuth Access Token


The first request you have to make is to get the OAuth access token, which is used in subsequent requests:

$post = 'grant_type=client_credentials&client_id=' . $apiKey
. '&client_secret=' . $secret;
$result = fedexRequest('oauth/token', $post);

This should return a JSON object that has an access_token. Validate and parse it as needed. It will also have an expiration timestamp, so you can reuse that access token by storing it in a file or database, which is recommended to reduce API calls.


Make a Request to Track API


With access token available, you can now make a request to get tracking data from FedEx. This requires sending a "payload" in a request with additional headers. It's not as complicated as it sounds.

// The access token from the previous OAuth request
$accessToken = 'ACCESS_TOKEN';

// The tracking number to get information for
$trackNum = 'FEDEX_TRACKING_NUMBER';

// The custom headers to set
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken
];

// The payload as a JSON object (in a PHP string)
$payload = '{
"includeDetailedScans": false,
"trackingInfo": [{
"trackingNumberInfo": {
"trackingNumber": "' . $trackNum . '"
}
}]
}';

// The request with payload as the post body
$result = fedexRequest('track/v1/trackingnumbers', $payload, $header);

The result of this request should be structured JSON with all the relevant information about the requested tracking number.


Full Code Sample


Here's a complete file you can copy-paste and try out. Note that this doesn't handle saving or expiring the access tokens, and has only basic data validation.

// Settings
$apiKey = 'YOUR_API_KEY';
$secret = 'YOUR_SECRET_KEY';
$trackNum = 'FEDEX_TRACKING_NUMBER';

// Get the OAuth access token
$post = 'grant_type=client_credentials&client_id=' . $apiKey
. '&client_secret=' . $secret;
$result = fedexRequest('oauth/token', $post);

// Validate access token
if (strpos($result, '{"access_token":') !== 0) {
exit('FedEx API Auth Failed: ' . $result);
}
$json = json_decode($result, true);
if (!$json || empty($json['access_token'])) {
exit('FedEx API Auth Decode Failed: ' . $result);
}

// Get the Track API response
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $json['access_token']
];
$payload = '{
"includeDetailedScans": false,
"trackingInfo": [{
"trackingNumberInfo": {
"trackingNumber": "' . $trackNum . '"
}
}]
}';
$result = fedexRequest('track/v1/trackingnumbers', $payload, $header);

// Validate the response
if (strpos($result, '{"transactionId":') !== 0) {
exit('FedEx API Track Failed: ' . $result);
}
$json = json_decode($result, true);
if (!$json || empty($json['output'])) {
exit('FedEx API Track Decode Failed: ' . $result);
}

// Output the results
echo '<pre>';
print_r($json);
echo '</pre>';

// Helper function
function fedexRequest($endpoint, $post, $header = null) {
$ch = curl_init('https://apis.fedex.com/' . $endpoint);
curl_setopt_array($ch, [
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_POSTFIELDS => $post,
]);
if ($header) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
return curl_exec($ch);
}
Comments (5)
Add a Comment
Ian   Dec 03, 2023
How do you code the payload to request the POD details?
Nick   Mar 25, 2023
There is a way to have it do multiple tracking numbers in a single request. I'm sorry but I don't have that information handy at the moment. The FedEx dev docs do cover it though.
Lew   Mar 25, 2023
How would adjust the payload to track multiple tracking numbers, without looping through it multiple times?
Nick   Mar 04, 2023
It's not a WordPress theme; it's just plain PHP. If you wanted to integrate this into a WordPress site, that would be very dependent on how you wanted to use it, and where. You can add PHP to a custom plugin or theme, or functions.php, among other places.
Karim   Mar 04, 2023
Can i ask you a question, What wordpress theme is that ?