Showing posts with label Channel Advisor PHP API. Show all posts
Showing posts with label Channel Advisor PHP API. Show all posts

Saturday, September 24, 2011

Case Study: Connect Magento with ChannelAdvisor

Hello,

This blog is again on different topic. It will not have single line of code. It's a case study on Synchronizing magento with leading eCommerce platforms.

Magento is very popular eCommerce platform widely used across the globe. eBay is acquiring magento and magento framework will be core part of eBay soon. eBay, Magento and Paypal are going to launch new eCommerce platform called xCommerce.

Sometimes it would be difficult to manage everything for those who sell their stuff online and using Magento and other sites like eBay and Amaozn. Because you have magento orders in magento admin. You can view eBay orders in eBay seller account and same way for Amazon orders. So seller have to process all the orders at different place. Same way it would be difficult to manage inventory.

To resolve this problems, magento should be synchronized with other platforms so that all the process like inventory management and order processing can be done at one place. Since last few months, I am working Magento synchronization with those platforms and I would like to share that experience here as a case study.

So this blog is about ChannelAdvisor

ChannelAdvisor provides you multiple channel for eBay and Amazon. ChannelAdvisor provides set of API to access ChhanelAdvisor account from outside. Those API can be used  synchronize it with Magento.

Inventory API

Inventory API is used to manage inventory. It gives various functions like

-Add item
-Delete item
-Update item
-Set quantity
-Set price and much more.

And it provides ability to send set of attributes for products so that all the magento attributes can be sent to CA. So basically on magento we need to set a cron job which runs every specified time interval and send updates in inventory to CA.

Order API


It gives an order api using which we can retrieve order details and using those details we can insert those orders in magento via code and process them in admin. You can retrieve orders based on specific date range. Also various filters can be applied like get all the pending orders, get all unshipped orders etc. We can control detail level of information. If you want all the information about order or only selected information, this can be controlled in API. Same way one can control number of orders returned by API. If you specify 100 orders, it will return information about 100 orders in one API call. It also gives you full details about customer, so that can be used in Magento to create customer and assign that order to him. Orders can be synchronized by setting a cron job in magento which runs on specified time interval and fetch those orders and create them in Magento.

Also after processing orders tracking information can be sent back to ChannelAdvisor using order API.

This makes complete integration of CA with Magento.

I hope this post helps you and if you are looking for such solution let me know.

Thanks,

Saturday, May 7, 2011

Programmatically create order in Magento

Hello,

This is the toughest work I ever did in Magento. Since last few days I am working on Magento and Channel Advisor(CA) Integration.  The requirement was to fetch order from CA and process them in Magento. We were using Channel Advisor PHP API to fetch orders from CA.

CA order service API needs order criteria to fetch orders. Following is the order criteria we were passing.


$OrderCriteria = array(
'OrderCreationFilterBeginTimeGMT'=> $date1,
'OrderCreationFilterEndTimeGMT'=> $date2,
'StatusUpdateFilterBeginTimeGMT' => $date1,
'StatusUpdateFilterEndTimeGMT' => $date2,
'JoinDateFiltersWithOr' => true,
'DetailLevel' => 'Complete',
'ExportState' => 'NotExported',
'OrderStateFilter' => 'Active',
'PaymentStatusFilter' => 'Cleared',
'CheckoutStatusFilter'  => 'Completed',
'ShippingStatusFilter'  =>'Unshipped',
'PageNumberFilter'=>1,
'PageSize'=>20
);



$arrData = array(
        'accountID'=>$accountID,
        'orderCriteria'=>$OrderCriteria
);
$result=$client->GetOrderList($arrData);               
$results=$result->GetOrderListResult->ResultData;
$orders=$results->OrderResponseItem ;

It will return first 20 orders that match above criteria.

Now here is the tough job. We have to fetch all the order data and have to create order in Magento. Following is the code for it.


foreach($orders as $order)
{

$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()
->getStore('default')->getId());
$customer = Mage::getModel('customer/customer')
->setWebsiteId(1)
->loadByEmail($order->BuyerEmailAddress);                  
                   
if(empty($customer)){
$quote->assignCustomer($customer);
}
else{
$quote->setCustomerEmail($order->BuyerEmailAddress);
}

$orderitems = $order->ShoppingCart->LineItemSKUList->OrderLineItemItem;


foreach($orderitems as $orderItem){
        $product = $newProd
                               ->load($newProd->getIdBySku($orderItem->SKU));

        $buyInfo = array(
         'qty' => $orderItem->Quantity
         );

         $quote->addProduct($product, new Varien_Object($buyInfo));                    

}


$region=$order->ShippingInfo->Region;
$regionid = GetRegionId($region);


$firstName = ($order->BillingInfo->FirstName != "")
? ($order->BillingInfo->FirstName)
:($order->ShippingInfo->FirstName);
if(empty($firstName)){
$firstName = "FirstName";  
}

$firstName = ($order->BillingInfo->FirstName != "") 
? ($order->BillingInfo->FirstName) 
:($order->ShippingInfo->FirstName);
if(empty($firstName)){
$firstName = "FirstName";    
}

$lastName = ($order->BillingInfo->LastName != "") 
? ($order->BillingInfo->LastName) 
: ($order->ShippingInfo->LastName);
if(empty($lastName)){
$lastName = "LastName";    
}
                    
$street = (($order->BillingInfo->AddressLine1 != "")
? ($order->BillingInfo->AddressLine1) 
: ($order->ShippingInfo->AddressLine1)).
(($order->BillingInfo->AddressLine2 != "") 
? ($order->BillingInfo->AddressLine2) 
: ($order->ShippingInfo->AddressLine2));

if(empty($street)){
$street = "Street";    
}
                    
$city = ($order->BillingInfo->City != "") 
? ($order->BillingInfo->City) 
: ($order->ShippingInfo->City);
if(empty($city)){
$city = "City";    
}
                    
$postCode = ($order->BillingInfo->PostalCode != "") 
? ($order->BillingInfo->PostalCode) 
: ($order->ShippingInfo->PostalCode);
if(empty($postCode)){
$postCode = "00000";    
}
                    
$telephone = ($order->BillingInfo->PhoneNumberDay != "") 
? ($order->BillingInfo->PhoneNumberDay) 
: ($order->ShippingInfo->PhoneNumberDay);

if(empty($telephone)){
$telephone = "00000";    
}
                    
$addressData = array(
'firstname' => $firstName,
'lastname' => $lastName,
'street' => $street,
'city' => $city,
'postcode' => $postCode,
'telephone' => $telephone,
'country_id' => $order->ShippingInfo->CountryCode,
'region_id' => $regionid
);

$billingAddress = $quote
                             ->getBillingAddress()
                             ->addData($addressData);

$firstName = ($order->ShippingInfo->FirstName != "") 
? ($order->ShippingInfo->FirstName) 
: ($order->BillingInfo->FirstName);
if(empty($firstName)){
$firstName = "FirstName";    
}
                    
$lastName = ($order->ShippingInfo->LastName != "") 
? ($order->ShippingInfo->LastName) 
: ($order->BillingInfo->LastName);
if(empty($lastName)){
$lastName = "LastName";    
}
                    
$street = (($order->ShippingInfo->AddressLine1 != "") 
? ($order->ShippingInfo->AddressLine1) 
: ($order->BillingInfo->AddressLine1)).
(($order->ShippingInfo->AddressLine2 != "") 
? ($order->ShippingInfo->AddressLine2) 
: ($order->BillingInfo->AddressLine2));                    
if(empty($street)){
$street = "Street";    
}
                    
$city = ($order->ShippingInfo->City != "") 
? ($order->ShippingInfo->City) 
: ($order->BillingInfo->City);
if(empty($city)){
$city = "City";    
}
                    
$postCode = ($order->ShippingInfo->PostalCode != "") 
? ($order->ShippingInfo->PostalCode) 
: ($order->BillingInfo->PostalCode);
if(empty($postCode)){
$postCode = "00000";    
}
                    
$telephone = ($order->ShippingInfo->PhoneNumberDay != "") 
? ($order->ShippingInfo->PhoneNumberDay) 
: ($order->BillingInfo->PhoneNumberDay);
if(empty($telephone)){
$telephone = "00000";    
}
                    
$addressData = array(
'firstname' => $firstName,
'lastname' => $lastName,
'street' => $street,
'city' => $city,
'postcode' => $postCode,
'telephone' => $telephone,
'country_id' => $order->ShippingInfo->CountryCode,
'region_id' => $regionid
);

$shippingAddress = $quote->getShippingAddress()->addData($addressData);
                    
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
                        ->setShippingMethod('perproductshipping_ground')
                        ->setPaymentMethod('purchaseorder');
                        
$quote->getPayment()->importData(array(
'method' => 'purchaseorder',
'po_number' => $order->ClientOrderIdentifier));
         
$quote->collectTotals()->save();
                    
Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0"); 
                    
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();




}

That's it and it will create new purchase order in magento. Limitations of above code are as follow.

1) It will only create purchase order
2) It will only be useful for simple products.

I hope this post helps you.

Thanks,



Friday, April 8, 2011

Use Channel Advisor Order PHP API with Magento

Hello,

In my previous blog I mentioned about Channel Advisor API. You can read that blog here. In this blog we will see how to use Channel Advisor Order service to get order details from Channel Advisor. This service is useful when you want to import orders from Channel Advisor to your own CMS or ERP. In my case I was working with Magento - Channel Advisor synchronization. So the requirement was to get order from Channel Advisor and add order to Magento.

Following is the code to create soap client for order service.


$client = new SoapClient("https://api.channeladvisor.com/ChannelAdvisorAPI/v4/OrderService.asmx?WSDL");

$headersData = array('DeveloperKey' => $developerKey, 'Password' => $password);

$head = new SoapHeader("http://api.channeladvisor.com/webservices/","APICredentials",$headersData);

$client->__setSoapHeaders($head);

To get necessary order details, we need to set order criteria. Following is the example of order criteria.

$OrderCriteria = array(
               'OrderCreationFilterBeginTimeGMT'=> $date1,
               'OrderCreationFilterEndTimeGMT'=> $date2,
               'StatusUpdateFilterBeginTimeGMT' => $date1,
               'StatusUpdateFilterEndTimeGMT' => $date2,
               'DetailLevel' => 'Complete',
               'ExportState' => 'NotExported',
               'OrderStateFilter' => 'Active',
               'PaymentStatusFilter' => 'Cleared',
               'CheckoutStatusFilter'  => 'Completed',
               'ShippingStatusFilter'  =>'Shipped',
               'PageNumberFilter'=>1,
               'PageSize'=>30
          );

Here date1 and date2 variable specify date range for orders. After this call function of API to get order data.

$arrData = array(
               'accountID'=>$accountID,
               'orderCriteria'=>$OrderCriteria
    );
$result=$client->GetOrderList($arrData); 

You will get API response in $result. If there is only one order matching criteria then it will return order object else it will return order object array if more than one order is matching criteria.

Saturday, March 5, 2011

Working with Channel Advisor API with PHP

Hello Guys,

Recently I was working with Channel Advisor(CA) API in PHP script. Script was built to get product information from CA and  update product information in CA. First of all lets see what is Channel Advisor platform?

It's a SaaS(Software As A Service) provider which enables retailers to sell products online through various channels like eBay, Amazon etc. It has certain features like product inventory using which retailer can store product information. Those products can be synchronized in various e commerce channels. User can track sales through each channel. Detailed reports are also available.


This platform is built upon .Net Framework and it offers Asp.Net web services to use its API. Using those web service we can use that platform from the third party application. To use web services you have to register as a developer and get developer key and password. After this channel advisor admin will approve your developer account and provides a account ID and local id that developer can use in the scripts. 


Now as we all know that Asp.Net web services use SOAP protocol so we need some soap client in PHP. PHP 5.1 and above has soap pears available while for older version one need to install it separately.


Following is the code to use CA web service.

$developerKey = 'your developer key';
$password = 'password';
$localID = '1111111050';
$accountID = 'account id';


$client = new SoapClient("https://api.channeladvisor.com/ChannelAdvisorAPI/v3/InventoryService.asmx?WSDL");


$headersData = array('DeveloperKey' => $developerKey, 'Password' => $password);


$head = new SoapHeader("http://api.channeladvisor.com/webservices/","APICredentials",$headersData);
$client->__setSoapHeaders($head);


That's it and you have Soap client available now you can call any method which is provided by web service. See the example below.
$result = $client->GetInventoryItemQuantityInfo(array('accountID'=>$accountID,'sku' => $sku));
Above code gives quantity of product specified by sku. 


So this is how you can integrate channel advisor API in PHP. Above example is of inventory service. There are other services also available. Each method in services needs some input. Some are the required fields like product SKU etc. for example cosider following example of SynchInventoryItem method. This is the method used to add or update product in inventory. While working in PHP all the parameters need to be sent in format of an array.



$iteminfo = array('Sku'=>$sku,
                      'Title'=>$title,
                      'Subtitle'=>$title, 
                      'ShortDescription'=>$shortdescription,
                      'Description'=>$description,
                      'Weight'=>$weight,
                      'UPC'=>$upc,
                      'Manufacturer'=>$manufacturer,
                      'Brand'=>$brand,                      
                      
                      'QuantityInfo'=>array('UpdateType'=>'Absolute',
                                            'Total'=>$total
                                            ),
                      'PriceInfo'=>array('Cost'=>$cost,
                                         'RetailPrice'=>$price,
                                         'TakeItPrice'=>$special_price
                                         ),
                      'ImageList'=>array(
                                'ImageInfoSubmit'=>array(
                                'PlacementName'=>'ITEMIMAGEURL1',
                                'FilenameOrUrl'=>$imageurl)),                      
                      'Classification'=>$classification,
                      'AttributeList'=>array(
                                            'AttributeInfo'=>array(
                                                         array(
                                                              'Name'=>'Size',
                                                              'Value'=>$size
                                                           ),
                                                         array(
                                                              'Name'=>'Brand',
                                                              'Value'=>$brand)
                                                           )
                      ),
                      'VariationInfo'=>array('IsInRelationship'=>true,
                                             'RelationshipName'=>'Color',
                                             'IsParent'=>false,
                                             'ParentSku'=>$parent_sku
                                      ),   
                                      
                       );


Then we need to send above array as a parameter in the method.

$arrData = array(
'accountID'=>$accountID,
'item'=>$iteminfo,
);
                
$result=$client->SynchInventoryItem($arrData);
So this is how you can use CA API in PHP script.