PHP code example of xi0s / royal-mail-php-api

1. Go to this page and download the library: Download xi0s/royal-mail-php-api 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/ */

    

xi0s / royal-mail-php-api example snippets



 * Example OAuth token using League of PHP OAuth client
 */
$provider = new League\OAuth2\Client\Provider\GenericProvider([
  'clientId'                => constant('SHIPPING_API_ROYALMAIL_V4_CLIENT'),    // The client ID assigned to you by the provider
  'clientSecret'            => constant('SHIPPING_API_ROYALMAIL_V4_SECRET'),    // The client password assigned to you by the provider
  'urlAuthorize'            => 'https://authentication.proshipping.net/connect/authorize',
  'urlAccessToken'          => 'https://authentication.proshipping.net/connect/token',
  'urlResourceOwnerDetails' => 'https://authentication.proshipping.net/connect/resource',
]);
try {
  $accessToken = $provider->getAccessToken('client_credentials');
} catch (League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
  throw $e;
}

// Configure OAuth2 access token for authorization: oauth2
$config = RoyalMailV4\ShipmentsApi\Configuration::getDefaultConfiguration()->setAccessToken($accessToken);

$items = [];
$total = 0;
foreach ($packetItems as $row) {
  $total   += round($row['price']*$row['qty'], 2);
  $items[] = new RoyalMailV4\ShipmentsApi\Model\Item([
    'description' => $row['name'],
    'quantity' => $row['qty'],
    'value' => $row['price'],
    'skuCode' => $row['sku'],
  ]);
}

$address = new RoyalMailV4\ShipmentsApi\Model\ShipmentAddress([
  'companyName' => '',
  'contactName' => '',
  'line1' => '',
  'line2' => '',
  'town' => '',
  'county' => '',
  'countryCode' => '',
  'postcode' => '',
  'contactPhone' => '',
  'contactEmail' => '',
]);
$destination = new RoyalMailV4\ShipmentsApi\Model\Destination([
  'address' => $address,
]);

$shipper = new RoyalMailV4\ShipmentsApi\Model\Shipper([
  'shippingAccountId' => constant('SHIPPING_API_ROYALMAIL_V4_SHIPPING_ACCOUNT_ID'), // Your RM shipping ID
  'shippingLocationId' => '', // guid from the v4 shipping console
  'reference1' => '', // your personal reference for the packet
]);

$shipmentInformation = new RoyalMailV4\ShipmentsApi\Model\RoyalMailLabelFormatShipmentInformation([
  'shipmentDate' => new \DateTime('now', new \DateTimeZone('UTC')),
  'serviceCode' => '', // RM Service code
  'declaredWeight' => 1,
  'weightUnitOfMeasure' => RoyalMailV4\ShipmentsApi\Model\WeightUnitOfMeasure::KG,
  'descriptionOfGoods' => '',
  'declaredValue' => (float) $total,
  'currencyCode' => 'GBP',
  'labelFormat' => RoyalMailV4\ShipmentsApi\Model\RoyalMailLabelFormat::PDF, // Label type of PDF
  'action' => RoyalMailV4\ShipmentsApi\Model\CreateShipmentAction::PROCESS, // Automatically process the label
  'contentType' => RoyalMailV4\ShipmentsApi\Model\ContentType::NDX, // Non-documents, for example
]);

$enhancements = [];
$enhancements[] = new RoyalMailV4\ShipmentsApi\Model\RoyalMailServiceEnhancement([
  'code' => RoyalMailV4\ShipmentsApi\Model\RoyalMailEnhancementCode::SAFEPLACE,
  'safeplaceLocation' => '',
]);
/**
 * Ensure that the service code supports these enhancements
 */
$enhancements[] = new RoyalMailV4\ShipmentsApi\Model\RoyalMailServiceEnhancement([
  'code' => RoyalMailV4\ShipmentsApi\Model\RoyalMailEnhancementCode::EMAIL,
]);
$enhancements[] = new RoyalMailV4\ShipmentsApi\Model\RoyalMailServiceEnhancement([
  'code' => RoyalMailV4\ShipmentsApi\Model\RoyalMailEnhancementCode::SMS,
]);
$carrierSpecifics = new RoyalMailV4\ShipmentsApi\Model\RoyalMailShipmentRequestCarrierSpecifics([
  'serviceEnhancements' => $enhancements,
]);

$package = new RoyalMailV4\ShipmentsApi\Model\RoyalMailPackage([
  'packageType' => RoyalMailV4\ShipmentsApi\Model\RoyalMailPackageTypeCode::PARCEL,
  'declaredValue' => (float) $total,
  'declaredWeight' => 1,
]);

$shipment = new RoyalMailV4\ShipmentsApi\Model\RoyalMailShipmentRequestCarrierSpecificsRoyalMailPackageRoyalMailLabelFormatCreateShipmentRequest([
  'shipmentInformation' => $shipmentInformation,
  'shipper' => $shipper,
  'destination' => $destination,
  'items' => $items,
  'carrierSpecifics' => $carrierSpecifics,
  'packages' => [$package],
  // 'customs' => '',
  // 'returnToSender' => '',
]);

try {
  $api = new RoyalMailV4\ShipmentsApi\Api\ShipmentsApi(null, $config);
  $response = $api->v4ShipmentsRmPost($shipment);
} catch (RoyalMailV4\ShipmentsApi\ApiException $e) {
}

// Save the PDF label to disk:
$base64pdf = $response->getLabels();
$data = base64_decode($base64pdf);
$filename = "rmlabel.pdf";
file_put_contents(__DIR__ . "{$filename}.pdf", $data);

// get the shipment ID - used for updates or anything [is now a guid]
$response->getPackages()[0]->getShipmentId();

// tracking number or the numbe that's printed on the label
$response->getPackages()[0]->getTrackingNumber();

// Get the tracking URL
$response->getPackages()[0]->getCarrierTrackingUrl();