How to Send Order Data in Shipstation Via API Call

Step 1: To create a new order in ship station using through api call in php. First get the ship station api key and merchant id to access that api data.

Step 2: Use that merchant Id and api key in “OneShopAPI.php” file.

<?php

# OneShopAPI: PHP wrapper class for MCSSL.com API

class OneShopAPI
{
    var $_merchantId = "2****3";
	var $_merchantKey = "898c57db*********9fab4bf";
	var $_apiUri = "https://www.mcssl.com";
	var $_apiParameters;

    function OneShopAPI($merchantId, $merchantKey, $apiUri)
    {
        $this->_merchantId = $merchantId;
        $this->_merchantKey = $merchantKey;
        $this->_apiUri = $apiUri;
    }
    # This method is used to add parameters to the
    # $_apiParameters array. This array is used by the
    # CreateRequestString() method.
     function AddApiParameter($parameterKey, $parameterValue)
     {
        # If $parameterKey exists, NULL it out and set the new value
        if (@array_key_exists($parameterKey, $this->_apiParameters))
        {
            $this->_apiParameters[$parameterKey] = NULL;
                 }
        $this->_apiParameters[$parameterKey] = $parameterValue;
     }


    # This method clears the $_apiParameters array
    # so it can be reused.
    function ClearApiParameters()
     {
        $this->_apiParameters = NULL;
     }

    # This method uses the curl object to make
    # a POST request to the api and return the response
    # from the API
    function SendHttpRequest($uri, $request_body)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-POST_DATA_FORMAT: xml'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); # TODO - SET THIS TO true FOR PRODUCTION
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if ($err)
            return $err;
        return $data;
    }

    # This method will call the SendHttpRequest method
    # after appending the proper information to the uri
    # and creating the request body
    function ApiRequest($path, $parameters = "")
    {
        $uri = $this->_apiUri."/API/".$this->_merchantId.$path;
        $request_body = $this->CreateRequestString();
        $result = $this->SendHttpRequest($uri, $request_body);

        return($result);
    }

    # This method will take a properly formatted api uri
    # and create the response body then call the http request method
    function XLinkApiRequest($xlink, $parameters = "")
    {
        $request_body = $this->CreateRequestString();
        $result = $this->SendHttpRequest($xlink, $request_body);
        return($result);
    }

    function CreateRequestString()
    {
        $request_body = "<Request><Key>".$this->_merchantKey."</Key>".$this->ParseApiParameters($this->_apiParameters)."</Request>";
        return $request_body;
    }

    function ParseApiParameters($parameters)
    {
        $request_payload = "";
        if ((!empty($parameters)) && (is_array($parameters)))
        {
            foreach($parameters as $key => $value)
            {
                if (!is_array($value))
                {
                    $request_payload .= ("<".$key.">".$value."</".$key.">\r\n");
                }
                 else
                 {
                    $request_payload .= "<".$key.">\r\n";
                    $request_payload .= $this->create_request($value);
                    $request_payload .= "</".$key.">\r\n";
                }
            }
        }
        return $request_payload;
    }

    function GetOrdersList()
    {
        return($this->ApiRequest("/ORDERS/LIST"));
    }

    function GetOrderById($orderId)
    {
        return($this->ApiRequest("/ORDERS/" . $orderId . "/READ"));
    }

    function GetProductsList()
    {
        return($this->ApiRequest("/PRODUCTS/LIST"));
    }

    function GetProductById($productId)
    {
        return($this->ApiRequest("/PRODUCTS/" . $productId . "/READ"));
    }

    function GetClientsList()
    {
        return($this->ApiRequest("/CLIENTS/LIST"));
    }

    function GetClientById($clientId)
    {
        return($this->ApiRequest("/CLIENTS/". $clientId ."/READ"));
    }

    function GetErrorsList()
    {
        return($this->ApiRequest("/ERRORS/LIST"));
    }

    function GetAvailableApiMethods()
    {
        return($this->ApiRequest(""));
    }
}


?>

Step 3: Use another file “OneShopNotificationListener.php” and change merchant id and key in it.

<?php
    include('OneShopAPI.php');

    # TODO: Add your Merchant ID as the First Parameter, and your Merchant Key as Second Parameter.
    $API = new OneShopAPI("2****3","898c57dbb***********9fab4bf","https://www.mcssl.com");
    
    $requestBodyXML = new DOMDocument();

echo "<pre>";
print_r($API);
print_r($requestBodyXML);
 $notificationType = $requestBodyXML->documentElement->nodeName;  
        $tokenNode = $requestBodyXML->getElementsByTagName('Token')->item(0)->nodeValue;  
      $apiResult = $API->GetOrderById($tokenNode); 
      print_r($apiResult);               
die;
    # Load the request body into XML and check that the result has been parsed into XML    
    if ($requestBodyXML->loadXML($HTTP_RAW_POST_DATA) == true)
    {
        $notificationType = $requestBodyXML->documentElement->nodeName;  
        $tokenNode = $requestBodyXML->getElementsByTagName('Token')->item(0)->nodeValue;  
        switch ($notificationType)
        {            
            case "NewOrder":
                
                $apiResult = $API->GetOrderById($tokenNode);                
               
            break;
            
            default:
                # May have other types of notifications in the future
            break;
        }
        
        $apiResultXML = new DOMDocument(); 
        
        if ($apiResultXML->loadXML($apiResult)==true)
        {            
            # Check if the API returned an error
            $apiSuccess = $apiResultXML->getElementsByTagName('Response')->item(0)->getAttribute('success');
           
           if ($apiSuccess == 'true')
            {
                # TODO: Do something useful with the XML                         
            }
            else
            {
				# TODO: Do something with the error returned by the API
            }
        }
        else
        {
            # TODO: Do something with the xml error to either notify or log that the XML could not be parsed            
        }
    }
    else
    {
        # TODO: Do something with the xml error to either notify or log that the XML could not be parsed	
    }            
?>

Step 4: To send new order data in shipstation account though api call. You need to send Xml object with all new order parameter data. Given below file code describe how to pass new order data using PHP curl code.

<?php

//Store your XML Request in a variable
    $xml_data = '<?xml version="1.0" encoding="utf-8"?>';
$xml_data .= '<Orders>'; 
$xml_data .= '<Order>'; 
$xml_data .= '<OrderID>123456</OrderID>'; 
 $xml_data .= '<OrderNumber>ABC123</OrderNumber>'; 
 $xml_data .= '<OrderDate>12/8/2011 21:56 PM</OrderDate>'; 
 $xml_data .= '<OrderStatus>AwaitingShipment</OrderStatus>'; 
 $xml_data .= '<LastModified>12/8/2011 12:56 PM</LastModified>'; 
 $xml_data .= '<ShippingMethod>USPSPriorityMail</ShippingMethod>'; 
 $xml_data .= '<PaymentMethod>Credit Card</PaymentMethod>'; 
 $xml_data .= '<OrderTotal>123.45</OrderTotal>'; 
 $xml_data .= '<TaxAmount>0.00</TaxAmount>'; 
 $xml_data .= '<ShippingAmount>4.50</ShippingAmount>'; 
 $xml_data .= '<CustomerNotes>Please make sure it gets here by Dec. 22nd!</CustomerNotes>'; 
 $xml_data .= '<InternalNotes>Ship by December 18th via Priority Mail.</InternalNotes>'; 
 $xml_data .= '<Customer>'; 
 $xml_data .= '<CustomerCode>[email protected]</CustomerCode>'; 
 $xml_data .= '<BillTo>';
	 $xml_data .= '<Name>The President</Name>'; 
 $xml_data .= '<Company>US Govt</Company>';
 $xml_data .= '<Phone>512-555-5555</Phone>'; 
 $xml_data .= '<Email>[email protected]</Email>'; 
 $xml_data .= '</BillTo>'; 
 $xml_data .= '<ShipTo>'; 
 $xml_data .= '<Name>The President</Name>'; 
 $xml_data .= '<Company>US Govt</Company>'; 
 $xml_data .= '<Address1>1600 Pennsylvania Ave</Address1>'; 
 $xml_data .= '<Address2></Address2>'; 
 $xml_data .= '<City>Washington</City>'; 
 $xml_data .= '<State>DC</State>'; 
 $xml_data .= '<PostalCode>20500</PostalCode>'; 
 $xml_data .= '<Country>US</Country>'; 
 $xml_data .= '<Phone>512-555-5555</Phone>'; 
 $xml_data .= '</ShipTo>'; 
 $xml_data .= '</Customer>'; 
 $xml_data .= '<Items>'; 
 $xml_data .= '<Item>'; 
 $xml_data .= '<SKU>FD88821</SKU>'; 
 $xml_data .= '<Name>My Product Name</Name>'; 
 $xml_data .= '<ImageUrl>http://www.mystore.com/products/12345.jpg</ImageUrl>'; 
 $xml_data .= '<Weight>8</Weight>'; 
 $xml_data .= '<WeightUnits>Ounces</WeightUnits>'; 
 $xml_data .= '<Quantity>2</Quantity>'; 
 $xml_data .= '<UnitPrice>13.99</UnitPrice>'; 
 $xml_data .= '<Location>A1-B2</Location>'; 
 $xml_data .= '<Options>'; 
 $xml_data .= '<Option>'; 
 $xml_data .= '<Name>Size</Name>';
 $xml_data .= '<Value>Large</Value>'; 
 $xml_data .= '<Weight>10</Weight>'; 
 $xml_data .= '</Option>'; 
 $xml_data .= '<Option>'; 
 $xml_data .= '<Name>Color</Name>'; 
 $xml_data .= '<Value>Green</Value>'; 
 $xml_data .= '<Weight>5</Weight>'; 
 $xml_data .= '</Option>'; 
 $xml_data .= '</Options>'; 
 $xml_data .= '</Item>'; 
 $xml_data .= '</Items>';
 $xml_data .= '</Order>'; 
$xml_data .= '</Orders>';

$xml=html_entity_decode($xml_data);

$URL = "http://articlesflip.com/test/shipstation/OneShopNotificationListener.php";

 
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);

echo"<pre>";
print_r($output);
 
if(curl_errno($ch))
    print curl_error($ch);
else
    curl_close($ch);
?>

You can check new order is placed in merchant account.

Similar Posts

2 Comments

  1. How to use this integration. and XML Code where we put.
    Kindly help me to integrate successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *