Magento Integration Suite:API Integrations

From XTENTO Support Wiki
Jump to: navigation, search


This article describes lots of different scenarios for API connections that can be realized using our modules. Also, sample code and guidance/ideas for implementation are provided. This is no "definitive guide" on how to connect an API - each and every API is completely different - but those ideas, and the sample code should make it a lot easier for you.

Do note you don't have to do this yourself: Using our Magento order export, stock import, tracking import, order import and product export modules, almost any API can be connected. Feel free to send us the documentation of your API to [email protected] and we will be happy to provide a quote. Not more than a couple hours of work usually!

Contents

Magento 1

Sample code / API scenarios for Magento 1. For Magento 2, scroll down to the Magento 2 section.

Order Export

Using the Order Export Module you can easily send your orders/invoices/shipments/credit memos/customers to almost any kind of API or webservice. Sample scenarios/implementations are described below.

Sending orders via HTTP Post

XSL Template

In your export profile at "Sales > Sales Export > Export Profiles" in the "Output Format" tab an XSL template must be configured. The XSL template defines the output format which gets sent to the API, so it's responsible of building CSV/XML/JSON or whatever data that is sent to your API. Sample XSL templates in the JSON or XML format can be found here: JSON_XSL_Template and XML_XSL_Template You will need to adjust them to your requirements so the data is built according to whatever the API expects.

It is important to assign the export destination to the export profile, this can be done in the "Export Destination" tab in your export profile. The export destination can be created at "Sales > Sales Export > Export Destinations", typically this would be the "HTTP Server" destination type for a custom API function. The function name you enter in the custom destination is defined by whatever you call the function (see below in our sample code, there it's "functionName" typically)

PHP / Destination Code

Sample code for a basic authentication, POST method, with a JSON or XML data format:

Your API function needs to be configured in the Http.php file placed in the "app/code/local/Xtento/OrderExport/Model/Destination/" folder in your Magento root directory. You can rename the "Http.php.sample" file to "Http.php" first.

Code for a simple HTTP POST API, sends your order XML/CSV/.. to an API (order XML/CSV/... is stored in $fileContent - which contains the generated order XML/CSV/whatever, defined by your XSL Template)

    public function functionName($fileArray)
    {
        foreach ($fileArray as $filename => $fileContent) {
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com/CreateOrder'); //this is the API URL where the request will be sent
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1); //returns the transfer as a string of the return value of curl_exec() instead of outputting it directly
            curl_setopt($curlClient, CURLOPT_POST, 1); // the POST method
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, $fileContent); // the variable $fileContent matches the data format defined in the export profile in the "Output Format" tab
	    curl_setopt($curlClient, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // an example for a JSON format, XML would be 'Content-Type: application/xml'
	    curl_setopt($curlClient, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // basic HTTP authentication, other possible parameters are CURLAUTH_DIGEST, CURLAUTH_BEARER and others
	    curl_setopt($curlClient, CURLOPT_USERPWD, 'user:password'); // the authentication credentials
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $result = curl_exec($curlClient);
            curl_close($curlClient);
 
            // Log result
            $logEntry = Mage::registry('export_log');
            #$logEntry->setResult(Xtento_OrderExport_Model_Log::RESULT_WARNING);
            $logEntry->addResultMessage(Mage::helper('xtento_orderexport')->__('Destination "%s" (ID: %s): %s', $this->getDestination()->getName(), $this->getDestination()->getId(), htmlentities($result)));
        }
    }

Authentication using a token: Get an authentication token from an API first, then build a Bearer authentication token and send your orders (which are stored in $fileContent - which contains the generated order XML/CSV/whatever, defined by your XSL Template) to an API.

    public function functionName($fileArray)
    {
        $getTokenJson = json_decode(file_get_contents("https://api-url.com/authenticate?apiKey=xxxxx-yyyyy-zzzzz")); // getting a token using your auth. key, please note there are more ways how to receive a token
        $token = $getTokenJson->sessionToken;
        $authorization ='Authorization: Bearer ' . $token;
 
        foreach ($fileArray as $filename => $fileContent) {
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization)); //the HTTPHEADER option with the token as a parameter
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com/api/CreateOrder'); //this is the API URL where the request will be sent
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1); //returns the transfer as a string of the return value of curl_exec() instead of outputting it directly
            curl_setopt($curlClient, CURLOPT_POST, 1); // the POST method
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, $fileContent); // the variable $fileContent matches the data format defined in the export profile in the "Output Format" tab
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $result = curl_exec($curlClient);
            curl_close($curlClient);
 
            // Log result
            $logEntry = Mage::registry('export_log');
            #$logEntry->setResult(Xtento_OrderExport_Model_Log::RESULT_WARNING);
            $logEntry->addResultMessage(Mage::helper('xtento_orderexport')->__('Destination "%s" (ID: %s): %s', $this->getDestination()->getName(), $this->getDestination()->getId(), htmlentities($result)));
        }
    }

Sending orders to a SOAP-API

Need to send your orders/invoices/... to a SOAP-API? No problem. This should get you started, and of course, must be adjusted to the API you want to have Magento talk to.

XSL Template

A sample SOAP XSL Template which produces SOAP-XML for orders exported can be downloaded here: SOAP_XSL_Template. Please note this is just a sample XSL template. Usually you would get a WSDL link to the SOAP XML schema, such a link can be opened in the Boomerang plugin for Google Chrome or a similar application. Using this or a similar plugin you can create a SOAP API request and take a look at the request and response XML formats. The "request" format is what you need to build using your XSL Template, as that is what our extension will then generate, and what the code below will send to the SOAP API then. An XSL template exporting in such a format needs to be created in the "Output Format" tab in the export profile at "Sales > Sales Export > Export Profiles".

PHP / Destination Code

Your API function needs to be configured in the Http.php file placed in the "app/code/local/Xtento/OrderExport/Model/Destination/" folder in your Magento root directory. You can rename the "Http.php.sample" file to "Http.php" first.

    public function yourFunctionName($fileArray)
    {
        foreach ($fileArray as $filename => $fileContent) {
            $soapRequest = $fileContent;
            $header = array( // the header is nexessary to specify the SOAP call parameters, usually the SOAP service provider provides you with the details
                "Content-type: text/xml;charset=\"utf-8\"",
                "Accept: text/xml",
                "Cache-Control: no-cache",
                "Pragma: no-cache",
                "SOAPAction: \"SubmitOrder\"", // IMPORTANT: Must be adjusted as this is specific for each SOAP service, you can see this in your WSDL file in "soapAction" node
                "Content-length: " . strlen($soapRequest),
            );
 
            $soap_do = curl_init();
            curl_setopt($soap_do, CURLOPT_URL, "http://soap-url.com/Service.svc"); // You can find this URL in the WSDL file, node soap:address location
            curl_setopt($soap_do, CURLOPT_PORT, 80); // here you can set the port, usually it's 80
            curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($soap_do, CURLOPT_TIMEOUT, 30);
            curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($soap_do, CURLOPT_POST, true); // the POST method
            curl_setopt($soap_do, CURLOPT_POSTFIELDS, $soapRequest);
            curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
 
	    $result = curl_exec($soap_do);
            if ($result === false) {
                $err = 'Curl error: ' . curl_error($soap_do);
                curl_close($soap_do);
            } else {
                curl_close($soap_do);
                $err = 'Operation completed without any errors: '.$result;
            }
            $logEntry = Mage::registry('export_log');
            $logEntry->addResultMessage(Mage::helper('xtento_orderexport')->__('Destination "%s" (ID: %s): %s', $this->getDestination()->getName(), $this->getDestination()->getId(), 'API returned: ' . $err));
        }
    }

Tracking Import

The Tracking Import Module allows you to query almost any webservice/API and fetch/import tracking numbers and shipment information from it into Magento. Sample scenarios/implementations are described below.

Getting orders from last 14 days, query API

The Http.php.sample file which needs to be renamed to Http.php can be found on your Magento server, in the Magento root directory in the "app/code/local/Xtento/TrackingImport/Model/Source/" folder.

This is sample code on how to get last 14 days of orders, compile the order numbers into a variable and query an API.

    public function yourFunctionName()
    {
        $filesToProcess = array();
        $orderCollection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('increment_id')
            ->addAttributeToFilter(
                'status', array( // the order status can be filtered so we avoid canceled orders for example
                'in' => array(
                    'processing',
                    'shipped',
                    'pending'
                )
            )
            )
            ->addFieldToFilter(
                'created_at', array(
                'from' => strtotime('-14 day', time()), // in this example orders from the last 14 days would be requested in the API call
                'to' => time(),
                'datetime' => true
            )
            );
 
 
        foreach ($orderCollection as $order) {
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api_url.com/api/v3/orders/'.$order->getIncrementId());
           // here the CURL parameters and the CURL call would continue, see below on the other examples

Fetch tracking numbers from a REST-API

        foreach ($orderCollection as $order) { // see above how to define the $orderCollection variable
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com?OrderRef=' . $order->getIncrementId());
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1);
 
            $header = array();
            $header[] = 'Content-type: application/json';
            $header[] = 'Authorization: account=12345, pass=pass123';
            curl_setopt($curlClient, CURLOPT_HTTPHEADER, $header);
 
            /*curl_setopt($curlClient, CURLOPT_POST, 1);
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, array());*/ // an example for a post method
 
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $fileContents = curl_exec($curlClient);  // the $fileContents variable would contain the data returned from the API, the data format needs to be mapped 
            //in the "File Mapping" tab in your import profile
            curl_close($curlClient);
            // process / parse the data here...
 
            $filesToProcess[] = array('source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download', 'data' => $fileContents); 
        }
 
        // Return files to process
        return $filesToProcess; // in this variable the values returned from API get stored. The data must be mapped in the "File Mapping" tab in the import profile

In case the API returns a JSON format you would have to convert the data to either a CSV or an XML format. A ready class to convert a JSON format to XML can be downloaded here: Array2XML You can add this class to the Http.php file and use it like this:

        $orders = json_decode($fileContents); // $fileContents holds the data returned from API
        $orders = json_decode(json_encode($orders), true); //stdClass to Array
        $orderNumbersXml = Array2XML::createXML('rows', $orders);
        $data = $orderNumbersXml->saveXML(); // $data is now a JSON converted to XML

In the import profile in the "File Mapping" tab you can now map the fields according to the XML format you converted using the Array2XML class. See our wiki article about how to map the XML format here: Mapping XML Fields

Fetch tracking numbers from a SOAP-API

This is a more complex SOAP API sample code including the token authentication, reading the Magento orders not older than 14 days with order statuses filters applied. The function returns the $filesToProcess variable. The format of this variable needs to be mapped in the "File Mapping" tab in the import profile at "Sales > Tracking Import > Import Profiles". Out of the box you can map the XML or CSV formats, JSON needs to be converted to either XML or CSV.

    public function yourFunction()
    {
        // Settings
        $apiUrl = "http://apiURL.com/WebOrders.asmx?WSDL"; 
        $apiUser = "someUsername";
        $apiPass = "somePassword";
 
        // in this variable the values returned from API get stored, these are then mapped in the "File Mapping" tab in the import profile
        $filesToProcess = [];
 
        $soapClient = new SoapClient(
            $apiUrl, array('trace' => 1)
        );
        $sh_param = array(
            'AuthenticationToken' => '',
            'ErrorMessage' => ''
        );
        $headers = new
        SoapHeader(
            'http://apiURL.com/WebOrders',
            'WebServiceHeader', $sh_param
        );
        $soapClient->__setSoapHeaders(array($headers));
        $ap_param = array(
            'Username' => $apiUser,
            'Password' => $apiPass
        );
        try {
            $res = $soapClient->GetAuthenticationToken($ap_param); // getting the authentication token
        } catch (SoapFault $fault) {
            $logEntry = $this->_registry->registry('trackingimport_log');
            $logEntry->setResult(\Xtento\TrackingImport\Model\Log::RESULT_WARNING);
            $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
	    'GetAuthenticationToken returned the following error: ' . $fault->faultcode . '-' . $fault->faultstring));
            return [];
        }
        $authToken = $res->GetAuthenticationTokenResult;
        if (!empty($authToken)) {
            // Orders to query
        $collection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('increment_id')
            ->addAttributeToFilter(
                'status', array( // the order status can be filtered so we avoid canceled orders for example
                'in' => array(
                    'processing',
                    'shipped',
                    'pending'
                )
            )
            )
            ->addFieldToFilter(
                'created_at', array(
                'from' => strtotime('-14 day', time()), // in this example orders from the last 14 days would be requested in the API call
                'to' => time(),
                'datetime' => true
            )
            );
 
            foreach ($collection as $order) {  // looping through the orders from the last teo weeks and sending the request to API
                $sh_param = array(
                    'AuthenticationToken' => $authToken,
                );
                $headers = new
                SoapHeader(
                    'http://apiURL.com/WebOrders',
                    'WebServiceHeader', $sh_param
                );
                $soapClient->__setSoapHeaders(array($headers));
                try {
                    $res = $soapClient->GetDespatchedOrderDetails(array('orderReference' => $order->getExtOrderId())); // reading the order info / tracking numbers from API
                } catch (SoapFault $fault) {
                    $logEntry = $this->_registry->registry('trackingimport_log');
                    $logEntry->setResult(\Xtento\TrackingImport\Model\Log::RESULT_WARNING);
                    $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
		    'GetDespatchedOrderDetails for order '.$order->getIncrementId().' returned the following error: ' . $fault->faultcode . '-' . $fault->faultstring));
                    return [];
                }
                $sxe = new \SimpleXMLElement($soapClient->__getLastResponse());
                $sxe->registerXPathNamespace(
                    'c',
                    'http://apiURL.com/WebOrders'
                );
                $result = $sxe->xpath('//c:ErrorMessage');
                if (!empty($result) && isset($result[0]) && !empty($result[0])) {
                    $logEntry = $this->_registry->registry('trackingimport_log');
                    $logEntry->setResult(\Xtento\TrackingImport\Model\Log::RESULT_WARNING);
                    $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
		    'GetDespatchedOrderDetails for order '.$order->getIncrementId().' - error: ' . $result[0]));
                    return [];
                }
                $xmlResult = $res->GetDespatchedOrderDetailsResult;
 
                $filesToProcess[] = ['source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download', 'data' => $xmlResult];
            }
        } else {
            $logEntry = $this->_registry->registry('trackingimport_log');
            $logEntry->setResult(\Xtento\TrackingImport\Model\Log::RESULT_WARNING);
            $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
	    'GetAuthenticationToken failed, no authentication token returned'));
            return [];
        }
 
        // Return files to process
        return $filesToProcess;
    }

Stock Import

Using the Stock Import Module you can query webservices/APIs and import the retrieved stock levels into Magento. Sample scenarios/implementations are described below.

Getting all products programmatically, query API

This sample code allows you to get all your product SKUs into a variable, comma-separate it and query an API.

        $filesToProcess = array();
        $readAdapter = Mage::getSingleton('core/resource')->getConnection('core_read');
        $select = $readAdapter->select()
            ->from(Mage::getSingleton('core/resource')->getTableName('catalog/product'), array('entity_id', 'sku'));
        $products = $readAdapter->fetchAll($select);
        $productsArray = array();
        foreach ($products as $product) {
            array_push($productsArray, $product['sku']);
        }

Fetch stock levels from a REST-API

Your API function needs to be configured in the Http.php file placed in the "app/code/local/Xtento/StockImport/Model/Source/" folder in your Magento root directory. You can rename the "Http.php.sample" file to "Http.php" first.

    public function yourFunctionName()
    {
        $filesToProcess = array();
        $curlClient = curl_init();
        curl_setopt($curlClient, CURLOPT_URL, 'http://api-url.com/GetStock'); // the URL of the API
        curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlClient, CURLOPT_POST, 1);  // the POST method
        curl_setopt($curlClient, CURLOPT_POSTFIELDS, 'LanguageCode=EN&apiKey=xxx-yyy-zzz&clientID=12345678'); // additional parameters / fields
        curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
        $fileContents = curl_exec($curlClient); // this variable contains the data format from the API, for example A JSON, XML or CSV format. 
        //The fields from the response format must be mapped in the import profile at "Catalog > Stock Import > Import Profiles", in an import profile in the "File Mapping" tab
        curl_close($curlClient);
 
        $filesToProcess[] = array('source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download', 'data' => $fileContents); // Set a filename here. 'data' must contain
        // the returned string from the HTTP source which will then be imported
 
        // Return files to process
        return $filesToProcess;
    }


In the import profile in the "File Mapping" tab you can now map the fields according to the XML format you converted using the Array2XML class. See our wiki article about how to map the XML format here: File_Configuration

Fetch stock levels from a SOAP-API

    public function yourFunctionName()
    {
 
        $filesToProcess = array();
        $readAdapter = Mage::getSingleton('core/resource')->getConnection('core_read');
        $select = $readAdapter->select()
            ->from(Mage::getSingleton('core/resource')->getTableName('catalog/product'), array('entity_id', 'sku'));
        $products = $readAdapter->fetchAll($select);
        $productsArray = array();
        foreach ($products as $product) {
            array_push($productsArray, $product['sku']);
        }
 
        $client = new SoapClient("https://api-url?wsdl", array('soap_version' => SOAP_1_1, 'exceptions' => true, 'trace' => 1)); // using a SoapClient
        try {
            $result = $client->getStockUpdate(implode(",", $productsArray), '1', 'filename.XML', 'password');
        } catch (Exception $e) {
        }
        if ($result && !empty($result)) {
            $filesToProcess[] = array('source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download_'.uniqid().'.xml', 'data' => $client->__getLastResponse()); // Set a filename here.
        // 'data' must contain the returned string from the HTTP source which will then be imported
        }
 
        // Return files to process, the format of the returned data needs to be mapped in the "File Configuration" tab in the import profile at "Catalog > Stock Import > Import Profiles"
        return $filesToProcess;
    }

Product Export

The Product Feed Export Module can be used to send products to webservices/APIs. Send your products to APIs - fully automatically.

Sending products via HTTP Post

XSL Template

The XSL Template can be configured in the "Output Format" tab in your export profile at "Catalog > Product Export > Export Profiles". A sample XSL template in the XML output format can be downloaded here: XML XSL Template The output format would define the format which gets sent to the API, please see below for further instructions about how to configure the API calls.

PHP / Destination Code

Your API function needs to be configured in the Http.php file placed in the "app/code/local/Xtento/ProductExport/Model/Destination/" folder in your Magento root directory. You can rename the "Http.php.sample" file to "Http.php" first.

    public function yourFunctionName($fileArray)
    {
        // Do whatever - sample code for a HTTP request below.
        foreach ($fileArray as $filename => $fileContent) {
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com/CreateProduct'); //this is the API URL where the request will be sent
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1); //returns the transfer as a string of the return value of curl_exec() instead of outputting it directly
            curl_setopt($curlClient, CURLOPT_POST, 1); // the POST method
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, $fileContent); // the variable $fileContent matches the data format defined in the export profile in the "Output Format" tab
	    curl_setopt($curlClient, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // an example for a JSON format, XML would be 'Content-Type: application/xml'
	    curl_setopt($curlClient, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // basic HTTP authentication, other possible parameters are CURLAUTH_DIGEST, CURLAUTH_BEARER and others
	    curl_setopt($curlClient, CURLOPT_USERPWD, 'username:password'); // the authentication credentials
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $result = curl_exec($curlClient);
            curl_close($curlClient);
        }
    }

Magento 2

Sample code / API scenarios for Magento 2. For Magento 1, scroll to the top of the page to the Magento 1 section.

Order Export

Using the Order Export Module you can easily send your orders/invoices/shipments/credit memos to almost any kind of API or webservice. Sample scenarios/implementations are described below.

Sending orders via HTTP Post

XSL Template

In your export profile at "Sales > Sales Export > Export Profiles" in the "Output Format" tab an XSL template must be configured. The XSL template defines the output format which gets sent to the API, so it's responsible of building CSV/XML/JSON or whatever data that is sent to your API. Sample XSL templates in the JSON or XML format can be found here: JSON_XSL_Template and XML_XSL_Template You will need to adjust them to your requirements so the data is built according to whatever the API expects.

It is important to assign the export destination to the export profile, this can be done in the "Export Destination" tab in your export profile. The export destination can be created at "Sales > Sales Export > Export Destinations", typically this would be the "HTTP Server" destination type for a custom API function. The function name you enter in the custom destination is defined by whatever you call the function (see below in our sample code, there it's "functionName" typically)

PHP / Destination Code

Sample code for a basic authentication, POST method, with a JSON or XML data format:

Your API function needs to be configured in the Http.php file placed in the "app/code/local/Xtento/OrderExport/Model/Destination/" folder in your Magento root directory. You can rename the "Http.php.sample" file to "Http.php" first.

Code for a simple HTTP POST API, sends your order XML/CSV/.. to an API (order XML/CSV/... is stored in $fileContent - which contains the generated order XML/CSV/whatever, defined by your XSL Template)

    public function functionName($fileArray)
    {
        foreach ($fileArray as $filename => $fileContent) {
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com/CreateOrder'); //this is the API URL where the request will be sent
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1); //returns the transfer as a string of the return value of curl_exec() instead of outputting it directly
            curl_setopt($curlClient, CURLOPT_POST, 1); // the POST method
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, $fileContent); // the variable $fileContent matches the data format defined in the export profile in the "Output Format" tab
	    curl_setopt($curlClient, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // an example for a JSON format, XML would be 'Content-Type: application/xml'
	    curl_setopt($curlClient, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // basic HTTP authentication, other possible parameters are CURLAUTH_DIGEST, CURLAUTH_BEARER and others
	    curl_setopt($curlClient, CURLOPT_USERPWD, 'user:password'); // the authentication credentials
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $result = curl_exec($curlClient);
            curl_close($curlClient);
 
            // Log result
            $logEntry = $this->_registry->registry('orderexport_log');
            #$logEntry->setResult(\Xtento\OrderExport\Model\Log::RESULT_WARNING);
            $logEntry->addResultMessage(__('Destination "%1" (ID: %2): %3', $this->getDestination()->getName(), $this->getDestination()->getId(), htmlentities($result)));
        }
    }

Authentication using a token: Get an authentication token from an API first, then build a Bearer authentication token and send your orders (which are stored in $fileContent - which contains the generated order XML/CSV/whatever, defined by your XSL Template) to an API.

    public function functionName($fileArray)
    {
        $getTokenJson = json_decode(file_get_contents("https://api-url.com/authenticate?apiKey=xxxxx-yyyyy-zzzzz")); // getting a token using your auth. key, please note there are more ways how to receive a token
        $token = $getTokenJson->sessionToken;
        $authorization ='Authorization: Bearer ' . $token;
 
        foreach ($fileArray as $filename => $fileContent) {
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization)); //the HTTPHEADER option with the token as a parameter
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com/api/CreateOrder'); //this is the API URL where the request will be sent
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1); //returns the transfer as a string of the return value of curl_exec() instead of outputting it directly
            curl_setopt($curlClient, CURLOPT_POST, 1); // the POST method
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, $fileContent); // the variable $fileContent matches the data format defined in the export profile in the "Output Format" tab
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $result = curl_exec($curlClient);
            curl_close($curlClient);
 
            // Log result
            $logEntry = $this->_registry->registry('orderexport_log');
            #$logEntry->setResult(\Xtento\OrderExport\Model\Log::RESULT_WARNING);
            $logEntry->addResultMessage(__('Destination "%1" (ID: %2): %3', $this->getDestination()->getName(), $this->getDestination()->getId(), htmlentities($result)));
        }
    }

Sending orders to a SOAP-API

Need to send your orders/invoices/... to a SOAP-API? No problem. This should get you started, and of course, must be adjusted to the API you want to have Magento talk to.

XSL Template

A sample SOAP XSL Template which produces SOAP-XML for orders exported can be downloaded here: SOAP_XSL_Template. Please note this is just a sample XSL template. Usually you would get a WSDL link to the SOAP XML schema, such a link can be opened in the Boomerang plugin for Google Chrome or a similar application. Using this or a similar plugin you can create a SOAP API request and take a look at the request and response XML formats. The "request" format is what you need to build using your XSL Template, as that is what our extension will then generate, and what the code below will send to the SOAP API then. An XSL template exporting in such a format needs to be created in the "Output Format" tab in the export profile at "Sales > Sales Export > Export Profiles".

PHP / Destination Code

Your API function needs to be configured in the Http.php file placed in the "app/code/local/Xtento/OrderExport/Model/Destination/" folder in your Magento root directory. You can rename the "Http.php.sample" file to "Http.php" first.

    public function yourFunctionName($fileArray)
    {
        foreach ($fileArray as $filename => $fileContent) {
            $soapRequest = $fileContent;
            $header = array( // the header is nexessary to specify the SOAP call parameters, usually the SOAP service provider provides you with the details
                "Content-type: text/xml;charset=\"utf-8\"",
                "Accept: text/xml",
                "Cache-Control: no-cache",
                "Pragma: no-cache",
                "SOAPAction: \"SubmitOrder\"", // IMPORTANT: Must be adjusted as this is specific for each SOAP service, you can see this in your WSDL file in "soapAction" node
                "Content-length: " . strlen($soapRequest),
            );
 
            $soap_do = curl_init();
            curl_setopt($soap_do, CURLOPT_URL, "http://soap-url.com/Service.svc"); // You can find this URL in the WSDL file, node soap:address location
            curl_setopt($soap_do, CURLOPT_PORT, 80); // here you can set the port, usually it's 80
            curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($soap_do, CURLOPT_TIMEOUT, 30);
            curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($soap_do, CURLOPT_POST, true); // the POST method
            curl_setopt($soap_do, CURLOPT_POSTFIELDS, $soapRequest);
            curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
 
	    $result = curl_exec($soap_do);
            if ($result === false) {
                $err = 'Curl error: ' . curl_error($soap_do);
                curl_close($soap_do);
            } else {
                curl_close($soap_do);
                $err = 'Operation completed without any errors: '.$result;
            }
            // Log result
            $logEntry = $this->_registry->registry('orderexport_log');
            #$logEntry->setResult(\Xtento\OrderExport\Model\Log::RESULT_WARNING);
            $logEntry->addResultMessage(__('Destination "%1" (ID: %2): %3', $this->getDestination()->getName(), $this->getDestination()->getId(), htmlentities($result)));
        }
    }

Tracking Import

The Tracking Import Module allows you to query almost any webservice/API and fetch/import tracking numbers and shipment information from it into Magento. Sample scenarios/implementations are described below.

Getting orders from last 14 days, query API

This is sample code on how to get last 14 days of orders, compile the order numbers into a variable and query an API.

        // Orders to query
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $collection = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\Collection');
        $collection->addFieldToSelect('increment_id');
        $collection->addFieldToFilter(
            'created_at', array(
                'from' => strtotime('-21 day', time()),
                'to' => time(),
                'datetime' => true
            )
        );
        $collection->addFieldToFilter('status', array('nin' => array('canceled', 'closed', 'complete')));
 
        foreach ($collection as $order) { // go through the orders and request the tracking numbers for each of them in the further code
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api_url.com/api/tracking/'.$order->getIncrementId());
           // here the CURL parameters and the CURL call would continue, see below on the other examples

Fetch tracking numbers from a REST-API

        foreach ($orderCollection as $order) { // see above how to define the $orderCollection variable
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com?OrderRef=' . $order->getIncrementId());
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1);
 
            $header = array();
            $header[] = 'Content-type: application/json';
            $header[] = 'Authorization: account=12345, pass=pass123';
            curl_setopt($curlClient, CURLOPT_HTTPHEADER, $header);
 
            /*curl_setopt($curlClient, CURLOPT_POST, 1);
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, array());*/ // an example for a post method
 
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $fileContents = curl_exec($curlClient);  // the $fileContents variable would contain the data returned from the API, the data format needs to be mapped 
            //in the "File Mapping" tab in your import profile
            curl_close($curlClient);
            // process / parse the data here...
 
            $filesToProcess[] = array('source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download', 'data' => $fileContents); 
        }
 
        // Return files to process
        return $filesToProcess; // in this variable the values returned from API get stored. The data must be mapped in the "File Mapping" tab in the import profile

In case the API returns a JSON format you would have to convert the data to either a CSV or an XML format. A ready class to convert a JSON format to XML can be downloaded here: Array2XML You can add this class to the Http.php file and use it like this:

        $arr = json_decode($fileContents);
        $arr = json_decode(json_encode($arr), true);
        $xml = \Xtento\TrackingImport\Model\Source\Array2XML::createXML('rows', $arr);
        $data = $xml->saveXML();
        $filesToProcess[] = ['source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download', 'data' => $data]; // Set a filename here. 'data' must contain the returned string from the HTTP source which will

In the import profile in the "File Mapping" tab you can now map the fields according to the XML format you converted using the Array2XML class. See our wiki article about how to map the XML format here: Mapping XML Fields

Fetch tracking numbers from a SOAP-API

public function yourFunction()
    {
        // Settings
        $apiUrl = "http://apiURL.com/WebOrders.asmx?WSDL"; 
        $apiUser = "someUsername";
        $apiPass = "somePassword";
 
        // in this variable the values returned from API get stored, these are then mapped in the "File Mapping" tab in the import profile
        $filesToProcess = [];
 
        $soapClient = new \SoapClient(
            $apiUrl, array('trace' => 1)
        );
        $sh_param = array(
            'AuthenticationToken' => '',
            'ErrorMessage' => ''
        );
        $headers = new
        \SoapHeader(
            'http://apiURL.com/WebOrders',
            'WebServiceHeader', $sh_param
        );
        $soapClient->__setSoapHeaders(array($headers));
        $ap_param = array(
            'Username' => $apiUser,
            'Password' => $apiPass
        );
        try {
            $res = $soapClient->GetAuthenticationToken($ap_param); // getting the authentication token
        } catch (\SoapFault $fault) {
            $logEntry = $this->_registry->registry('trackingimport_log');
            $logEntry->setResult(\Xtento\TrackingImport\Model\Log::RESULT_WARNING);
            $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
	    'GetAuthenticationToken returned the following error: ' . $fault->faultcode . '-' . $fault->faultstring));
            return [];
        }
        $authToken = $res->GetAuthenticationTokenResult;
        if (!empty($authToken)) {
            // Orders to query
        $collection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('increment_id')
            ->addAttributeToFilter(
                'status', array( // the order status can be filtered so we avoid canceled orders for example
                'in' => array(
                    'processing',
                    'shipped',
                    'pending'
                )
            )
            )
            ->addFieldToFilter(
                'created_at', array(
                'from' => strtotime('-14 day', time()), // in this example orders from the last 14 days would be requested in the API call
                'to' => time(),
                'datetime' => true
            )
            );
 
            foreach ($collection as $order) {  // looping through the orders from the last teo weeks and sending the request to API
                $sh_param = array(
                    'AuthenticationToken' => $authToken,
                );
                $headers = new
                \SoapHeader(
                    'http://apiURL.com/WebOrders',
                    'WebServiceHeader', $sh_param
                );
                $soapClient->__setSoapHeaders(array($headers));
                try {
                    $res = $soapClient->GetDespatchedOrderDetails(array('orderReference' => $order->getExtOrderId())); // reading the order info / tracking numbers from API
                } catch (\SoapFault $fault) {
                    $logEntry = $this->_registry->registry('trackingimport_log');
                    $logEntry->setResult(Log::RESULT_WARNING);
                    $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
		    'GetDespatchedOrderDetails for order '.$order->getIncrementId().' returned the following error: ' . $fault->faultcode . '-' . $fault->faultstring));
                    return [];
                }
                $sxe = new \SimpleXMLElement($soapClient->__getLastResponse());
                $sxe->registerXPathNamespace(
                    'c',
                    'http://apiURL.com/WebOrders'
                );
                $result = $sxe->xpath('//c:ErrorMessage');
                if (!empty($result) && isset($result[0]) && !empty($result[0])) {
                    $logEntry = $this->_registry->registry('trackingimport_log');
                    $logEntry->setResult(Log::RESULT_WARNING);
                    $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
		    'GetDespatchedOrderDetails for order '.$order->getIncrementId().' - error: ' . $result[0]));
                    return [];
                }
                $xmlResult = $res->GetDespatchedOrderDetailsResult;
 
                $filesToProcess[] = ['source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download', 'data' => $xmlResult];
            }
        } else {
            $logEntry = $this->_registry->registry('trackingimport_log');
            $logEntry->setResult(Log::RESULT_WARNING);
            $logEntry->addResultMessage(__('Source "%1" (ID: %2): %3', $this->getSource()->getName(), $this->getSource()->getId(),
	    'GetAuthenticationToken failed, no authentication token returned'));
            return [];
        }
 
        // Return files to process
        return $filesToProcess;
    }

Stock Import

Using the Stock Import Module you can query webservices/APIs and import the retrieved stock levels into Magento. Sample scenarios/implementations are described below.

Getting all products programmatically, query API

This sample code allows you to get all your product SKUs into a variable, comma-separate it and query an API.

        $collection = $this->objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection');
        $collection->addAttributeToSelect('sku');
        $skus = [];
        foreach ($collection as $product) {
            $skus[] = $product->getSku();
        }
 
        $chunks = array_chunk($skus, 50); // in case API would process max. 50 products at once
 
        $filesToProcess = [];
        $i = 0;
        foreach ($chunks as $chunk) {
            $i++;
            $curlClient = curl_init();
            $url = 'https://api-url.com/api/v5/inventory?itemNumbers=' . implode(",", $chunk); // this creates a URL with the SKUs separated by a comma

Fetch stock levels from a REST-API

    public function yourFunctionName()
    {
        $filesToProcess = array();
        $curlClient = curl_init();
        curl_setopt($curlClient, CURLOPT_URL, 'http://api-url.com/GetStock'); // the URL of the API
        curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlClient, CURLOPT_POST, 1);  // the POST method
        curl_setopt($curlClient, CURLOPT_POSTFIELDS, 'LanguageCode=EN&apiKey=xxx-yyy-zzz&clientID=12345678'); // additional parameters / fields
        curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
        $fileContents = curl_exec($curlClient); // this variable contains the data format from the API, for example A JSON, XML or CSV format. 
        //The fields from the response format must be mapped in the import profile at "Catalog > Stock Import > Import Profiles", in an import profile in the "File Mapping" tab
        curl_close($curlClient);
 
        $filesToProcess[] = array('source_id' => $this->getSource()->getId(), 'path' => '', 'filename' => 'http_download', 'data' => $fileContents); // Set a filename here. 'data' must contain
        // the returned string from the HTTP source which will then be imported
 
        // Return files to process
        return $filesToProcess;
    }

Fetch stock levels from a SOAP-API

Product Export

The Product Feed Export Module can be used to send products to webservices/APIs. Send your products to APIs - fully automatically.

Sending products via HTTP Post

XSL Template

The XSL Template can be configured in the "Output Format" tab in your export profile at "Catalog > Product Export > Export Profiles". A sample XSL template in the XML output format can be downloaded here: XML XSL Template The output format would define the format which gets sent to the API, please see below for further instructions about how to configure the API calls.

PHP / Destination Code

Your API function needs to be configured in the Http.php file placed in the "app/code/local/Xtento/ProductExport/Model/Destination/" folder in your Magento root directory. You can rename the "Http.php.sample" file to "Http.php" first.

    public function yourFunctionName($fileArray)
    {
        // Do whatever - sample code for a HTTP request below.
        foreach ($fileArray as $filename => $fileContent) {
            $curlClient = curl_init();
            curl_setopt($curlClient, CURLOPT_URL, 'https://api-url.com/CreateProduct'); //this is the API URL where the request will be sent
            curl_setopt($curlClient, CURLOPT_RETURNTRANSFER, 1); //returns the transfer as a string of the return value of curl_exec() instead of outputting it directly
            curl_setopt($curlClient, CURLOPT_POST, 1); // the POST method
            curl_setopt($curlClient, CURLOPT_POSTFIELDS, $fileContent); // the variable $fileContent matches the data format defined in the export profile in the "Output Format" tab
	    curl_setopt($curlClient, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // an example for a JSON format, XML would be 'Content-Type: application/xml'
	    curl_setopt($curlClient, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // basic HTTP authentication, other possible parameters are CURLAUTH_DIGEST, CURLAUTH_BEARER and others
	    curl_setopt($curlClient, CURLOPT_USERPWD, 'username:password'); // the authentication credentials
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curlClient, CURLOPT_SSL_VERIFYHOST, 0);
            $result = curl_exec($curlClient);
            curl_close($curlClient);
        }
    }
Personal tools
Namespaces
Variants
Actions
General Information
Magento 2 Guides
Magento 2 Extensions
Magento 1 Guides
Magento 1 Extensions
Magento Integration Suite
Product Feed Guides
Toolbox