PHP code example of mijora / itella-api

1. Go to this page and download the library: Download mijora/itella-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/ */

    

mijora / itella-api example snippets




try {
  // ...
} catch (ItellaException $e) {
  // ...
}

use Mijora\Itella\Shipment\Party;
use Mijora\Itella\ItellaException;

try {
  $sender = new Party(Party::ROLE_SENDER);
  $sender
    ->setContract('000000')               // API contract number given by Itella
    ->setName1('TEST Web Shop')           // sender name
    ->setStreet1('Test str. 150')         // sender address
    ->setPostCode('47174')                // sender post code
    ->setCity('Kaunas')                   // sender city
    ->setCountryCode('LT')                // sender country code in ISO 3166-1 alpha-2 format (two letter code)
    ->setContactMobile('+37060000000')    // sender phone number in international format
    ->setContactEmail('[email protected]');  // sender email
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\Party;
use Mijora\Itella\ItellaException;

try {
  $receiver = new Party(Party::ROLE_RECEIVER);
  $receiver
    ->setName1('Testas')                    // receiver name
    ->setStreet1('None str. 4')             // receiver address
    ->setPostCode('47174')                  // receiver post code
    ->setCity('Kaunas')                     // receiver city
    ->setCountryCode('LT')                  // receiver country code in ISO 3166-1 alpha-2 format (two letter code)
    ->setContactMobile('+37060000000')      // receiver phone number in international format
    ->setContactEmail('[email protected]');  // receiver email
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\Party;
use Mijora\Itella\ItellaException;

try {
  $receiver = new Party(Party::ROLE_RECEIVER);
  $receiver
    ->setName1('Testas')
    ->setStreet1('None str. 4')
    ->setPostCode('47174')
    ->setCity('Kaunas')
    ->disablePhoneCheck()                   // disable phone checking / fixing
    ->setCountryCode('LT')                  // country is set to Lithuania
    ->setContactMobile('+37120000000')      // but phone number is Latvian
    ->setContactEmail('[email protected]');
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\GoodsItem;
use Mijora\Itella\ItellaException;

try {
  $item = new GoodsItem();
  $item
    ->setGrossWeight(0.5)       // kg, optional
    ->setVolume(0.5)            // m3, optional
    ->setContentDesc('Stuff');  // optional package content description
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\AdditionalService;
use Mijora\Itella\ItellaException;

try {
  $service_fragile = new AdditionalService(AdditionalService::FRAGILE);
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\AdditionalService;
use Mijora\Itella\Helper;
use Mijora\Itella\ItellaException;

try {
  $service_cod = new AdditionalService(
    AdditionalService::COD,
    array(
      'amount'    => 100,
      'codbic'    => 'XBC0101',
      'account'   => 'LT100000000000',
      'reference' => Helper::generateCODReference('666')
    )
  );
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\Shipment;
use Mijora\Itella\ItellaException;

try {
  $shipment = new Shipment($p_user, $p_secret);
  $shipment
    ->setProductCode(Shipment::PRODUCT_COURIER) // product code, should always be set first
    ->setShipmentNumber('Test_ORDER')           // shipment number, Order ID is good here
    ->setSenderParty($sender)                   // Register Sender
    ->setReceiverParty($receiver)               // Register Receiver
    ->addAdditionalServices(                    // Register additional services
      array($service_fragile, $service_cod)
    )
    ->addGoodsItems(                            // Register GoodsItem
      array($item)
    )
    ->setComment('Comment about shipment')      // Comment string
  ;
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\Shipment;
use Mijora\Itella\ItellaException;

$user = 'API_USER';     // API user
$secret = 'API_SECRET'; // API secret / password

try {
  $shipment = new Shipment($user, $secret);
  $shipment
    ->setProductCode(Shipment::PRODUCT_PICKUP)  // product code, should always be set first
    ->setShipmentNumber('Test_ORDER')           // shipment number, Order ID is good here
    ->setSenderParty($sender)                   // Register Sender
    ->setReceiverParty($receiver)               // Register Receiver
    ->setPickupPoint('071503201')               // Register pickup point pupCode
    ->addAdditionalService($service_cod)        // Register additional services
    ->addGoodsItem($item)                       // Register GoodsItem (this adds just one)
    ->setComment('Comment about shipment')      // Comment string
  ;
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

try {
  $tracking_number = $shipment->registerShipment();
  echo "Shipment registered:\n <code>" . $tracking_number . "</code>\n";
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

try {
  $xml = $shipment->asXML();
  file_put_contents('request.xml', $xml);
} catch (ItellaException $e) {
  // Handle validation exceptions here
}

use Mijora\Itella\Shipment\Shipment;
use Mijora\Itella\ItellaException;

$user = 'API_USER';     // API user
$secret = 'API_SECRET'; // API secret / password

$track = 'JJFI12345600000000001';
// or if need multiple in one pdf
// $track = ['JJFI12345600000000001', 'JJFI12345600000000010'];

try {
  $shipment = new Shipment($user, $secret);
  $pdf_base64 = $shipment->downloadLabels($track, Shipment::LABEL_SIZE_A5);
  $pdf = base64_decode($pdf_base64);
  if ($pdf) { // check if its not empty
    if (is_array($track)) {
      $track = 'labels';
    }
    $path = $track . '.pdf';
    $is_saved = file_put_contents($path, $pdf);
    $filename = 'labels.pdf';
    if (!$is_saved) { // make sure it was saved
      throw new ItellaException("Failed to save label pdf to: " . $path);
    }

    // make sure there is nothing before headers
    if (ob_get_level()) ob_end_clean();
    header("Content-Type: application/pdf; name=\"{$filename}\"");
    header("Content-Transfer-Encoding: binary");
    // disable caching on client and proxies, if the download content vary
    header("Expires: 0");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    readfile($path);
  } else {
    throw new ItellaException("Downloaded label data is empty.");
  }
} catch (ItellaException $e) {
  echo "Exception: <br>\n" . $e->getMessage() . "<br>\n";
}

use Mijora\Itella\Locations\PickupPoints;

$pickup = new PickupPoints('https://locationservice.posti.com/api/2/location');
// it is advised to download locations for each country separately
// this will return filtered pickup points list as array
$itella_loc = $pickup->getLocationsByCountry('LT');
// now points can be stored into file or database for future use
$pickup->saveLocationsToJSONFile('itella_locations_lt.json', json_encode($itella_loc));

use Mijora\Itella\Pdf\Manifest;

$items = array(
  array(
    'track_num' => 'JJFItestnr00000000015',
    'weight' => 1,
    'delivery_address' => 'Test Tester, Example str. 6, 44320 City, LT',
  ),
);

// If need to translate default english
$translation = array(
  'sender_address' => 'Sender address:',
  'nr' => 'No.',
  'track_num' => 'Tracking number',
  'date' => 'Date',
  'amount' => 'Quantity',
  'weight' => 'Weight (kg)',
  'delivery_address' => 'Delivery address',
  'courier' => 'Courier',
  'sender' => 'Sender',
  'name_lastname_signature' => 'name, surname, signature',
);

$manifest = new Manifest();
$manifest
  ->setStrings($translation) // set translation
  ->setSenderName('TEST Web Shop') // sender name
  ->setSenderAddress('Shop str. 150') // sender address
  ->setSenderPostCode('47174') // sender postcode
  ->setSenderCity('Kaunas') // sender city
  ->setSenderCountry('LT') // sender country code
  ->addItem($items) // register item list
  ->setToString(true) // if 

use Mijora\Itella\CallCourier;
use Mijora\Itella\ItellaException;
use Mijora\Itella\Pdf\Manifest;

$manifest = new Manifest();
$manifest_string = $manifest
  /*
  See previous examples on how to create manifest, here only show last couple settings to get base64 string
  */
  ->setToString(true)
  ->setBase64(true)
  ->printManifest('manifest.pdf')
;

$sendTo = '[email protected]'; // email to send courier call to
try {
  $caller = new CallCourier($sendTo);
  $result = $caller
    ->setSenderEmail('[email protected]') // sender email
    ->setSubject('E-com order booking') // currently it must be 'E-com order booking'
    ->setPickUpAddress(array( // strings to show in email message
      'sender' => 'Name / Company name',
      'address' => 'Street, Postcode City, Country',
      'contact_phone' => '860000000',
    ))
    ->setAttachment($manifest_string, true) // attachment is previously generated manifest, true - means we are passing base64 encoded string
    ->callCourier() // send email
  ;
  if ($result) {
    echo 'Email sent to: <br>' . $sendTo;
  }
} catch (ItellaException $e) { // catch if something goes wrong
  echo 'Failed to send email, reason: ' . $e->getMessage();
}

use Mijora\Itella\CallCourier;
use Mijora\Itella\ItellaException;
use Mijora\Itella\Pdf\Manifest;

$manifest = new Manifest();
$manifest_string = $manifest
  /*
  See previous examples on how to create manifest, here only show last couple settings to get base64 string
  */
  ->setToString(true)
  ->setBase64(true)
  ->printManifest('manifest.pdf')
;

$items = array( // selected orders array
  array(
    'tracking_number' => 'JJFItestnr00000000015',
    'weight' => 1,
    'amount' => 1,
    'delivery_address' => 'Test Tester, Example str. 6, 44320 City, LT',
  ),
);

$translates = array( // translate text in email, recommend use english
  'mail_title' => 'Pickup information',
  'mail_sender' => 'Sender',
  'mail_address' => 'Address (pickup from)',
  'mail_phone' => 'Contact Phone',
  'mail_pickup_time' => 'Pickup time',
  'mail_attachment' => 'See attachment for manifest PDF.',
);

$sendTo = '[email protected]'; // email to send courier call to
try {
  $caller = new CallCourier($sendTo);
  $result = $caller
    ->setSenderEmail('[email protected]') // sender email
    ->setSubject('E-com order booking') // currently it must be 'E-com order booking'
    ->setPickUpAddress(array( // strings to show in email message
      'sender' => 'Name / Company name',
      'address_1' => 'Street str. 1',
      'postcode' => '12345',
      'city' => 'City name',
      'country' => 'LT', // Country code
      'pickup_time' => '8:00 - 17:00',
      'contact_phone' => '+37060000000',
    ))
    ->setAttachment($manifest_string, true) // attachment is previously generated manifest, true - means we are passing base64 encoded string
    ->setItems($items) // add orders
    ->setTranslates($translates) // add translated email text
    ->callCourier() // send email
  ;
  if ($result) {
    echo 'Email sent to: <br>' . $sendTo;
  }
} catch (ItellaException $e) { // catch if something goes wrong
  echo 'Failed to send email, reason: ' . $e->getMessage();
}