5.5.4 Print Shipments (PHP)
Print Shipment
Sample source code to print shipment.
<?php
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set("Asia/Chongqing");
$production_url = "https://apiv2.unixus.com.my/";
$sandbox_url = "https://sandbox-apiv2.unixus.com.my/";
$url = $sandbox_url;
$myRefreshToken = "88888888"; // Replace with your Refresh Token
function getAccessToken() {
global $url, $myRefreshToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . 'Token/Refresh');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept-Language: en'
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "RefreshToken" : "' . $myRefreshToken . '"}');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$res = curl_exec($ch);
curl_close($ch);
$obj = json_decode($res,true);
return $obj['AccessToken'];
}
function printShipment($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . 'shipment/v2/Print');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept-Language: en',
'Authorization: Bearer ' .
getAccessToken()
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
function pgwApiDate($myDate) {
// input "2019-01-01 00:00:00"
// output "2019-01-01T00:00:00+08:00"
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $myDate);
$requiredJsonFormat = $dateTime->format('Y-m-d\TH:i:sP');
return $requiredJsonFormat;
}
function pgwApiDateNow() {
// output "2019-01-01T00:00:00+08:00"
$dateTime = new DateTime();
$requiredJsonFormat = $dateTime->format('Y-m-d\TH:i:sP');
return $requiredJsonFormat;
}
function parseResponse($obj) {
if (isset($obj['Summary']['Success']) && $obj['Summary']['Success'] > 0) {
//Decode pdf content
$pdf_decoded = base64_decode($obj['LabelResponse']['LabelImageString']);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=Label.pdf');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($pdf_decoded));
// send to the browser
echo $pdf_decoded;
} else if (isset($obj['Summary']['Failed']) && $obj['Summary']['Failed'] > 0) {
foreach($obj['Errors'] as $errors) {
echo "Error: ";
echo $errors['ErrorMessage'] . "<br>";
}
}
}
$data = '
{
"HawbNo": [
"458040010619682"
]
}';
$response = printLabel($url, $data);
$obj = json_decode($response,true);
parseResponse($obj);
?>