Update stock in ChannelAdvisor after an item sold in Magento e-commerce site

Here is the php example for updating stock in Channel Advisor after an item sold in Magento site.

<?php
$order_id=15115; //this will be dynamic, u can use magento webservice or an extension to observe after sales 
update_ca_stock($order_id);
function update_ca_stock($order_id){
//taking order details using order id
$root=$_SERVER['DOCUMENT_ROOT'];
require_once $root.'/app/Mage.php';
Mage::app("default");
$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
 // get order details from magento
$orderValue = number_format ($order->getGrandTotal(), 2, '.' , $thousands_sep = '');
$orderItems = $order->getItemsCollection();
    $skuQtyArray = array();
	$skuDuplArray = array();
	$skuList=array();
	$i=0;
    foreach ($orderItems as $item)
    {
        $product_id = $item->product_id;
        $product_sku = $item->sku;
        $product_name = $item->getName();
        $product_qty = $item->getQtyOrdered();
        $_product = Mage::getModel('catalog/product')->load($product_id);
        $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $product_sku);  
		//use this sectioon only if u have multiple distribution center in CA and its details u can get based on magento backend product attributes
		$location = trim(Mage::getModel('catalog/product')->load($product_id)->getAttributeText('stock_location'));
		if($location=="location" || $location==""):
			$location="CA Distribution center code";
		endif;
		//end distribution center list
        $productType=$product->getTypeID();  //choose SKU as per your store product configuration
        if($productType=='simple')
        {                                                                   
			 $text=explode(" ",$product_sku);
			 $product_sku=$text[0];
			  if(!in_array($product_sku,$skuDuplArray)):
			    $skuQtVal[$i]['sku'] = $product_sku;  //SKU - should match with SKU in CA
				$skuQtVal[$i]['qty']=$product_qty;    //Quantity need to update on CA 
				$skuQtVal[$i]['location']=$location;    //Distribution center code, which need to be added to update Quantity                 
				$skuDuplArray[]=  $product_sku;      //You may get some duplication SKU when u get order details from magento, I used this way to filter out duplicate SKU before do API call to CA
				$skuList['string'][$i]=$product_sku;  //SKU array for check all SKU exists in CA first before start stock update API call. If any SKU in array not exist in CA the API call will return error
				$i++;
			endif;	               
			
        }
		}
	// call custom php function to update CA stock after an item sold
	UpdateCAstock($skuList,$skuQtVal,$order_id);
}
function UpdateCAstock($skuList,$skuQtVal,$order_id){
$root=$_SERVER['DOCUMENT_ROOT'];
require_once($root.'/nusoap/lib/nusoap.php');
$client = new nusoap_client('https://api.channeladvisor.com/ChannelAdvisorAPI/v7/InventoryService.asmx?WSDL', true );
$err = $client->getError();
if ($err)
{
	//error log
}
$developerKey = '';
$password = '';
$headers = '<web:APICredentials>
				<web:DeveloperKey></web:DeveloperKey>
				<web:Password></web:Password>
		   </web:APICredentials>';
$arrData = array('accountID'=>'', 'skuList'=>$skuList);
$result = $client->call('GetInventoryItemList', $arrData, false, false, $headers); //call to get current quantity details in CA 
if($result['GetInventoryItemListResult']['Status']=='Failure'){ //if call failed
				//this section can help if the error is SKU not exists
				$messge=$result['GetInventoryItemListResult']['Message'];
				$fields=explode("Parameter name:",$messge);
				$notExitsSku = trim($fields[1]);
				if(count($skuList['string'])>0){
					$nonExistsSku[0]['SKU']=$notExitsSku;
					$nonExistsSku[0]['Quantity']=1;
					$nonExistsSku[0]['MessageCode']=1;
					$skuList=remove_element_by_value($skuList,$notExitsSku);   // remove non existing SKU
					UpdateCAstock($skuList,$skuQtVal,$order_id); //Call same function again after remove non exists SKU from array list
				}
}elseif ($client->fault)
{
	//error log
}
else
{
$err = $client->getError();
if ($err)
{
	//error log
}
else
{
	$result=$result['GetInventoryItemListResult']['ResultData']['InventoryItemResponse'];
	$i=0;
//This section will prepare Sku List array with quantity need to update on CA based on quatity sold and current stock in CA
if (count($skuList['string'])==1) //for single SKU 
{
		
		$search_result=searchArray($skuQtVal,$result['Sku']);
		$text=explode("+BH+",$search_result);
		$qty=$text[0];
		$location=$text[1];
		 if($qty==""):
			$qty=0;
		endif;
		$skulist['InventoryItemQuantityAndPrice'][$i]['Sku'] = $result['Sku'];
		$resultDc=$result['DistributionCenterList']['DistributionCenterInfoResponse'];
		$l=count($resultDc);
		if($resultDc[0]):
			if($resultDc[0]['DistributionCenterCode']==$location):
				$available_qty=$resultDc[0]['AvailableQuantity'];
			elseif($resultDc[1]['DistributionCenterCode']==$location):
				$available_qty=$resultDc[1]['AvailableQuantity'];
			endif;
		else:
			if($resultDc['DistributionCenterCode']==$location):
				$available_qty=$resultDc['AvailableQuantity'];
			elseif($resultDc['DistributionCenterCode']==$location):
				$available_qty=$resultDc['AvailableQuantity'];
			endif;
		endif;
		if($available_qty>=$qty):
			$skulist['InventoryItemQuantityAndPrice'][$i]['Quantity'] = $available_qty-$qty;
		elseif($available_qty<=0):
			$skulist['InventoryItemQuantityAndPrice'][$i]['Quantity'] = 0;
		elseif($qty>$available_qty):
			$skulist['InventoryItemQuantityAndPrice'][$i]['Quantity'] = 0;
		endif;
		$skulist['InventoryItemQuantityAndPrice'][$i]['UpdateType'] = 'Available';
		$skulist['InventoryItemQuantityAndPrice'][$i]['DistributionCenterCode'] = $location;
}
else
{
 
  foreach($result as $res){  //if multiple SKU need to update
		//$qty=$skuQtVal[$i]['qty'];
		$search_result=searchArray($skuQtVal,$res['Sku']);
		$text=explode("+BH+",$search_result);
		$qty=$text[0];
		$location=$text[1];
		if($qty==""):
			$qty=0;
		endif;
		$skulist['InventoryItemQuantityAndPrice'][$i]['Sku'] = $res['Sku'];
		$skulist['InventoryItemQuantityAndPrice'][$i]['UpdateType'] = 'Available';
		$resultDc=$res['DistributionCenterList']['DistributionCenterInfoResponse'];
		$l=count($resultDc);
		if($resultDc[0]):
			if($resultDc[0]['DistributionCenterCode']==$location):
				$available_qty=$resultDc[0]['AvailableQuantity'];
			elseif($resultDc[1]['DistributionCenterCode']==$location):
				$available_qty=$resultDc[1]['AvailableQuantity'];
			endif;
		else:
			if($resultDc['DistributionCenterCode']==$location):
				$available_qty=$resultDc['AvailableQuantity'];
			elseif($resultDc['DistributionCenterCode']==$location):
				$available_qty=$resultDc['AvailableQuantity'];
			endif;
		endif;
		if($available_qty>=$qty):
			$skulist['InventoryItemQuantityAndPrice'][$i]['Quantity'] = $available_qty-$qty;
		elseif($available_qty<=0):
			$skulist['InventoryItemQuantityAndPrice'][$i]['Quantity'] = 0;
		elseif($qty>$available_qty):
			$skulist['InventoryItemQuantityAndPrice'][$i]['Quantity'] = 0;
		endif;
		$skulist['InventoryItemQuantityAndPrice'][$i]['DistributionCenterCode'] = $location;
		$i++;
	}
}
	$arrData = array('accountID'=>'', 'itemQuantityAndPriceList'=>$skulist);
// Call the SOAP method and send to CA API for update stock
	$result = $client->call('UpdateInventoryItemQuantityAndPriceList', $arrData, false, false, $headers);

		if ($client->fault)
			{
				
			}
			else
			{
			$err = $client->getError();
			if ($err)
			{
				
			}
			else
			{
				echo "Success"; //if call return success message
			}
			}
			
	//end
}
}


}
function remove_element_by_value($arr, $val) {
   $return = array(); 
   foreach($arr as $k => $v) {
      if(is_array($v)) {
         $return[$k] = remove_element_by_value($v, $val); //recursion
         continue;
      }
      if($v == $val) continue;
      $return[$k] = $v;
   }
   return $return;
}
function searchArray($skuQtVal,$sku){
		$sku_found=0;
		$l=count($skuQtVal);
		for($j=0;$j<=$l-1;$j++){
			if($skuQtVal[$j]['sku']==$sku):
				$sku_found=1;
				$qty=$skuQtVal[$j]['qty'];
				$location=$skuQtVal[$j]['location'];
				
				break;
			endif;
		
		}
		if($sku_found==1):
			return $qty."+BH+".$location;
		else:
			return 0;
		endif;
		
	}
	

?>