Jump to content

Need array help for Fedex API


ccchan

Recommended Posts

I'm trying to work on connecting to Fedex to generate a printable shipping label. I've got it almost working but I need the shipper's information to be gathered by a form and then used to generate the label. Here's how the API sets up defining the shipper info:

 

function addShipper(){
$shipper = array(
	'Contact' => array(
		'PersonName' => 'Sender Name',
		'PhoneNumber' => '1234567890'),
	'Address' => array(
		'StreetLines' => array('Address Line 1', '' ),
		'City' => 'Austin',
		'StateOrProvinceCode' => 'TX',
		'PostalCode' => '73301',
		'CountryCode' => 'US')
);
return $shipper;

I want to set the values of this array using $_POST variables like

... 'City' => $_POST['city'] ...

but I get errors that indicate the values don't drop into place like they're supposed to. Can someone explain this to me?

 

THANK YOU!!!!

Link to comment
Share on other sites

It doesn't seem to be a full on "php error" so much as just the value is not coming through.

 

Here's what it shows to let me know that it didn't like what I did

Error returned in processing transaction

Severity: ERROR

Source: ship

Code: 3003

Message: Invalid Shipper state Or Province Code

LocalizedMessage: Invalid Shipper state Or Province Code

 

It shows that for each value that I attempt to fill with a variable. If I were to use 'TX' instead of $_POST['state'] (where it is set as 'TX') it would be fine with it. I am guessing that the error message is generated somewhere on the Fedex server since I can't find the error handling anywhere in the files that I have. 

Link to comment
Share on other sites

why not use rocketshipit to create a label shipment for fedex|USPS|UPS  8)

 

 

require('RocketShip.php');
$shipment = new RocketShipShipment('FedEx');

$shipment->setParameter('toCompany', 'John Doe');
$shipment->setParameter('toPhone', '1231231234');
$shipment->setParameter('toAddr1', '101 W Main');
$shipment->setParameter('toCity', 'Bozeman');
$shipment->setParameter('toState', 'MT');
$shipment->setParameter('toCode', '59715');
$shipment->setParameter('weight', '5');

$shipment->submitShipment();

 

 

Link to comment
Share on other sites

to:darkfreaks

RocketShipit looks like a cool service, but it's not for my own project so I cant make decisions for purchasing licensed solutions.  :shrug:

 

to:Pikachu2000

You mean you want all of the code at play (across 4 files)?

Link to comment
Share on other sites

Ok, great! Here we go.

 

form.html (simple just for the purposes of testing)

<html>
<body>

<form action="label/labelprocessor.php" method="post">
First Name<input type="text" name="first" />
Last Name<input type="text" name="last" />
Phone Number<input type="text" name="phone" />
Street Address<input type="text" name="street" />
Address Line 2<input type="text" name="line2" />
City<input type="text" name="city" />
State<input type="text" name="state" />
Zip Code<input type="text" name="zip" />
Email<input type="text" name="email" />
<input type="submit" />
</form>

</body>
</html> 

 

labelprocessor.php

<?php

$senderName = $_POST["first"]." ".$_POST["last"];
$senderPhone = $_POST["phone"];
$senderStreet = $_POST["street"];
$senderLine2 = $_POST["line2"];
$senderCity = $_POST["city"];
$senderState = $_POST["state"];
$senderZip = $_POST["zip"];
$senderCountry = "US";

echo $senderName; //test to make sure the POST values are coming through. 

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

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


//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "../wsdl/ShipService_v10.wsdl";
$number="336454";
define('SHIP_LABEL', '../shippinglabels/shipexpresslabel'.$number.'.png');  // PNG label file. Change to file-extension .pdf for creating a PDF label (e.g. shiplabel.pdf)

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' => getProperty('key'),
	'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => '*** Express Domestic Shipping Request v10 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'ship',
'Major' => '10',
'Intermediate' => '0',
'Minor' => '0'
);

$request['RequestedShipment'] = array(
'ShipTimestamp' => date('c'),
'DropoffType' => 'REGULAR_PICKUP', // valid values REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER and STATION
'ServiceType' => 'FEDEX_EXPRESS_SAVER', // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
'PackagingType' => 'YOUR_PACKAGING', // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
'TotalWeight' => array('Value' => 1.0, 'Units' => 'LB'), // valid values LB and KG
'Shipper' => addShipper(),
'Recipient' => addRecipient(),
'ShippingChargesPayment' => addShippingChargesPayment(),
'SpecialServicesRequested' => addSpecialServices(),
'LabelSpecification' => addLabelSpecification(),
'RateRequestTypes' => array('ACCOUNT'), // valid values ACCOUNT and LIST
'PackageCount' => 1,
'RequestedPackageLineItems' => array(
	'0' => addPackageLineItem1()
)
);


try
{
if(setEndpoint('changeEndpoint'))
{
	$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}

$response = $client->processShipment($request);  // FedEx web service invocation

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

        // Create PNG or PDF label
        // Set LabelSpecification.ImageType to 'PDF' or 'PNG for generating a PDF or a PNG label
        $fp = fopen(SHIP_LABEL, 'wb');
        fwrite($fp, $response->CompletedShipmentDetail->CompletedPackageDetails->Label->Parts->Image); //Create PNG or PDF file
        fclose($fp);
	echo getProperty('billaccount');
        echo '<h3>This is your printable shipping label.</h3> <strong>For your convenience a copy has been sent to the email address provided.</strong><br /><img src="./'.SHIP_LABEL.'" />';
    }
    else
    {
        printError($client, $response);
    }

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

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

function addShipper(){
$shipper = array(
	'Contact' => array(
		'PersonName' => 'Sender Name', //doesn't process at all if at least this one isn't a text value
		'PhoneNumber' => $senderPhone), 
	'Address' => array(
		'StreetLines' => array($senderStreet, $senderLine2 ),
		'City' => 'Arlington',
		'StateOrProvinceCode' => $senderState,
		'PostalCode' => $senderZip,
		'CountryCode' => 'US')
);
return $shipper;
}
function addRecipient(){
$recipient = array(
	'Contact' => array(
		'PersonName' => 'Processing Department',
		'CompanyName' => 'Money for Old Jewelry',
		'PhoneNumber' => '1-800-234-5678'),
	'Address' => array(
		'StreetLines' => array('Address Line 1'),
		'City' => 'Herndon',
		'StateOrProvinceCode' => 'VA',
		'PostalCode' => '20171',
		'CountryCode' => 'US',
		'Residential' => false)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
	'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
	'Payor' => array(
		'AccountNumber' => getProperty('billaccount'),
		'CountryCode' => 'US')
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
	'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
	'ImageType' => 'PNG',  // valid values DPL, EPL2, PDF, ZPLII and PNG
	'LabelStockType' => 'PAPER_7X4.75');
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
	'SpecialServiceTypes' => array('COD'),
	'CodDetail' => array(
		'CodCollectionAmount' => array('Currency' => 'USD', 'Amount' => 150),
		'CollectionType' => 'ANY')// ANY, GUARANTEED_FUNDS
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
	'SequenceNumber'=>1,
	'GroupPackageCount'=>1,
	'Weight' => array(
		'Value' => 1.0,
		'Units' => 'LB')
);
return $packageLineItem;
}

?>

 

fedex-common.php

<?php

// 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()));
}

/**
* This section provides a convenient place to setup many commonly used variables
* needed for the php sample code to function.
*/
function getProperty($var){
if($var == 'check') Return true;
if($var == 'shipaccount') Return '510087364';
if($var == 'billaccount') Return '510087364';
if($var == 'dutyaccount') Return '510087364';
if($var == 'accounttovalidate') Return '510087364';
if($var == 'meter') Return '100092328';
if($var == 'key') Return 'DELETED';
if($var == 'password') Return 'DELETED';
if($var == 'shippingChargesPayment') Return 'SENDER';
if($var == 'internationalPaymentType') Return 'SENDER';
if($var == 'readydate') Return '2010-05-31T08:44:07';
if($var == 'readytime') Return '12:00:00-05:00';
if($var == 'closetime') Return '20:00:00-05:00';
if($var == 'closedate') Return date("Y-m-d");
if($var == 'pickupdate') Return date("Y-m-d", mktime(8, 0, 0, date("m")  , date("d")+1, date("Y")));
if($var == 'pickuptimestamp') Return mktime(8, 0, 0, date("m")  , date("d")+1, date("Y"));
if($var == 'pickuplocationid') Return 'XXX';
if($var == 'pickupconfirmationnumber') Return '00';
if($var == 'dispatchdate') Return date("Y-m-d", mktime(8, 0, 0, date("m")  , date("d")+1, date("Y")));
if($var == 'dispatchtimestamp') Return mktime(8, 0, 0, date("m")  , date("d")+1, date("Y"));
if($var == 'dispatchlocationid') Return 'XXX';
if($var == 'dispatchconfirmationnumber') Return '00';
if($var == 'shiptimestamp') Return mktime(10, 0, 0, date("m"), date("d")+1, date("Y"));
if($var == 'tag_readytimestamp') Return mktime(10, 0, 0, date("m"), date("d")+1, date("Y"));
if($var == 'tag_latesttimestamp') Return mktime(15, 0, 0, date("m"), date("d")+1, date("Y"));
if($var == 'trackingnumber') Return 'XXX';
if($var == 'trackaccount') Return 'XXX';
if($var == 'shipdate') Return '2010-06-06';
if($var == 'account') Return '510087364';
if($var == 'phonenumber') Return '1234567890';
if($var == 'closedate') Return '2010-05-30';
if($var == 'expirationdate') Return '2012-02-15';
if($var == 'hubid') Return '5531';
if($var == 'begindate') Return '2011-05-20';
if($var == 'enddate') Return '2011-05-31';
if($var == 'address1') Return array('StreetLines' => array('10 Fed Ex Pkwy'),
                                          'City' => 'Memphis',
                                          'StateOrProvinceCode' => 'TN',
                                          'PostalCode' => '38115',
                                          'CountryCode' => 'US');
if($var == 'address2') Return array('StreetLines' => array('13450 Farmcrest Ct'),
                                          'City' => 'Herndon',
                                          'StateOrProvinceCode' => 'VA',
                                          'PostalCode' => '20171',
                                          'CountryCode' => 'US');
if($var == 'locatoraddress') Return array(array('StreetLines'=>'240 Central Park S'),
									  'City'=>'Austin',
									  'StateOrProvinceCode'=>'TX',
									  'PostalCode'=>'78701',
									  'CountryCode'=>'US');
if($var == 'recipientcontact') Return array('ContactId' => 'arnet',
									'PersonName' => 'Recipient Contact',
									'PhoneNumber' => '1234567890');
if($var == 'freightaccount') Return '510087364';
if($var == 'freightbilling') Return array(
	'Contact'=>array(
		'ContactId' => 'freight1',
		'PersonName' => 'Big Shipper',
		'Title' => 'Manager',
		'CompanyName' => 'Freight Shipper Co',
		'PhoneNumber' => '1234567890'
	),
	'Address'=>array(
		'StreetLines'=>array('1202 Chalet Ln', 'Do Not Delete - Test Account'),
		'City' =>'Harrison',
		'StateOrProvinceCode' => 'AR',
		'PostalCode' => '72601-6353',
		'CountryCode' => 'US'
	)
);
}

function setEndpoint($var){
if($var == 'changeEndpoint') Return false;
if($var == 'endpoint') Return '';
}

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);
}
function trackDetails($details, $spacer){
foreach($details as $key => $value){
	if(is_array($value) || is_object($value)){
        	$newSpacer = $spacer. '    ';
    		echo '<tr><td>'. $spacer . $key.'</td><td> </td></tr>';
    		trackDetails($value, $newSpacer);
    	}elseif(empty($value)){
    		echo '<tr><td>'.$spacer. $key .'</td><td> </td></tr>';
    	}else{
    		echo '<tr><td>'.$spacer. $key .'</td><td>'.$value.'</td></tr>';
    	}
    }
}

?>

 

 

Link to comment
Share on other sites

Thank you for the replies!

 

That's what's so weird about what's going on! I am putting valid stuff in the form in attempt to generate a shipping label for real addresses.

 

I'll look into the phpmoot link you suggested, but my concern is that it seems to be a rate check. I'm really only interested in the shipping label. Here's the circumstance: this task is for a "we buy old jewelry for cash" type place. They want users to come to their site, fill out their address and receive a shipping label to send with their gold. The gold buyers will pay for the shipping (so the shipping label should notate "bill recipient" and should access and charge their fedex account).

 

Here's where I have it thrown together: http://moneyforoldjewelry.com/get-started

Right now it is has all the shipping user info with garbage instead of trying to read from the form input.

 

So, based on the suggestions so far, does that mean the way I've been trying SHOULD have resulted in the expected outcome?  :-\

Link to comment
Share on other sites

Your problem is due to "variable scope" in labelprocessor.php.

 

$senderName = $_POST["first"]." ".$_POST["last"];
$senderPhone = $_POST["phone"];
$senderStreet = $_POST["street"];
$senderLine2 = $_POST["line2"];
$senderCity = $_POST["city"];
$senderState = $_POST["state"];
$senderZip = $_POST["zip"];
$senderCountry = "US";

// THEN LATER


function addShipper(){
$shipper = array(
	'Contact' => array(
		'PersonName' => 'Sender Name', //doesn't process at all if at least this one isn't a text value
		'PhoneNumber' => $senderPhone), 
	'Address' => array(
		'StreetLines' => array($senderStreet, $senderLine2 ),
		'City' => 'Arlington',
		'StateOrProvinceCode' => $senderState,
		'PostalCode' => $senderZip,
		'CountryCode' => 'US')
);
return $shipper;
}

 

Here you have defined the variables (such as $senderPhone) in the "Global" scope of the script. Then you try to access the variable in the scope of function addShipper. Those variables do not exist inside of the function. You need to pass them in as parameters to the function (or -- not recommended -- refer to them as globals).

 

Link to comment
Share on other sites

Thanks for the replies, guys.

 

So DavidAM, you mean that it seems as though the variables are dropping in empty values in the function because they are seen as "undefined".

 

So I need to pass them in such as:

function addShipper($senderName, $senderPhone, $senderStreet, ...etc){
...
}

 

... time elapse...

 

I went straight to trying that since it'd be more useful to have the results of it to discuss and it acted like before when everything was blank but when it went to pass those variables to the function it also returned these errors:

Warning: Missing argument 1 for addShipper(), called in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 64 and defined in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 131

 

Warning: Missing argument 2 for addShipper(), called in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 64 and defined in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 131

 

Warning: Missing argument 3 for addShipper(), called in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 64 and defined in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 131

 

Warning: Missing argument 4 for addShipper(), called in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 64 and defined in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 131

 

Warning: Missing argument 5 for addShipper(), called in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 64 and defined in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 131

 

Warning: Missing argument 6 for addShipper(), called in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 64 and defined in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 131

 

Warning: Missing argument 7 for addShipper(), called in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 64 and defined in /home/moneyfor/public_html/fedex/label/labelprocessor.php on line 131

Link to comment
Share on other sites

only way i see it working is by using globals which was mentioned is not standard practice to use.

 

 


global $senderName 
global $senderPhone 
global $senderStreet
global $senderLine2
global $senderCity 
global $senderState 
global $senderZip 
global $senderCountry

 

put it after your include file or if you don't use an include at the top.

 

Link to comment
Share on other sites

Don't forget to add the arguments to the function call:

<?php
$request['RequestedShipment'] = array(
'ShipTimestamp' => date('c'),
'DropoffType' => 'REGULAR_PICKUP', // valid values REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER and STATION
'ServiceType' => 'FEDEX_EXPRESS_SAVER', // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
'PackagingType' => 'YOUR_PACKAGING', // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
'TotalWeight' => array('Value' => 1.0, 'Units' => 'LB'), // valid values LB and KG
'Shipper' => addShipper(),   ////////////////////**** FUNCTION CALL *****//////////////////////////
'Recipient' => addRecipient(),
'ShippingChargesPayment' => addShippingChargesPayment(),
'SpecialServicesRequested' => addSpecialServices(),
'LabelSpecification' => addLabelSpecification(),
'RateRequestTypes' => array('ACCOUNT'), // valid values ACCOUNT and LIST
'PackageCount' => 1,
'RequestedPackageLineItems' => array(
	'0' => addPackageLineItem1()
)
);

[/code]

Link to comment
Share on other sites

har har har... That was totally it jcbones! Resolved!

 

Well, almost, that uncovered a new problem. But that's just an issue with my complicated, difficult to add to, form plugin using state names spelled out rather than abbreviated. An inconvenient problem well with in my grasp.

 

Thank you everybody for all of the help!!!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.