Royal Mail Shipment API ( SOAP ) - php

I have been battling with the royal mail shipment soap api for a while now and I am not getting anywhere. The error I am getting is a validation error but it isn't telling me what is not right.
I tried the sample code that Royal Mail offers and that doesn't seem to be working properly either.
Does anyone have a really basic xml example for creating a shipment?
Thanks

<?php
ini_set('soap.wsdl_cache_enabled', 1);
ini_set('soap.wsdl_cache_ttl', 1);
class royalmaillabelRequest
{
private $apiapplicationid = "application id";
private $api_password = "password ";
private $api_username = ""; //"rxxxxxAPI"
private $locationforrequest = 'https://api.royalmail.net/shipping/v2';
private $api_service_enhancements = "";
private function preparerequest()
{
//PASSWORD DIGEST
$api_password = "";
$clientId = ""; //royal mail credentials
$clientSecret = "";
$time = gmdate('Y-m-d\TH:i:s');
$created = gmdate('Y-m-d\TH:i:s\Z');
$creationDate = gmdate('Y-m-d\TH:i:s\Z');
$nonce = mt_rand();
$nonce_date_pwd = $nonce . $creationDate . base64_encode(sha1($api_password, TRUE));
$passwordDigest = base64_encode(sha1($nonce_date_pwd, TRUE));
$ENCODEDNONCE = base64_encode($nonce);
//SET CONNECTION DETAILS
$soapclient_options = array();
$soapclient_options['cache_wsdl'] = 'WSDL_CACHE_NONE';
$soapclient_options['stream_context'] = stream_context_create(array(
'http' => array(
'header' => implode("\r\n", array(
'Accept: application/soap+xml',
'X-IBM-Client-Id: ' . $clientId,
'X-IBM-Client-Secret: ' . $clientSecret
))
)
));
$soapclient_options['trace'] = true;
$soapclient_options['ssl_method'] = 'SOAP_SSL_METHOD_SSLv3';
$soapclient_options['location'] = $this->locationforrequest;
$soapclient_options['soap_version'] = 'SOAP_1_1';
//launch soap client
$client = new SoapClient(dirname(__FILE__) . "/SAPI/ShippingAPI_V2_0_9.wsdl", $soapclient_options);
$client->__setLocation($soapclient_options['location']);
//headers needed for royal mail//D8D094Fd2716E3Es142588808s317
$HeaderObjectXML = '<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-D8D094FC22716E3EDE14258880881317">
<wsse:Username>' . $this->api_username . '</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">' . $passwordDigest . '</wsse:Password>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">' . $ENCODEDNONCE . '</wsse:Nonce>
<wsu:Created>' . $created . '</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>';
//push the header into soap
$HeaderObject = new SoapVar($HeaderObjectXML, XSD_ANYXML);
//push soap header
$header = new SoapHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd', 'Security', $HeaderObject);
$client->__setSoapHeaders($header);
return $client;
}
public function CreateShippiment($data)
{
$request = $this->buildCreateshippiment($data);
$type = 'createShipment';
return $this->makerequest($type, $request);
}
public function PrintLabel($shipmentNumber, $order_tracking_id)
{
$time = gmdate('Y-m-d\TH:i:s');
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->apiapplicationid,
'transactionId' => $order_tracking_id
)
),
'shipmentNumber' => $shipmentNumber,
'outputFormat' => 'PDF'
);
$type = 'printLabel';
$response = $this->makerequest($type, $request);
return $response->label;
}
public function PrintDocument($shipmentNumber, $order_tracking_id)
{
$time = gmdate('Y-m-d\TH:i:s');
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->apiapplicationid,
'transactionId' => $order_tracking_id
)
),
'shipmentNumber' => $shipmentNumber,
'documentName' => 'CN22',
'documentCopies' => '1',
'documentFormat' => 'PDF'
);
$type = 'printDocument';
$response = $this->makerequest($type, $request);
return $response->internationalDocument;
}
private function makerequest($type, $request)
{
$client = $this->preparerequest();
$response = false;
$times = 1;
while (true) {
try {
$response = $client->__soapCall($type, array(
$request
), array(
'soapaction' => $this->locationforrequest
));
// echo "REQUEST:\n" . htmlentities($client->__getLastResponse()) . "\n";
break;
}
catch (Exception $e) {
print_r($e);
if ($e->detail->exceptionDetails->exceptionCode == "E0010" && $times <= 25) {
sleep(1.5);
$times++;
continue;
} else {
echo $e->getMessage();
echo "<pre>";
print_r($e->detail);
echo $client->__getLastResponse();
echo "REQUEST:\n" . htmlentities($client->__getLastResponse()) . "\n";
break;
}
}
break;
}
return $response;
}
private function buildCreateshippiment($data2)
{
$time = gmdate('Y-m-d\TH:i:s');
$data = new ArrayObject();
foreach ($data2 as $key => $value) {
$data->$key = $value;
}
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->apiapplicationid,
'transactionId' => $data->order_tracking_id
)
),
'requestedShipment' => array(
'shipmentType' => array(
'code' => 'Delivery'
),
'serviceOccurrence' => 1,
'serviceType' => array(
'code' => $data->api_service_type
),
'serviceOffering' => array(
'serviceOfferingCode' => array(
'code' => $data->api_service_code
)
),
'serviceFormat' => array(
'serviceFormatCode' => array(
'code' => $data->api_service_format
)
),
'shippingDate' => date('Y-m-d'),
'recipientContact' => array(
'name' => $data->shipping_name,
'complementaryName' => $data->shipping_company
),
'recipientAddress' => array(
'addressLine1' => $data->shipping_address1,
'addressLine2' => $data->shipping_address2,
'addressLine3' => $data->shipping_county,
'stateOrProvince' => array(
stateOrProvinceCode => array(
name => $data->shipping_county
)
),
'postTown' => $data->shipping_town,
'postcode' => $data->shipping_postcode,
'country' => array(
'countryCode' => array(
'code' => 'US'
)
)
),
'items' => array(
'item' => array(
'numberOfItems' => $data->order_tracking_boxes,
'weight' => array(
'unitOfMeasure' => array(
'unitOfMeasureCode' => array(
'code' => 'g'
)
),
'value' => $data->order_tracking_weight
)
)
),
// 'internationalInfo' => array('parcels' => array('parcel' => array( 'weight' => array( 'unitOfMeasure' => array('unitOfMeasureCode' => array('code' => 'g')),
// 'value' => $data->parcel_weight)),
// 'purposeOfShipment'=> '999',
// 'contentDetails' => $data->content
// )
// ),
'senderReference' => $data->sendersReference
//'signature' => 0,
)
);
if ($data->api_service_enhancements == 6 && $data->api_service_type == 1) {
$request['requestedShipment']['serviceEnhancements'] = array(
'enhancementType' => array(
'serviceEnhancementCode' => array(
'code' => $data->api_service_enhancements
)
)
);
}
return $request;
}
}
// $new= new royalmaillabelRequest();
// $data['order_tracking_id']="";
// $data['api_service_type']="";
// echo $data['api_service_code']="";
// $data['api_service_format']="";
// $data['shipping_name']="";
// $data['shipping_company']="";
// $data['shipping_address1']="";
// $data['shipping_address2']="";
// $data['shipping_town']="";
// $data['shipping_postcode']="";
// $data['order_tracking_boxes']="";
// $data['order_tracking_weight']="";
// $data['api_service_enhancements']="";
// $data['value']="600";
// $data['shipping_postcode']="123456";
// $data['serviceEnhancementCode']="";
// $new->CreateShippiment($data);
?>

Related

CI3 hook only work on local but not on server

So my team have cloned a project that have a hook that can track the activity of the users like anything that they POST or GET. The previous project have work perfectly on local and on server. But on the recent project, it only work normal when I run it on local. But on server the hook only track user when they log out.
here's the hooks.php "application/config":
$hook['post_controller_constructor'][] = array(
'class' => 'Activity_user',
'function' => 'log_activity',
'filename' => 'log_activity_user.php',
'filepath' => 'hooks',
// 'params' => array('red', 'yellow', 'blue')
);
here's the log_activity_user "application/hooks/":
class Activity_user {
function __construct() {
$this->CI =& get_instance();
$this->CI->load->library('session');
$this->CI->load->library('lactivityuser');
}
public function log_activity() {
$post = $this->CI->input->post();
$get = $this->CI->input->get();
$timezone = new DateTimeZone('Asia/Jakarta');
$date = new DateTime();
$date->setTimeZone($timezone);
$result = $date->format('Y-m-d H:i:s');
if(count($post) > 0){
if (strpos($_SERVER["REQUEST_URI"], '/login')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'melakukan login',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/Log_data')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Melihat Log Data',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/History_IO')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Melihat History IO',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/Dashboard')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Melihat Dashboard',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/api/rule')) {
$data = array(
'email' => ' ',
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Rule',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/API/Rule')) {
$data = array(
'email' => ' ',
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Rule',
'created_date' => $result,
);
}
else{
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => json_encode($post),
'created_date' => $result,
);
}
$this->CI->db->insert('tb_activity_user', $data);
}else if(count($get) > 0){
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => json_encode($get),
'created_date' => $result,
);
$this->CI->db->insert('tb_activity_user', $data);
}
}
}
edit: they have enable the hook to TRUE in the config file

Not display NULL value in multi-axis chart

I am using multi-axis chart from Highcharts.
It works fine but I don't want to display my variable if it’s NULL , where should I put the test on the NULL value ?
I have done it in a pie chart but now with all this arrays I am lost
my multi-axis chart function which took an array composed of years and 4 arrays:
public function multiAxeChartDyn($date, $list1, $list2,$list3,$list4)
{
$dates = $date;
$ob = new Highchart();
$ob->chart->renderTo('containerMultiaxe'); // The #id of the div where to render the chart
$ob->chart->type('column');
$ob->title->text('Budget');
$ob->xAxis->categories($dates);
$ob->legend->enabled(true);
$dataSeries= array(
$list1,
$list2,
$list3,
$list4,
);
$yData = array(
array(
'labels' => array(
'formatter' => new Expr('function () { return this.value + " %" }'),
'style' => array('color' => '#AA4643')
),
'title' => array(
'text' => 'Taux',
'style' => array('color' => '#AA4643')
),
'opposite' => true,
),
array(
'labels' => array(
'formatter' => new Expr('function () { return this.value + " mDT" }'),
'style' => array('color' => '#4572A7')
),
'gridLineWidth' => 0,
'title' => array(
'text' => 'Budget',
'style' => array('color' => '#4572A7')
),
),
);
$ob->yAxis($yData);
$formatter = new Expr('function () {
var unit = {
"Budget": "mDT",
"Ressource": "mDT",
"Taux global": "%",
"Taux Consumption": "%"
}[this.series.name];
return this.x + ": <b>" + this.y + "</b> " + unit;
}');
$ob->tooltip->formatter($formatter);
$ob->series( $dataSeries);
return $ob;
}
my controller :
public function indexAction(Survey $survey)
{
$chart=new ChartController();
$ent = $survey ->getEnt();
$year= $survey->getYear();
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->select('e')
->from('AppBundle:Survey, 'e')
->where('e.year <= :year')
->andWhere('e.ent = :ent')
->setParameter('year', $year)
->setParameter('ent', $ent->getId())
->orderBy('e.year', 'DESC')
->setMaxResults(4);
$survey_year = $qb->getQuery()->getResult();
$date = array();
$data1 = array();
$data2 = array();
$data3 = array();
$data4 = array();
$survey_year= array_reverse($survey_year, true);
foreach($survey_year as $ea){
$date[] = $ea->getyear();
$data1[] = $ea->getForm ()->getBudget()/1000;
$data2[] = $ea->getForm ()->getRessources()/1000;
$data3[] = $ea->getForm ()->getTauxGlobal ();
$data4[] = $ea->getForm ()->getTauxConsumption ();
}
$list1= array(
'name' => 'Budget',
'type' => 'column',
'color' => '#4572A7',
'yAxis' => 1,
'dataLabels' => array(
'enabled' => true
),
'data' => $data1
);
$list2 = array(
'name' => 'Ressource',
'type' => 'column',
'color' => '#D49EDA',
'yAxis' => 1,
'dataLabels' => array(
'enabled' => true
),
'data' => $data2
);
$list3= array(
'name' => 'Taux global',
'type' => 'spline',
'color' => '#0A0F19',
'dataLabels' => array(
'enabled' => true
),
'data' => $data3
);
$list4 = array(
'name'=> 'Taux Consumption',
'type' => 'spline',
'color' => '#225824',
'dataLabels' => array(
'enabled' => true
),
'data' => $data4
);
$containermultiaxe=$chart->multiAxeChartDyn($date, $list1, $list2,$list3,$list4);
$html = $this->render('AppBundle:Charting:index.html.twig',array(
'survey' =>$survey,
'containerMultiaxe' => $containermultiaxe,
));
return $html;
}

Converting a php array to XML Soap api

I am have trouble converting array to xml here as the CustomerOrderLines are getting repeated, the xml generated gets only the last [CustomerOrderLines] value, how do i generate an xml with all the objects.
public function ProcessOrderAction(){
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
$quoteId = Mage::getSingleton('checkout/session')->getQuoteId();
$quote = Mage::getModel("sales/quote")->load($quoteId);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerAddress = array();
$_orders = Mage::getModel('sales/order')->getCollection()- >addFieldToFilter('customer_id',$customerData->getId());
$_orderCnt = $_orders->count(); //orders count
if($_orderCnt == 0){
$CustomerOperation="Create";
}else{
$CustomerOperation="Find";
}
$soapClient = new SoapClient("https://api.ongoingsystems.se/Colliflow/service.asmx?wsdl", array('trace' => 1));
$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
$store = Mage::app('checkout/session')->getStore();
$ap_param = array(
'GoodsOwnerCode'=>'Test',
'UserName' => 'test',
'Password' => 'test',
'co'=> [
'OrderInfo'=>[
'OrderIdentification' => 'SystemId',
'OrderOperation' => 'Create',
'GoodsOwnerOrderNumber' => '1111',
'OrderId' => '',
'GoodsOwnerOrderId' => '102',
'DeliveryDate' => '2016-05-14T22:16:00',
'OrderType'=> [
'OrderTypeOperation' => 'CreateOrFind',
'OrderTypeIdentification' => 'OrderTypeCode'
]
],
'Customer'=> [
'CustomerOperation' => $CustomerOperation,
'CustomerIdentification' => 'CustomerNumber',
'ExternalCustomerCode' => 'ExternalCustomerCode',
'CustomerNumber' => ''.$customerData->getId(),
'CustomerId' => ''.$customerData->getId(),
'Name' => ''.$customerData->getName(),
'Address' => ''.$customerAddress['region'],
'PostCode' => ''.$customerAddress['postcode'],
'City' => ''.$customerAddress['city'],
'TelePhone' => ''.$customerAddress['telephone'],
'Remark' => 'Remarks',
'IsVisible'=>'true',
'NotifyBySMS'=> 'true',
'NotifyByEmail'=> 'false',
'NotifyByTelephone'=>'false',
'Email' => ''.$customerData->getEmail(),
'MobilePhone' => ''.$customerAddress['telephone'],
'CountryCode' =>'NO',
'CountryStateCode' => '90'
],
'CustomerOrderLines' => [
'CustomerOrderLine'=> [
'OrderLineIdentification' => 'ArticleNumber',
'ArticleIdentification' => 'ArticleNumber',
'OrderLineSystemId' => '123',
'ExternalOrderLineCode' => 'ExternalOrderLineId',
'ArticleSystemId' => '123',
'ArticleNumber' => ''.$item->getSku(),
'ArticleName' => ''.$item->getName(),
'NumberOfItems' => '6',
'ProductCode' => ''.$item->getProductId()
],
'CustomerOrderLine'=> [
'OrderLineIdentification' => 'ArticleNumber',
'ArticleIdentification' => 'ArticleNumber',
'OrderLineSystemId' => '1231',
'ExternalOrderLineCode' => 'ExternalOrderLineId',
'ArticleSystemId' => '1230',
'ArticleNumber' => '0000099',
'ArticleName' => 'test222',
'NumberOfItems' => '6',
'ProductCode' => '6786978'
]
]
]
);
print_r($ap_param);
$error = 0;
try {
$info = $soapClient->__call("ProcessOrder", array($ap_param));
}catch (SoapFault $fault) {
$error = 1;
print("
alert('Sorry, returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.". We will now take you back to our home page.');
window.location = 'main.php'; ");
}
if ($error == 0) {
$auth_num = $info->ProcessOrderResult;
print_r($auth_num);
}
}

Fedex API Rate request issues, php

I can't figure out what I'm doing wrong I've set the authentication and version number but I just can get authenticated.
I get the following error when I try the sample code.
Severity: ERROR
Source: prof
Code: 1000
Message: Authentication Failed
Can anyone advise me on this please?! This is the first part of code, which is a barely modified copy of the example.
$path_to_wsdl = "./RateService_v18.wsdl";
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' => 'PmzmlFAKEKEYVha',
'Password' => 'myfedex-website-password'
)
);
$request['ClientDetail'] = array(
'AccountNumber' => '123456789',
'MeterNumber' => '123456789'
);
$request['TransactionDetail'] = array('CustomerTransactionId' => 'testing');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '18',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array('Ammount'=>100,'Currency'=>'USD');
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT';
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try
{
if(setEndpoint('changeEndpoint'))
{
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
$rateReply = $response -> RateReplyDetails;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
echo $serviceType . $amount. $deliveryDate;
echo '</tr>';
echo '</table>';
printSuccess($client, $response);
}
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',
'CompanyName' => 'Sender Company Name',
'PhoneNumber' => '9012638716'),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Collierville',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38017',
'CountryCode' => 'US')
);
return $shipper;
}
function addRecipient(){
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => '9012637906'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Richmond',
'StateOrProvinceCode' => 'BC',
'PostalCode' => 'V7C4V4',
'CountryCode' => 'CA',
'Residential' => false)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'CountryCode' => 'US')
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // 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' => 50.0,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 108,
'Width' => 5,
'Height' => 5,
'Units' => 'IN'
)
);
return $packageLineItem;
}
Thank you in advance for ANY help! :)
the password is not your password you already have. it is another one they email you later. :/

Fedex api returns this error array(0) { }?

I am using Codeigniter library to get fedex rates i have created my own library to get rates and i grab data on my controller the request processes but its returns me array(0) { } error, i have searched a lot i can't find why it returns array 0 what is this error what i am doing wrong.
My library file.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class fedex{
function rates(){
$weight = '46';
$this->path_to_wsdl = base_url()."assets/wsdl/RateService_v14.wsdl";
$key = 'acess_key';
$password = 'password';
$shipAccount = 'accound_no';
$meter = 'meter_no';
$dropofftype = 'dropofftype';
$service = 'FEDEX_1_DAY_FREIGHT';
$package = 'package';
$handling_method = 'price';
$handling_amount = '5';
$pkg_width = '6';
$pkg_height = '6';
$pkg_length = '5';
$insurance = true;
$billAccount = $shipAccount;
// Build Request
$package = $this->package_types['FEDEX_10KG_BOX'] = 'FEDEX_10KG_BOX';
$dropofftype = $this->dropoff_types['REGULAR_PICKUP'] = 'REGULAR_PICKUP';
ini_set("soap.wsdl_cache_enabled", 0);
ini_set('soap.wsdl_cache_ttl',0);
$client = new SoapClient($this->path_to_wsdl, array('trace' => 1, "exception" => 0));
// 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' => '*** Rate Request v14 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '14',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = false;
$request['RequestedShipment']['RequestedCurrency'] ='$';
$request['RequestedShipment']['DropoffType'] = $dropofftype;
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['PackagingType'] = $package;
if($insurance=='yes')
{
$request['RequestedShipment']['TotalInsuredValue']=array(
'Ammount'=> '5',
'Currency'=> '$',
);
}
$request['RequestedShipment']['Shipper'] = array(
'Contact' => array(
'CompanyName' => 'companyname',
'EMailAddress' => 'EMailAddress'
),
'Address' => array(
'StreetLines' => 'StreetLines',
'City' => 'City',
'StateOrProvinceCode' => 'StateOrProvinceCode',
'PostalCode' => 'PostalCode',
'CountryCode' => 'CountryCode'
)
);
$request['RequestedShipment']['Recipient'] = array(
'Contact' => array(
'PersonName' => " ",
'CompanyName' => '',
'PhoneNumber' => '',
),
'Address' => array(
'StreetLines' => '',
'City' => '',
'StateOrProvinceCode' => '',
'PostalCode' => 'postalcode',
'CountryCode' => '',
//'Residential' => false // no way to determine this
)
);
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => $weight,
'Units' => 'lbs'
),
'Dimensions' => array(
'Length' => $pkg_length,
'Width' => $pkg_width,
'Height' => $pkg_height,
'Units' => 'feet'
)
);
// Send the request to FedEx
$response = $client->getRates($request);
// Handle response
if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR' )
{
if(!is_array(#$response->RateReplyDetails))
{
return array(); // No Results
}
foreach ($response->RateReplyDetails as $rateReply)
{
if(in_array($rateReply->ServiceType, $service))
{
$amount = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
if(is_numeric($handling_amount)) // valid entry?
{
if($handling_method=='price')
{
$amount += $handling_amount;
}
elseif($handling_method=='percent')
{
$amount += $amount * ($handling_amount/100);
}
}
$rates[$this->service_list[$rateReply->ServiceType]] = number_format($amount,2,".",",");
}
}
return $rates;
}
else
{
return array(); // fail
}
}
}
My controller.
public function fedex(){
$this->load->library('fedex/fedex');
$fedex = new Fedex;
$weight = 46;
$dest_zip = '10001';
$fexed_rates = $fedex->rates();
var_dump($fexed_rates); die;
}
from the last you can see the line
Error Line No : $amount = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
Correct:
$amount = $rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount;

Categories