Integrating the Labelary ZPL API with Magento 2 and FedEx API for generating and printing ZPL shipping labels involves several steps. Here’s a detailed guide:
Step 1: Set Up Your Magento 2 Module
- Create Module Directory Structure:
app/code/YourVendor/FedExLabel/
- Define the
module.xml:<!-- app/code/YourVendor/FedExLabel/etc/module.xml --> <config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="YourVendor_FedExLabel" setup_version="1.0.0"/> </config> - Register the Module:
// app/code/YourVendor/FedExLabel/registration.php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'YourVendor_FedExLabel', __DIR__ );
Step 2: Create Configurations for FedEx API
- Create System Configuration File:
<!-- app/code/YourVendor/FedExLabel/etc/adminhtml/system.xml -->
<config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/system_file.xsd">
<system>
<section id="fedex_label">
<group id="settings" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<field id="api_key" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>API Key</label>
<validate>required-entry</validate>
</field>
<field id="api_password" translate="label" type="password" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>API Password</label>
<validate>required-entry</validate>
</field>
<field id="account_number" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Account Number</label>
<validate>required-entry</validate>
</field>
<field id="meter_number" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Meter Number</label>
<validate>required-entry</validate>
</field>
</group>
</section>
</system>
</config>2. Create Configuration Scope File:
<!-- app/code/YourVendor/FedExLabel/etc/config.xml -->
<config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/config.xsd">
<default>
<fedex_label>
<settings>
<api_key></api_key>
<api_password></api_password>
<account_number></account_number>
<meter_number></meter_number>
</settings>
</fedex_label>
</default>
</config>Step 3: Create Model for FedEx Label Generation
- Create the Label Generator Class
// app/code/YourVendor/FedExLabel/Model/LabelGenerator.php
namespace YourVendor\FedExLabel\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Sales\Model\Order;
class LabelGenerator
{
protected $scopeConfig;
public function __construct(ScopeConfigInterface $scopeConfig)
{
$this->scopeConfig = $scopeConfig;
}
public function generateZplLabel(Order $order)
{
$apiKey = $this->scopeConfig->getValue('fedex_label/settings/api_key');
$apiPassword = $this->scopeConfig->getValue('fedex_label/settings/api_password');
$accountNumber = $this->scopeConfig->getValue('fedex_label/settings/account_number');
$meterNumber = $this->scopeConfig->getValue('fedex_label/settings/meter_number');
// FedEx API endpoint and request details
$url = 'https://apis-sandbox.fedex.com/ship/v1/shipments';
$jsonRequest = $this->buildJsonRequest($order, $apiKey, $apiPassword, $accountNumber, $meterNumber);
// cURL to send the request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonRequest);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer ' . $this->getFedExAuthToken()]);
$response = curl_exec($ch);
curl_close($ch);
// Handle the response to extract ZPL label
$labelZpl = $this->parseZplLabel($response);
return $labelZpl;
}
private function buildJsonRequest(Order $order, $apiKey, $apiPassword, $accountNumber, $meterNumber)
{
// Build JSON request for FedEx API
// Include necessary details like shipper, recipient, package details, etc.
// Refer to FedEx API documentation for specifics
$json = [
// JSON structure based on FedEx API requirements
];
return json_encode($json);
}
private function parseZplLabel($response)
{
// Parse the response to extract ZPL label
// Refer to FedEx API documentation for specifics on response format
$zplLabel = ''; // Extract ZPL label from the response
return $zplLabel;
}
private function getFedExAuthToken()
{
// Implement OAuth2.0 token retrieval logic as per FedEx API requirements
return 'your-oauth-token';
}
}Step 4: Generate PNG Label Using Labelary API
- Create a Method to Convert ZPL to PNG
// app/code/YourVendor/FedExLabel/Model/LabelGenerator.php namespace YourVendor\FedExLabel\Model; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Sales\Model\Order; class LabelGenerator { // Existing code... public function convertZplToPng($zplLabel) { $url = 'https://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $zplLabel); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/png']); $response = curl_exec($ch); curl_close($ch); if (!$response) { throw new \Exception('Failed to convert ZPL to PNG.'); } return $response; } }Step 5: Generate Label When Order is Shipped
1. Observer to Generate Label:
<!-- app/code/YourVendor/FedExLabel/etc/events.xml --> <config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="sales_order_shipment_save_after"> <observer name="generate_fedex_label" instance="YourVendor\FedExLabel\Observer\GenerateLabel" /> </event> </config>2. Observer Class:
// app/code/YourVendor/FedExLabel/Observer/GenerateLabel.php namespace YourVendor\FedExLabel\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use YourVendor\FedExLabel\Model\LabelGenerator; class GenerateLabel implements ObserverInterface { protected $labelGenerator; public function __construct(LabelGenerator $labelGenerator) { $this->labelGenerator = $labelGenerator; } public function execute(Observer $observer) { $shipment = $observer->getEvent()->getShipment(); $order = $shipment->getOrder(); $zplLabel = $this->labelGenerator->generateZplLabel($order); // Convert ZPL to PNG using Labelary API $pngLabel = $this->labelGenerator->convertZplToPng($zplLabel); // Save PNG label or handle printing // e.g., save to order comments, attach to shipment, etc. } }
