In Magento 2, sometimes we need to use APIs to get some information for online shipping methods. So, in this blog, we are going to learn that how can we create XML requests and send requests in XML format in API.
Here, we have created a Controller File MakeXmlRequest.php inside app/code/Vendor/CustomModule/Controller/Demo/ directory.
In this Controller, we are creating requests in XML format and sending the requests using CURL methods.
In API response, we are getting scheduled pickup information for a package.
<?php /** * Webkul Software. * * @category Webkul * @package Vendor_CustomModule * @author Webkul * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ namespace Vendor\CustomModule\Controller\Demo; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; class MakeXmlRequest extends Action { /** * @var \Magento\Shipping\Model\Simplexml\ElementFactory */ protected $xmlElFactory; /** * @var \Magento\Framework\Controller\Result\JsonFactory */ protected $resultJsonFactory; /** * initialization * * @param Context $context * @param \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory */ public function __construct( Context $context, \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory ) { $this->xmlElFactory = $xmlElFactory; $this->resultJsonFactory = $resultJsonFactory; parent::__construct($context); } public function execute() { $userId = "008COMPAN2890"; //usps userid; $gatewayUrl = "https://secure.shippingapis.com/ShippingAPI.dll";//usps gateway_secure_url'; //request information of customer, address and package $firstName = "John"; $lastName = "Doe"; $firmName = "ABC Corp."; $suiteOrApt = "2759 Momorial"; $address2 = "8 WILDWOOD DR"; $urbanization = ""; $city = "OLD LYME"; $state = "CT"; $zIP5 = "06371"; $zIP4 = "1844"; $phone = "5555551234"; $extension = "201"; $estimatedWeight = "14"; $packageLocation = "Front Door"; $specialInstructions = "Packages are behind the screen door."; $packVals = []; $eachPack = []; $eachPack["ServiceType"] = "PriorityMailExpress"; $eachPack["Count"] = "2"; $packVals[] = $eachPack; $eachPack = []; $eachPack["ServiceType"] = "PriorityMail"; $eachPack["Count"] = "1"; $packVals[] = $eachPack; //format data in XML format $xml = $this->xmlElFactory->create( ['data' => '<?xml version = "1.0" encoding = "UTF-8"?><CarrierPickupScheduleRequest/>'] ); $xml->addAttribute('USERID', $userId); $xml->addChild('FirstName', $firstName); $xml->addChild('LastName', $lastName); $xml->addChild('FirmName', $firmName); $xml->addChild('SuiteOrApt', $suiteOrApt); $xml->addChild('Address2', $address2); $xml->addChild('Urbanization', $urbanization); $xml->addChild('City', $city); $xml->addChild('State', $state); $xml->addChild('ZIP5', $zIP5); $xml->addChild('ZIP4', $zIP4); $xml->addChild('Phone', $phone); $xml->addChild('Extension', $extension); for ($i=0; $i<count($packVals); $i++) { $package = $xml->addChild('Package'); $package->addChild('ServiceType', $packVals[$i]["ServiceType"]); $package->addChild('Count', $packVals[$i]["Count"]); } $xml->addChild('EstimatedWeight', $estimatedWeight); $xml->addChild('PackageLocation', $packageLocation); $xml->addChild('SpecialInstructions', $specialInstructions); $request = $xml->asXML(); $result = $this->executeCurlRequest($request, $gatewayUrl, "CarrierPickupSchedule"); $data = ["result" => $result]; $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData($data); } public function executeCurlRequest($xml, $url, $api) { $arrayData = []; try { //Initiate cURL $ch = curl_init(); curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, "API=".$api."&XML=" . $xml); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300); $data = curl_exec($ch); curl_close($ch); //convert the XML result into array $arrayData = json_decode(json_encode(simplexml_load_string($data)), true); } catch (\Exception $e) { \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug($e->getMessage()); } return $arrayData; } }
When we will hit this controller in the browser’s window, we will get the response as the following image:

Hope this will be helpful. Thanks 🙂 You may also check our previous blog for Magento 2 custom shipping method development
Be the first to comment.