...

View Full Version : Having trouble with FedEx API tracking



cyphix
06-16-2010, 11:19 PM
I am having a heck of a time getting the correct responses returned from the FedEx API when trying to track a package.

I have tried several different things to get it working but when I get a response back from FedEx it always say's the tracking number is invalid..... which is untrue.

I have even tried a 3rd party script called FedExDC.... while this works on SOME numbers, it doesn't work with others.

Here is some of the code I have tried..



// Copyright 2009, FedEx Corporation. All rights reserved.
// Version 4.0.0

require_once('../library/fedex-common.php5');


//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "../../TrackService_v4.wsdl";

//Set commonly used variables in fedex-common.php5. Set check to true.
if(setDefaults('check'))
{
$key=setDefaults('key');
$password=setDefaults('password');
$shipAccount=setDefaults('shipaccount');
$meter=setDefaults('meter');
$billAccount=setDefaults('billaccount');
$dutyAccount=setDefaults('dutyaccount');
}
//Set commonly used variables below. Set check to false.
else
{
$key='xxxxxxxxxxxxxxx';
$password='xxxxxxxxxxxxxxxxxxxxxxx';
$shipAccount='xxxxxxxxx';
$meter='xxxxxxxxxxx';
$billAccount='XXX';
$dutyAccount='XXX';
}

ini_set("soap.wsdl_cache_enabled", "0");

$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information

$request['WebAuthenticationDetail'] = array('UserCredential' =>
array('Key' => $key, 'Password' => $password));
$request['ClientDetail'] = array('AccountNumber' => $shipAccount, 'MeterNumber' => $meter);
$request['TransactionDetail'] = array('CustomerTransactionId' => '*** Track Request v4 using PHP ***');
$request['Version'] = array('ServiceId' => 'trck', 'Major' => '4', 'Intermediate' => '0', 'Minor' => '0');
$request['PackageIdentifier'] = array('Value' => xxxxxxxxxx, // Replace 'XXX' with a valid tracking identifier
'Type' => 'TRACKING_NUMBER_OR_DOORTAG');

try
{
$response = $client ->track($request);

if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
printSuccess($client, $response);
}
else
{
printError($client, $response);
}

writeToLog($client); // Write to log file

} catch (SoapFault $exception) {
printFault($exception, $client);
}


Then in "fedex-common.php5" I have the standard FedEx code..



// Copyright 2009, FedEx Corporation. All rights reserved.

define('TRANSACTIONS_LOG_FILE', '../fedextransactions.log'); // Transactions log file

/**
* Print SOAP request and response
*/
define('Newline',"<br />");

function printSuccess($client, $response) {
echo '<h2>Transaction Successful</h2>';
echo "\n";
printRequestResponse($client);
}
function printRequestResponse($client){
echo '<h2>Request</h2>' . "\n";
echo '<pre>' . htmlspecialchars($client->__getLastRequest()). '</pre>';
echo "\n";

echo '<h2>Response</h2>'. "\n";
echo '<pre>' . htmlspecialchars($client->__getLastResponse()). '</pre>';
echo "\n";
}

/**
* Print SOAP Fault
*/
function printFault($exception, $client) {
echo '<h2>Fault</h2>' . "<br>\n";
echo "<b>Code:</b>{$exception->faultcode}<br>\n";
echo "<b>String:</b>{$exception->faultstring}<br>\n";
writeToLog($client);
}

/**
* SOAP request/response logging to a file
*/
function writeToLog($client){
if (!$logfile = fopen(TRANSACTIONS_LOG_FILE, "a"))
{
error_func("Cannot open " . TRANSACTIONS_LOG_FILE . " file.\n", 0);
exit(1);
}

fwrite($logfile, sprintf("\r%s:- %s",date("D M j G:i:s T Y"), $client->__getLastRequest(). "\n\n" . $client->__getLastResponse()));
}

//To use these defaults set the check to return true.
function setDefaults($var){
if($var == 'shipaccount') Return 'XXX';
/**
* If the billaccount and dutyaccount do not match the shipping account
* the pay type will need to be changed from SENDER in shipping transactions.
*/
if($var == 'billaccount') Return 'XXX';
if($var == 'dutyaccount') Return 'XXX';
if($var == 'meter') Return 'XXX';
if($var == 'key') Return 'XXX';
if($var == 'password') Return 'XXX';
if($var == 'check') Return false;
}

function printNotifications($notes){
foreach($notes as $noteKey => $note){
if(is_string($note)){
echo $noteKey . ': ' . $note . Newline;
}
else{
printNotifications($note);
}
}
echo Newline;
}

function printError($client, $response){
echo '<h2>Error returned in processing transaction</h2>';
echo "\n";
printNotifications($response -> Notifications);
printRequestResponse($client, $response);
}



Thanks for any help...... it is driving me crazy!

CybrMike
01-26-2011, 04:55 AM
Did you ever figure out what was wrong? I am having the same problem and the only info I can find on it is this thread. Please help!!!

cyphix
01-26-2011, 05:20 PM
Hi Mike...... If I recall correctly I basically changed from using SOAP to using XML.

Here are the details below..

This was the OLD code that used SOAP..



function tracking_status_Fedex($tracking_number){

global $fedex;

require_once('inc/fedex-common.php');

$path_to_wsdl = "inc/TrackService_v4.wsdl";

ini_set("soap.wsdl_cache_enabled", "0");



$client = new SoapClient($path_to_wsdl, array('trace' => 1));

$request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $fedex['key'], 'Password' => $fedex['password']));

$request['ClientDetail'] = array('AccountNumber' => $fedex['account_number'], 'MeterNumber' => $fedex['meter_number']);

$request['TransactionDetail'] = array('CustomerTransactionId' => '*** Track Request v4 using PHP ***');

$request['Version'] = array('ServiceId' => 'trck', 'Major' => '4', 'Intermediate' => '0', 'Minor' => '0');

$request['PackageIdentifier'] = array('Value' => $tracking_number, 'Type' => 'TRACKING_NUMBER_OR_DOORTAG');

$request['IncludeDetailedScans'] = 1;

print_r($request);


try{

$response = $client ->track($request);

if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){

return ucwords(strtolower($response -> TrackDetails -> StatusDescription));

}else{

echo 'Error in processing transaction.'. $newline. $newline;

foreach ($response -> Notifications as $notification)

{

if(is_array($response -> Notifications)){

echo $notification -> Severity;

echo ': ';

echo $notification -> Message . $newline;

}else{

echo $notification . $newline;

}

}

}

}catch(SoapFault $exception){

printFault($exception, $client);

}

}


I changed that part to this..



function tracking_status_Fedex($tracking_number){

global $fedex;

require_once('inc/fedex-common.php5');

$path_to_wsdl = "inc/TrackService_v4.wsdl";

// Get XML data that we're sending to the FedEx API into a string
$xmlDocument = file_get_contents('inc/data.xml');

// Set placeholder array for XML data
$ph = array('{key}','{password}','{account_number}','{meter_number}','{tracking_number}');

// Set replacements array for XML data
$rep = array($fedex['key'], $fedex['password'], $fedex['account_number'], $fedex['meter_number'], $tracking_number);

// Do replacements
$xmlDocument = str_replace($ph, $rep, $xmlDocument);

// Make socket connection to FedEx
$response = postXMLtoURL("ssl://gateway.fedex.com", "/xml", $xmlDocument);

if ($response !== false) {

// Attempt to get some info on the response we got back
$package_info = package_info($response);

if ($package_info !== false) {

if ($package_info['severity'] != 'FAILURE' and $package_info['severity'] != 'ERROR'){

return ucwords(strtolower($package_info['status']));

} else {

echo 'Error in processing transaction.'. $newline. $newline;

foreach ($response -> Notifications as $notification) {

if (is_array($response -> Notifications)) {

echo $notification -> Severity;

echo ': ';

echo $notification -> Message . $newline;

} else {

echo $notification . $newline;

}

}

}

}

} else {

fsock_fault();

}

}


...and here are some of the used functions it uses:



function postXMLToURL($server, $path, $xmlDocument) {

$contentLength = strlen($xmlDocument);

$fp = fsockopen($server, 443);

if ($fp !== false) {

fputs($fp, "POST $path HTTP/1.0\r\n");
fputs($fp, "Referer: YourReferer\r\n");
fputs($fp, "Host: $server\r\n");
fputs($fp, "Port: 443\r\n");
fputs($fp, "Accept: image/gif, image/jpeg, image/pjpeg, text/plain, text/html, */*\r\n");
fputs($fp, "Content-Type: image/gif\r\n");
fputs($fp, "Content-Length: $contentLength\r\n\r\n");
//fputs($fp, "Connection: close\r\n");
//fputs($fp, "\r\n"); // all headers sent
fputs($fp, $xmlDocument);

$result = '';
$header = "not yet";

// Make up data without headers

while(!feof($fp)) {

$line = fgets($fp, 1024);

if ($line == "\r\n" and $header == "not yet") {
$header = "passed";
continue;
}

if ($header == "passed") {
$result .= $line;
}

}

// Return data
return $result;

} else {

return false;

}

}

/* Retrieves some package info out of the FedEx XML response & returns it */

function package_info($response) {

// Get tracking request result
preg_match('~<v4:HighestSeverity>([^<]+)</v4:HighestSeverity>~iU', $response, $severity);

// Get tracking status
preg_match('~<v4:StatusDescription>([^<]+)</v4:StatusDescription>~iU', $response, $status);

if (!empty($severity) and !empty($status)) {

// Make an array with data to return
$data['severity'] = strip_tags($severity[1]);
$data['status'] = strip_tags($status[1]);

return $data;

} else {

return false;

}

}


Lastly..... here is the contents of the XML file that I use as the template:



<?xml version='1.0'?>
<ns:TrackRequest xmlns:ns="http://fedex.com/ws/track/v4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://fedex.com/ws/track/v4 TrackService_v4.xsd ">
<ns:WebAuthenticationDetail>
<ns:UserCredential>
<ns:Key>{key}</ns:Key>
<ns:Password>{password}</ns:Password>
</ns:UserCredential>
</ns:WebAuthenticationDetail>
<ns:ClientDetail>
<ns:AccountNumber>{account_number}</ns:AccountNumber>
<ns:MeterNumber>{meter_number}</ns:MeterNumber>
</ns:ClientDetail>
<ns:TransactionDetail>
<ns:CustomerTransactionId>User Customizable Field</ns:CustomerTransactionId>
</ns:TransactionDetail>
<ns:Version>
<ns:ServiceId>trck</ns:ServiceId>
<ns:Major>4</ns:Major>
<ns:Intermediate>0</ns:Intermediate><ns:Minor>0</ns:Minor>
</ns:Version>
<ns:PackageIdentifier>
<ns:Value>{tracking_number}</ns:Value>
<ns:Type>TRACKING_NUMBER_OR_DOORTAG</ns:Type>
</ns:PackageIdentifier>
<ns:IncludeDetailedScans>true</ns:IncludeDetailedScans>
</ns:TrackRequest>


Hope this helps you! :)

CybrMike
01-26-2011, 06:13 PM
Thank you so much!! This saved me bigtime! Been pounding my head on the wall for 3 days now. Your changes work great!

cyphix
01-26-2011, 08:08 PM
No problems at all - Glad it helped you. :) I remember that wall all too well!

anands
01-27-2011, 06:12 AM
Hi,

I have used these steps, still I can't get response.
The return value is,
"prof1000Authentication Failed
User Customizable Field".
I have used test account and original shipped tracking number. When I tried to track on fedex.com, it working well. But by using API I can't get response. Please help me out from this. :confused:
Thank you in advance.

anands
01-27-2011, 07:35 AM
Hi,

I have used these steps, still I can't get response.
The return value is,
"prof1000Authentication Failed
User Customizable Field".
I have used test account and original shipped tracking number. When I tried to track on fedex.com, it working well. But by using API I can't get response. Please help me out from this. :confused:
Thank you in advance.

I am getting return error from API, here you go.

"Severity: FAILURE
Source: trck
Code: 9045
Message: Sorry, we are unable to process your tracking request. Please retry later, or contact Customer Service at 1.800.Go.FedEx(R) 800.463.3339.
LocalizedMessage: Sorry, we are unable to process your tracking request. Please retry later, or contact Customer Service at 1.800.Go.FedEx(R) 800.463.3339 "

Please help on this.

cyphix
01-27-2011, 11:32 AM
Hi..... I'm not sure if I can help you as the changes I made were just to fix problems with certain numbers that were returning false negative responses.

It seems you have some kind of other problem with your script.

anands
01-31-2011, 06:08 AM
Thank you! Cyphix..

I have used FedEx developer script only, but I got those errors.I think should check my script again.
Thanks for your assistance. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum