PHP code example of omobude / dhl-symfony-bundle

1. Go to this page and download the library: Download omobude/dhl-symfony-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

omobude / dhl-symfony-bundle example snippets




return [
    // ... other bundles
    Omobude\DhlBundle\OmobudeDhlBundle::class => ['all' => true],
];


declare(strict_types=1);

namespace App\Controller;

use Omobude\DhlBundle\Exception\DhlApiException;
use Omobude\DhlBundle\Exception\DhlAuthenticationException;
use Omobude\DhlBundle\Exception\DhlDownloadLabelException;
use Omobude\DhlBundle\Model\ConsigneeAddress;
use Omobude\DhlBundle\Model\PickupData;
use Omobude\DhlBundle\Model\SenderAddress;
use Omobude\DhlBundle\Model\ShipmentData;
use Omobude\DhlBundle\Model\ShipmentDetails;
use Omobude\DhlBundle\Service\DhlApiClient;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


class ShippingController extends AbstractController
{
    #[Route('/create-shipment', name: 'create_shipment')]
    public function createShipment(DhlApiClient $dhlClient): Response
    {
        try {
            $pickupData = new PickupData(
                date: new \DateTimeImmutable('now', new \DateTimeZone("Europe/London")),
                accountAddress: true
            );
    
            $senderAddress = new SenderAddress(
                companyName: 'XXXXXXXXXX LIMITED',
                address1: 'UNIT 5C, XXXXXXX DRIVE',
                city: 'SHEFFIELD',
                postalCode: 'XXXXX',
                country: 'GB',
                name: 'DISPATCH MANAGER',
                phone: '07443822832',
                email: '[email protected]',
                address2: 'XXXXXXXXXX HOUSE',
                address3: 'SHEFFIELD'
            );
    
            $consigneeAddress = new ConsigneeAddress(
                name: 'JOHN DOE',
                address1: '123 CUSTOMER STREET',
                city: 'LONDON',
                postalCode: 'XXXXXX',
                country: 'GB',
                phone: '07123456789',
                email: '[email protected]',
                recipientType: 'residential',
                addressType: 'doorstep',
                address2: 'APARTMENT 4B'
            );
    
            $shipmentDetails = new ShipmentDetails(
                customerRef1: 'TN-' . date('YmdHis'),
                customerRef2: substr(md5(uniqid()), 0, 8),
                orderedProduct: '1', // 1 = Next day, 48 = 48 hours
                totalPieces: 1,
                totalWeight: 5.5
            );
    
            $shipmentData = new ShipmentData(
                pickupAccount: 'XXXXXXX',
                dropoffType: 'PICKUP',
                consigneeAddress: $consigneeAddress,
                pickupData: $pickupData,
                senderAddress: $senderAddress,
                shipmentDetails: $shipmentDetails,
            );

            // Create shipment with PDF label
            $result = $dhlClient->createShipment($shipmentData);

            return $this->json([
                'success' => true,
                'shipment_id' => $result->getShipmentId(),
                'message' => 'Shipment created successfully',
            ]);
            
        } catch (DhlApiException|DhlAuthenticationException $ex) {
            return $this->json([
                'success' => false,
                'error' => $ex->getMessage(),
                'code' => $ex->getCode(),
            ], $ex->getCode());
        }
    }
}


declare(strict_types=1);

namespace App\Controller;

use Omobude\DhlBundle\Exception\DhlApiException;
use Omobude\DhlBundle\Exception\DhlAuthenticationException;
use Omobude\DhlBundle\Model\ClearanceDeclaration;
use Omobude\DhlBundle\Model\ClearanceItem;
use Omobude\DhlBundle\Model\ConsigneeAddress;
use Omobude\DhlBundle\Model\PickupData;
use Omobude\DhlBundle\Model\SenderAddress;
use Omobude\DhlBundle\Model\ShipmentData;
use Omobude\DhlBundle\Model\ShipmentDetails;
use Omobude\DhlBundle\Service\DhlApiClient;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;

class ShippingController extends AbstractController
{
    #[Route('/create-ni-shipment', name: 'create_ni_shipment')]
    public function createNorthernIrelandShipment(DhlApiClient $dhlClient): Response
    {
        try {
            $pickupData = new PickupData(
                date: new \DateTimeImmutable('now', new \DateTimeZone('Europe/London')),
                accountAddress: true
            );

            $senderAddress = new SenderAddress(
                companyName: 'XXXXXXXXXX LIMITED',
                address1: 'UNIT 5C, XXXXXXX DRIVE',
                city: 'SHEFFIELD',
                postalCode: 'S9 1XX',
                country: 'GB',
                name: 'DISPATCH MANAGER',
                phone: '07443822832',
                email: '[email protected]',
                address2: 'XXXXXXXXXX HOUSE',
                address3: 'SHEFFIELD'
            );

            // Northern Ireland consignee — postcode starts with "BT"
            $consigneeAddress = new ConsigneeAddress(
                name: 'JANE DOE',
                address1: '45 BELFAST ROAD',
                city: 'BELFAST',
                postalCode: 'BT1 5GS',
                country: 'GB',
                phone: '07123456789',
                email: '[email protected]',
                recipientType: 'residential',
                addressType: 'doorstep',
                address2: 'FLAT 2'
            );

            $shipmentDetails = new ShipmentDetails(
                customerRef1: 'NI-' . date('YmdHis'),
                customerRef2: substr(md5(uniqid()), 0, 8),
                orderedProduct: '1',
                totalPieces: 2,
                totalWeight: 3.2
            );

            // Build each line item being shipped
            $items = [
                new ClearanceItem(
                    descriptionOfGoods: 'Cotton T-Shirt',
                    unitQuantity: 1,
                    commodityCode: '6109100010'
                ),
                new ClearanceItem(
                    descriptionOfGoods: 'Wool Scarf',
                    unitQuantity: 1,
                    commodityCode: '6117100000'
                ),
            ];

            // Build the clearance declaration
            $clearanceDeclaration = new ClearanceDeclaration(
                shipmentMovementType: 'B2C',     // B2C or B2B
                totalValue: 49.99,                // Total goods value (excl. shipping)
                numberOfItems: 2,                 // Total number of items
                items: $items,
                sendersEORINumber: 'GB123456789000',     // Replace with your actual EORI
                sendersUKIMSNumber: 'XIUKIM12345678901234567890' // Replace with your actual UKIMS number
            );

            $shipmentData = new ShipmentData(
                pickupAccount: 'XXXXXXX',
                dropoffType: 'PICKUP',
                consigneeAddress: $consigneeAddress,
                pickupData: $pickupData,
                senderAddress: $senderAddress,
                shipmentDetails: $shipmentDetails,
                clearanceDeclaration: $clearanceDeclaration, // <-- 

/**
 * Download shipping label as a file (PDF).
 * Returns a BinaryFileResponse that automatically downloads the file.
 */
#[Route('/label/{shipmentId}', name: 'get_label')]
public function getLabel(string $shipmentId, DhlApiClient $dhlClient): Response
{
    try {
            return $dhlClient->getLabel($shipmentId);
            
        } catch (DhlAuthenticationException $ex) {
            return $this->json([
                'success' => false,
                'error' => 'Authentication failed',
                'message' => $ex->getMessage(),
            ], Response::HTTP_UNAUTHORIZED);
        } catch (DhlDownloadLabelException $ex) {
            return $this->json([
                'success' => false,
                'error' => 'Failed to process label',
                'message' => $ex->getMessage(),
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        } catch (DhlApiException $ex) {
            return $this->json([
                'success' => false,
                'error' => 'DHL API error',
                'message' => $ex->getMessage(),
            ], $ex->getCode() ?: Response::HTTP_BAD_REQUEST);
        }
}

/**
 * Inline display of label (opens in browser).
 */
#[Route('/label/{shipmentId}/view', name: 'view_label', methods: ['GET'])]
public function viewLabel(string $shipmentId, DhlApiClient $dhlClient): BinaryFileResponse|Response
{
    try {
        $response = $dhlClient->getLabel($shipmentId);

        // Change disposition to inline so it opens in browser
        $response->headers->set(
            'Content-Disposition',
            sprintf('inline; filename="label-%s.pdf"', $shipmentId)
        );

        return $response;
        
    } catch (DhlAuthenticationException | DhlDownloadLabelException | DhlApiException $e) {
        return $this->json([
            'success' => false,
            'error' => $e->getMessage(),
        ], $e->getCode() ?: Response::HTTP_BAD_REQUEST);
    }
}

if ($dhlClient->isSandbox()) {
    // Running in sandbox mode
    echo "Testing mode - no real shipments created";
} else {
    // Running in production mode
    echo "Production mode - real shipments will be created";
}

   Omobude\DhlBundle\OmobudeDhlBundle::class => ['all' => true],
bash
php bin/console debug:config omobude_dhl
php bin/console debug:container DhlApiClient