Fedex Rate API Request - php

I need to create a simple webpage that gets rate quotes from FedEx. Only thing is, I've never messed with an API before.
The XML is easy, but how do I send that XML to FedEx and view the response? API Request... Yes I know, but what is the code for an API request to FedEx? I just need some guidance. I know PHP to an extent - but, I'm no expert.
I understand that I need to send an API request but I need a simple working example using PHP. I want to be able to input my account information and then have a simple working rate quote.
I don't care if it only returns the simplest data. I just need to have something to get me started.
It seems as if FedEx only goes so far in providing information for doing this with PHP.

fedex offers acceleration packages in www.fedex.com/us/developer/ , you will find information about different types of calls to their webservices. as an example if you want to request a rate from fedex you will need to do something like this:
<?php
require_once('../../library/fedex-common.php5');
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "../../wsdl/RateService_v13.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' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v13 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '13',
'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;
}
?>
so go to fedex.com, download wsdl or xml with library and more. run this code and you will receive a quote. important to say that you need an account to access that area, where you will receive a test meter-account to try, and then move to production.. hope it helps.

Related

How Do I Prevent Duplicates When Adding Leads to SuiteCRM?

The developer guide for SuiteCRM is kind of incomplete (at least here in Q4 2017) compared to the old SugarCRM one that it was based on before the software fork. So, by downloading the WordPress Plugin for SugarCRM, I was able to figure out the REST API and JSON for adding a sales lead into SuiteCRM with the following code.
Now how do I prevent duplicates by home phone, mobile phone, or email address?
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
header('Content-Type: text/plain');
CRM::loginCRM('admin','xxxxPASSWORDxxxxxx');
$aResult = CRM::addLead(array(
'name' => 'John Doe',
'description' => 'sample description',
'salutation' => 'Mr.',
'first_name' => 'John',
'last_name' => 'Doe',
'do_not_call' => 'No',
'phone_home' => '202-111-2222',
'phone_mobile' => '202-111-2222',
'email1' => 'test#example.com',
'primary_address_street' => '123 Main Street',
'primary_address_street2' => '',
'primary_address_street3' => '',
'primary_address_city' => 'New York',
'primary_address_state' => 'NY'
));
print_r($aResult);
CRM::logoutCRM();
die('OK');
/////////////////////////
class CRM {
private static $SessionID = '';
private static $URL = 'https://mycrmserver-example.com/service/v4_1/rest.php';
private static $User = '';
private static $Shadow = '';
public static function sendJSON($a) {
$s = file_get_contents(
self::$URL,
false,
stream_context_create(
array(
'http' => array (
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => http_build_query($a)
)
)
)
);
$a2 = json_decode($s);
return $a2;
}
public static function loginCRM($sUser,$sPass) {
$sShadow = md5($sPass);
self::$User = $sUser;
self::$Shadow = $sShadow;
$asLogin = array (
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'user_auth' => array(
'user_name' => $sUser,
'password' => $sShadow,
'version' => 1
),
'application_name' => 'RestTest',
'name_value_list' => array()
))
);
$a = self::sendJSON($asLogin);
self::$SessionID = $a->id;
}
public static function logoutCRM() {
$asLogin = array (
'method' => 'logout',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'user_auth' => array(
'user_name' => self::$User,
'password' => self::$Shadow,
'version' => 1
),
'application_name' => 'RestTest',
'name_value_list' => array()
))
);
self::sendJSON($asLogin);
}
public static function addLead($a) {
$asNameValueList = array();
foreach($a as $sKey => $sVal) {
$asNameValueList[] = array('name'=>$sKey,'value'=>$sVal);
}
$asAddEntry = array (
'method' => 'set_entry',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'session' => self::$SessionID,
'module_name' => 'Leads',
'name_value_list' => $asNameValueList
))
);
$a = self::sendJSON($asAddEntry);
return $a;
}
} // end CRM
Add these functions into your CRM class and check them before adding a lead. I had a little help from this answer that incidentally gave me some insights. Also, I recommend you do things to tighten down your security such as add an .htaccess or NGINX rule that only allows certain IP addresses or require certain headers to reach anything in your /service folder, and /service/* subfolders either over HTTP or HTTPS.
public static function leadExistsByPhone($sHomePhone,$sMobilePhone) {
$sHomePhone = (empty($sHomePhone)) ? 'xxxxxinvalid' : $sHomePhone;
$sMobilePhone = (empty($sMobilePhone)) ? 'xxxxxinvalid' : $sMobilePhone;
$asCheck = array (
'method' => 'get_entry_list',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'session' => self::$SessionID,
'module_name' => 'Leads',
'query' => "
leads.phone_home = '$sHomePhone'
OR leads.phone_mobile = '$sMobilePhone'
",
'order_by' => 'leads.date_entered DESC',
'offset' => '0',
'select_fields' => array(),
'link_name_to_fields_array' => array(),
'max_results' => 999999,
'deleted' => false
))
);
$a = self::sendJSON($asCheck);
$nCount = # $a->result_count;
$nCount = intval($nCount);
return ($nCount > 0);
}
public static function leadExistsByEmail($sEmail) {
if (!filter_var($sEmail, FILTER_VALIDATE_EMAIL)) {
die('DENIED: invalid email address format');
}
$asCheck = array (
'method' => 'get_entry_list',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => json_encode(array(
'session' => self::$SessionID,
'module_name' => 'Leads',
'query' => "
leads.id IN
(
SELECT email_addr_bean_rel.bean_id
FROM email_addr_bean_rel
JOIN email_addresses
ON email_addr_bean_rel.email_address_id = email_addresses.id
WHERE
email_addresses.email_address = '$sEmail'
)
",
'order_by' => 'leads.date_entered DESC',
'offset' => '0',
'select_fields' => array(),
'link_name_to_fields_array' => array(),
'max_results' => 999999,
'deleted' => false
))
);
$a = self::sendJSON($asCheck);
$nCount = # $a->result_count;
$nCount = intval($nCount);
return ($nCount > 0);
}

Laravel $push->getAdapter()->getResponse() is blank for iphone

I am using Laravel push notification library, for pushing notification.
However, i can easly get responses for GCM responses for Android Device.
But unable to get APNS response.
$message = PushNotification::Message("New Messages",$params['payload']);
$collection = PushNotification::app('appNameIOS')
->to($params['reg_id'])
->send($message);
foreach ($collection->pushManager as $push) {
$response = $push->getAdapter()->getResponse();
}
Make sure you have followed proper format as below:-
//iOS app
PushNotification::app(['environment' => 'development',
'certificate' => '/path/to/certificate.pem',
'passPhrase' => 'password',
'service' => 'apns']);
$devices = PushNotification::DeviceCollection(array(
PushNotification::Device('token', array('badge' => 5)),
PushNotification::Device('token1', array('badge' => 1)),
PushNotification::Device('token2')
));
$message = PushNotification::Message('Message Text',array(
'badge' => 1,
'sound' => 'example.aiff',
'actionLocKey' => 'Action button title!',
'locKey' => 'localized key',
'locArgs' => array(
'localized args',
'localized args',
),
'launchImage' => 'image.jpg',
'custom' => array('custom data' => array(
'we' => 'want', 'send to app'
))
));
$collection = PushNotification::app('appNameIOS')
->to($devices)
->send($message);
// get response for each device push
foreach ($collection->pushManager as $push) {
$response = $push->getAdapter()->getResponse();
}

Magento Product Create via API not working

I have been fighting with the Magento SOAP web service for a week and I can not figure out why I can not create a product using the API.
Below is my PHP code:
$client = new SoapClient('http://mywebsie.com/wp/store/api/soap/?wsdl');
// If some stuff requires api authentification,
// then get a session token
$session = $client->login('apiuser', 'apikey');
// get attribute set
$attributeSets = $client->call($session, 'product_attribute_set.list');
$attributeSet = current($attributeSets);
$newProductData = array(
'name' => 'Test product',
'websites' => array(1),
'short_description' => 'This is the short desc',
'description' => 'This is the long desc',
'price' => 150.00,
'status' => 1,
'tax_class_id' => 0,
'visibility' => 4
);
try {
// product creation
$client->call($session, 'product.create', array('simple', $set['set_id'], $ItemNmbr, $newProductData));
}
catch(SoapFault $e)
{
$msg = "Error in inserting product with sku $ItemNmbr : ".$e->getMessage();
echo $msg;
}
I am getting the following error:
Error in inserting product with sku ING-ACCS-00009 : Invalid data given. Details in error message.
I think you got this code from http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalogProduct.html. There are some bugs. Here is a fixed version:
$client = new SoapClient('http://mywebsie.com/wp/store/api/soap/?wsdl');
// If some stuff requires api authentification,
// then get a session token
$session = $client->login('apiuser', 'apikey');
$newProductData = array(
'name' => 'Test product',
'websites' => array(1),
'short_description' => 'This is the short desc',
'description' => 'This is the long desc',
'price' => 150.00,
'status' => 1,
'tax_class_id' => 0,
'url_key' => 'product-url-key',
'url_path' => 'product-url-path',
'visibility' => '4',
);
$sku = 'Some unique sku';
$storeView = 1;
$attributeSetId = 4; // you can get this id from admin area
$productType = 'simple';
try {
// product creation
$client->call($session, 'catalog_product.create', array($productType, $attributeSetId, $sku, $newProductData, $storeView));
} catch (SoapFault $e) {
echo "Error in inserting product with sku $sku : " . $e->getMessage();
}
For Soap v2 this worked for me.
$client = new SoapClient('http://localhost/index.php/api/v2_soap/?wsdl'); // TODO : change url
$sessionId = $client->login('youruser', 'yourpasswd');
$attributeSets = $client->catalogProductAttributeSetList($sessionId);
$attributeSet = current($attributeSets);
$sku = 'COD002';
//catalogProductCreate( sessionId, type, setId, sku, productData, storeView )
try {
$result = $client->catalogProductCreate($sessionId, 'simple', $attributeSet->set_id, $sku, array(
'categories' => array(2),
'websites' => array(1),
'name' => 'producto de prueba',
'description' => 'Product description',
'short_description' => 'Product short description',
'weight' => '10',
'status' => '1',
'url_key' => 'product-url-key',
'url_path' => 'product-url-path',
'visibility' => '4',
'price' => '100',
'tax_class_id' => 1,
'meta_title' => 'Product meta title',
'meta_keyword' => 'Product meta keyword',
'meta_description' => 'Product meta description',
'stock_data' => array(
'qty' => '49',
'is_in_stock' => 1
)
),1);
$result2 = $client->catalogProductList($sessionId);
echo "<pre>";
print_r($result2);
echo "</pre>";
} catch (SoapFault $e) {
echo "Error in inserting product with sku $sku : " . $e->getMessage();
}

how to create Order using magento v2_soap api in php

Could you tell me how can I create Order using magento v2_soap api?
It's not possible with default single api you need to create you own custom api
OR
You need to call multiple api to place order as follows -
$proxy = new SoapClient('http://mywebside.com/api/v2_soap/?wsdl');
$sessionId = $proxy->login($user, $password);
$cartId = $proxy->shoppingCartCreate($sessionId, 1);
// load the customer list and select the first customer from the list
//$customerList = $proxy->customerCustomerList($sessionId, array());
//$customer = (array) $customerList[188];
//Do not change this credentials
$customer['customer_id'] = 199; // customer id
$customer['created_at'] = '2016-02-03 19:24:41';
$customer['updated_at'] = '2016-04-22 03:33:33';
$customer['store_id'] = 1;
$customer['website_id'] = 1;
$customer['created_in'] = 'Default Store View';
$customer['email'] = 'test#gmail.com';
$customer['firstname'] = 'test';
$customer['lastname'] = 'test';
$customer['group_id'] = 1;
$customer['password_hash'] = 'assassaXXXXO';
$customer['mode'] = 'customer';
$proxy->shoppingCartCustomerSet($sessionId, $cartId, $customer);
// load the product list and select the first product from the list
//$productList = $proxy->catalogProductList($sessionId);
// $product = (array) $productList[0];
$product= array(array(
'product_id' => '43001',
'sku' => 'SKU420',
'qty' => '2',
),
array(
'product_id' => '43002',
'sku' => 'SKUZ42B2',
'qty' => '1',
));
try{
$proxy->shoppingCartProductAdd($sessionId, $cartId, $product);
} catch (SoapFault $e) {
$error['product'] = $e->getMessage();
}
$address = array(
array(
'mode' => 'shipping',
'firstname' => $customer['firstname'],
'lastname' => $customer['lastname'],
'street' => 'street address',
'city' => 'city',
'region' => 'region',
'telephone' => 'phone number',
'postcode' => '',
'country_id' => 'country ID',
'is_default_shipping' => 0,
'is_default_billing' => 0
),
array(
'mode' => 'billing',
'firstname' => $customer['firstname'],
'lastname' => $customer['lastname'],
'street' => 'street address',
'city' => 'city',
'region' => 'region',
'telephone' => 'phone number',
'postcode' => '',
'country_id' => 'country ID',
'is_default_shipping' => 0,
'is_default_billing' => 0
),
);
// add customer address
try{
$proxy->shoppingCartCustomerAddresses($sessionId, $cartId, $address);
} catch (SoapFault $e) {
$error['shipping'] = $e->getMessage();
}
try{
// add shipping method
$proxy->shoppingCartShippingMethod($sessionId, $cartId, 'freeshipping_freeshipping');
} catch (SoapFault $e) {
$result = $e->getMessage();
}
// add payment method
enter code here
$paymentMethod = array(
'method' => 'cashondelivery'
);
$proxy->shoppingCartPaymentMethod($sessionId, $cartId, $paymentMethod);
// place the order
$orderId = $proxy->shoppingCartOrder($sessionId, $cartId, null, null);
There is a cart object where you can attach a customer and products.
information on cart_product.add (SOAP v1) or shoppingCartProductAdd (SOAP v2) is in Magento API documenattion
http://www.magentocommerce.com/api/soap/checkout/cartProduct/cart_product.add.html

PHP GetResponse API and CF7 connection

Im trying to take data from Contact Form 7 WordPress plugin and pass it with json to GetResponse API
I have a php file that pull the data and send it, and its looks like this
I'm getting the CF7 email of confirmation but im not getting GetResponse Email confirmation for newsletter, i don't understand why, i tried to do some debugging and there was no errors
add_action('wpcf7_before_send_mail', 'mytheme_save_to_getresponse', 10, 1);
function mytheme_save_to_getresponse($form)
{
include 'ChromePhp.php';
require_once 'jsonRPCClient.php';
$api_key = 'some_api_key';
$api_url = 'http://api2.getresponse.com';
$client = new jsonRPCClient($api_url);
$result = NULL;
try {
$result = $client->get_campaigns(
$api_key,
array (
# find by name literally
'name' => array ( 'EQUALS' => 'testcase_001' )
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
$campaigns = array_keys($result);
$CAMPAIGN_ID = array_pop($campaigns);
$subscriberName = $_POST['name'];
$subscriberEmail = $_POST['email'];
$subscriberPhone = $_POST['c_phone'];
$subscriberCellphone = $_POST['c_cellphone'];
$subscriberArea = $_POST['c_area'];
$subscriberInsuranceType = $_POST['c_type'];
$subscriberCarType = $_POST['c_cartype'];
$subscriberManifacture = $_POST['c_manifacture'];
$subscriberManifacturemodel = $_POST['c_manifacturemodel'];
$subscriberManifactureYear = $_POST['c_manifactureyear'];
$subscriberDriverAge = $_POST['c_driversage'];
$subscriberPrevent = $_POST['c_prevent'];
$subscriberClaim = $_POST['c_claim'];
try {
$result = $client->add_contact(
$api_key,
array (
'campaign' => $CAMPAIGN_ID,
'name' => $subscriberName,
'email' => $subscriberEmail,
'cycle_day' => '0',
'customs' => array(
array(
'name' => 'home_phone',
'content' => $subscriberPhone
),
array(
'name' => 'cell_phone',
'content' => $subscriberCellphone
),
array(
'name' => 'living_area',
'content' => $subscriberArea
),
array(
'name' => 'drivers_age',
'content' => $subscriberDriverAge
),
array(
'name' => 'insurance_type',
'content' => $subscriberInsuranceType
),
array(
'name' => 'car_type',
'content' => $subscriberCarType
),
array(
'name' => 'manifacture_type',
'content' => $subscriberManifacture
),
array(
'name' => 'manifacture_model',
'content' => $subscriberManifacturemodel
),
array(
'name' => 'manifacture_year',
'content' => $subscriberManifactureYear
),
array(
'name' => 'license_loss',
'content' => $subscriberPrevent
),
array(
'name' => 'claims_number',
'content' => $subscriberClaim
)
)
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
}
Thanks in advance
everything was OK with this code, i GetResponse don't send confirmation requests more than once on the same email..

Categories