01-23-2020, 05:01 AM
Shipping API Integration in PHP with Australia Post Example
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/shipping-api-integration-in-php-with-australia-post-example.png" width="550" height="461" title="" alt="" /></div><div><p>Last modified on January 22nd, 2020 by Vincy.</p>
<p>In an eCommerce website, we use the shipping API to calculate shipping cost. We calculate based on the items added to the shopping cart.</p>
<p>Integrating Shipping API with an eCommerce website will optimize the logistics cost. It takes care of the shipping needs in an effective way.</p>
<p>Shipping API integration helps eCommerce website by charging the right amount for shipping. Imagine when we add a random fixed cost to each checkout. What will happen is that, we will either overcharge the customer or end up in direct loss.</p>
<p><a href="https://phppot.com/wp-content/uploads/2020/01/Australia-Post-Shipping-API-Integration-in-PHP.png"><img class="alignnone wp-image-11171 size-large" src="https://phppot.com/wp-content/uploads/2020/01/Australia-Post-Shipping-API-Integration-in-PHP-550x461.png" alt="Australia Post Shipping API Integration in PHP" width="550" height="461" srcset="https://phppot.com/wp-content/uploads/2020/01/Australia-Post-Shipping-API-Integration-in-PHP-550x461.png 550w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...in-PHP.png 940w" sizes="(max-width: 550px) 100vw, 550px"></a></p>
<p>In this article, we will see how to integrate Australia Post shipping API in a PHP application. You can use this <a href="https://phppot.com/php/simple-php-shopping-cart/">code in a shopping cart</a> checkout page to calculate shipping rates.</p>
<p>I have created code to request the Australia Post API to calculate the shipping rates. This rate is for the products on domestic shipping.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#what-is-shipping-api">What is Shipping API?</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#utilities-of-third-party-shipping-api">Utilities of third-party shipping API</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#existing-shipping-api-available">Existing shipping API available</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#about-australia-post-api">About Australia Post API</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#about-this-example">About this example</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#file-structure">File Structure</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#australia-post-shipping-api-integration-steps">Australia Post shipping API integration steps</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#payment-form-html-with-shipping-details">Web interface to get data to calculate shipping rates</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#php-code-with-australia-post-shipping-api-request-response-handlers">PHP code with Australia Post shipping API request-response handlers</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#australia-post-shipping-api-integration-output">Australia Post shipping API integration output</a></li>
</ol>
<h2 id="what-is-shipping-api">What is Shipping API?</h2>
<p>Shipping API – a digital intermediate as like as other APIs. It resolves eCommerce website shipping needs.</p>
<p>Integratable extern responds to the queries generated by the application.</p>
<p>With the available services and capabilities, it help build the eCommerce website’s shipping needs.</p>
<p>This ready-made solution will smoothen the customer’s buying experience with your online store.</p>
<h2 id="utilities-of-third-party-shipping-api">Capabilities of Shipping APIs</h2>
<p>For each eCommerce website, the motive to integrate Shipping API differs. This variation depends on the utilities required by the shopping cart. </p>
<p>In general, the capabilities of Shipping APIs are,</p>
<ol>
<li>Verifying shipping zone</li>
<li>Multi-carrier support</li>
<li>Tracking the order traces during shipment.</li>
</ol>
<p>With these capability limit, the Shipping APIs provides ultimate services. And, they are huge in number. For example,</p>
<ol>
<li>Ensuring the shipping destination and thereby calculate the success probability of the delivery.</li>
<li>Request a quote for the carrier or shipment.</li>
<li>Receiving notification about tracking updates.</li>
</ol>
<p>The Australia Post shipping API provides services like,</p>
<ul>
<li>Postage assessment calculation</li>
<li>Postal code search </li>
<li>SecurePay online payments and more.</li>
</ul>
<h2 id="existing-shipping-api-available">Existing shipping API available</h2>
<p>Postal carrier APIs like DHL, USPS, Australia Post provides services for the eCommerce website. It offers services like calculating shipping rates, tracking shipped parcel and more.</p>
<p>There are numerous third-party shipping APIs available. For example <a href="https://www.postmen.com/" target="_blank" rel="noopener noreferrer">Postmen</a>, <a href="https://www.easypost.com/" target="_blank" rel="noopener noreferrer">EasyPost</a>, Shippo and more.</p>
<p>The third-party shipping API has a RESTful interface that connects postal service APIs. It creates a channel to read the API to access its functionalities.</p>
<h2 id="about-australia-post-api">About Australia Post API</h2>
<p>Australia Post API suite has the following list APIs. All these APIs help to fulfil the transactional needs of your <a href="https://phppot.com/wordpress/ecommerce-website-set-up-using-wordpress-woocommerce/">eCommerce website</a>.</p>
<ol>
<li>Postage assessment calculator – To get the cost for shipping a document or parcel.</li>
<li>Shipping and tracking – To get service on product dispatch and tracking. </li>
<li>SecurePay online payments – Payment solutions for an eCommerce website via SecurePay integration.</li>
<li>Delivery choices API – gives the delivery choices to the user to choose location, speed, day, date, time.</li>
</ol>
<p>For accessing the API, it requires the corresponding API key. As per the Australia Post API access requirements it asks to register with the API to get the key.</p>
<p>Australia Post provides an interface to <a href="https://developers.auspost.com.au/apis/explorer" target="_blank" rel="noopener noreferrer">explore the APIs</a>. You may generate live API requests via this explorer to see how it works.</p>
<h2 id="about-this-example">About this example</h2>
<p>In this example, it uses the <em>Postage assessment calculator API or PAC </em>of the Australia Post API suite.</p>
<p>This API provides services to calculate the shipping cost. This cost varies based on the parcel weight, dimension, and more parameters.</p>
<p>This API includes various endpoints returning resources data based on the access requests.</p>
<p>I am creating a request for calculating the shipping cost for a domestic parcel. This request needs the corresponding API key. In the next section, we will see how to get the API key for accessing the <em>PAC API</em>.</p>
<p>For this calculation, the API requires the parcel dimension, height, width. And also, it needs the shipping zone’s origin and destination postal codes. These are all common considering any eCommerce website.</p>
<p>I get the parameters from the user via an HTML form and send it with the API request.</p>
<p>This example uses PHP CURL to access the Australia Post Postage assessment calculator API.</p>
<h2 id="file-structure">File Structure</h2>
<p>The below screenshot shows the Australia Post shipping rate calculation example files.</p>
<p><img class="alignnone size-full wp-image-11180" src="https://phppot.com/wp-content/uploads/2020/01/shipping-api-auspost-files-structure.gif" alt="Shipping API AusPost Files Structure" width="400" height="396"></p>
<h2 id="australia-post-shipping-api-integration-steps">Australia Post shipping API integration steps</h2>
<p>The steps to integrate Australia Post in an eCommerce website are,</p>
<ol>
<li>Choose API from the Australia Post API suite.</li>
<li>Create a new account to get the API key.</li>
<li>Choose the postage service and set the endpoint.</li>
<li>Set the API key as the HTTP header AUTH-KEY.</li>
<li>Generate the PAC API request with the header set in step 4.</li>
</ol>
<h3>How to get the Australia Post PAC API key</h3>
<p>There are many APIs provided by the Australia Post in API suite. The first step is to choose the API based on the need of your eCommerce website.</p>
<p>As discussed in the last section, I choose PAC API for calculating the shipping cost.</p>
<p>The PAC API access requirements state that it need the API key. This key is for authenticating the service request generated from the application.</p>
<p><img class="alignnone size-large wp-image-11167" src="https://phppot.com/wp-content/uploads/2020/01/aus-post-pac-api-registration-550x346.jpg" alt="Aus Post PAC API Registration" width="550" height="346" srcset="https://phppot.com/wp-content/uploads/2020/01/aus-post-pac-api-registration-550x346.jpg 550w, https://phppot.com/wp-content/uploads/20...00x189.jpg 300w, https://phppot.com/wp-content/uploads/20...ration.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>On submitting valid information, it will send the API key to the registered email address. You can use this API then, to access the PAC API services.</p>
<p><img class="alignnone size-large wp-image-11165" src="https://phppot.com/wp-content/uploads/2020/01/getting-api-key-from-auspost-550x449.jpg" alt="Getting API Key from Auspost" width="550" height="449" srcset="https://phppot.com/wp-content/uploads/2020/01/getting-api-key-from-auspost-550x449.jpg 550w, https://phppot.com/wp-content/uploads/20...00x245.jpg 300w, https://phppot.com/wp-content/uploads/20...68x627.jpg 768w, https://phppot.com/wp-content/uploads/20...uspost.jpg 1078w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2 id="payment-form-html-with-shipping-details">Web interface to enter details to calculate shipping rates</h2>
<p>This is the code to show a form to collect the product and shipping details. </p>
<p>It has the fields to collect the width, height, weight, and length of the parcel. The form will show the units of these parameters to the user.</p>
<p> Also, it collects the shipping address. This is the shipping destination address. The zip code is a mandatory field among the shipping address fields.</p>
<p>The shipping origin and destination postal codes are mandatory to calculate the rates.</p>
<p>In this example, the postal code of the shipping origin is configurable. You can also move it to the HTML form to let the user enter the data.</p>
<p class="code-heading">index.php</p>
<pre class="prettyprint lang-php"><HTML> <HEAD> <TITLE>Shipping API</TITLE> <link href="./assets/css/phppot-style.css" type="text/css" rel="stylesheet" /> <link href="./assets/css/shipping-api.css" type="text/css" rel="stylesheet" /> <script src="./vendor/jquery/jquery-3.3.1.js" type="text/javascript"></script> </HEAD> <BODY> <div class="phppot-container"> <div class="australian-api"> <div class="page-heading">Australian Shipping API</div> <form name="australian-api" id="australian-api" action="" method="post" onsubmit="return formValidation()"> <div class="sub-heading">Product Details</div> <div class="row"> <div class="inline-block"> <div class="form-label"> Length<span class="units-style">(cm)</span><span class="required error" id="length-info"></span> </div> <input class="input-box-110" type="text" name="length" id="length" value="<?php if(! empty($_POST["length"])){ echo $_POST["length"];}?>"> </div> <div class="inline-block input-right-margin"> <div class="form-label"> Width<span class="units-style">(cm)</span><span class="required error" id="width-info"></span> </div> <input class="input-box-110" type="text" name="width" id="width" value="<?php if(! empty($_POST["width"])){ echo $_POST["width"];}?>"> </div> <div class="inline-block"> <div class="form-label"> Height<span class="units-style">(cm)</span><span class="required error" id="height-info"></span> </div> <input class="input-box-110" type="text" name="height" id="height" value="<?php if(! empty($_POST["height"])){ echo $_POST["height"];}?>"> </div> <div class="inline-block input-right-margin"> <div class="form-label"> Weight<span class="units-style">(kg)</span><span class="required error" id="weight-info"></span> </div> <input class="input-box-110" type="text" name="weight" id="weight" value="<?php if(! empty($_POST["weight"])){ echo $_POST["weight"];}?>"> </div> </div> <div class="row"> <div class="inline-block"> <div class="form-label"> Quantity<span class="required error" id="quantity-info"></span> </div> <input class="input-box-110" type="number" name="quantity" id="quantity" value="<?php if(! empty($_POST["quantity"])){ echo $_POST["quantity"];}else{echo 1;}?>"> </div> </div> <div class="sub-heading">Shipping Address</div> <div class="row"> <div class="inline-block input-right-margin"> <div class="form-label">Address1</div> <input class="input-box-330" type="text" name="address1" id="address1" value="<?php if(! empty($_POST["address1"])){ echo $_POST["address1"];}?>"> </div> <div class="inline-block"> <div class="form-label">Address2</div> <input class="input-box-330" type="text" name="address2" id="address2" value="<?php if(! empty($_POST["address2"])){ echo $_POST["address2"];}?>"> </div> </div> <div class="row"> <div class="inline-block input-right-margin"> <div class="form-label">Country</div> <input class="input-box-330" type="text" name="country" id="country" value="<?php if(! empty($_POST["country"])){ echo $_POST["country"];}?>"> </div> <div class="inline-block"> <div class="form-label">State</div> <input class="input-box-330" type="text" name="state" id="state" value="<?php if(! empty($_POST["state"])){ echo $_POST["state"];}?>"> </div> </div> <div class="row"> <div class="inline-block input-right-margin"> <div class="form-label">City</div> <input class="input-box-330" type="text" name="city" id="city" value="<?php if(! empty($_POST["city"])){ echo $_POST["city"];}?>"> </div> <div class="inline-block"> <div class="form-label"> Zip Code<span class="required error" id="to-postcode-info"></span> </div> <input class="input-box-330" type="text" name="to-postcode" id="to-postcode" value="<?php if(! empty($_POST["to-postcode"])){ echo $_POST["to-postcode"];}?>"> </div> </div> <div class="row"> <div id="inline-block"> <input type="submit" class="submit-button" name="submit-btn" id="submit-btn" value="Get Quote"><span><img src="img/loader.gif" class="loader-ic" id="loader-icon"></span> </div> </div> </form> <?php if (! empty($shippingPrice)) { ?><div> <div class="sub-heading">Shipping Details</div> <div class="row"> <label class="shipping-result">Address1:</label> <?php echo $address1;?></div> <div class="row"> <label class="shipping-result">Address2:</label> <?php echo $address2;?></div> <div class="row"> <label class="shipping-result">Country:</label> <?php echo $country;?></div> <div class="row"> <label class="shipping-result">State:</label> <?php echo $state;?></div> <div class="row"> <label class="shipping-result">City:</label> <?php echo $city;?></div> <div class="row"> <label class="shipping-result">Quantity:</label> <?php echo $quantity;?></div> <div class="row"> <label class="shipping-result">Shipping price:</label> $<?php echo $quantity * $shippingPrice;?></div> </div> <?php }else if(!empty($errorMsg)){?> <div class="error-message"><?php echo $errorMsg;?></div> <?php }?> </div> </div> <script src="./assets/js/shipping.js"></script> </BODY> </HTML> </pre>
<h3>CSS created to present the payment form</h3>
<p>This CSS includes basic styles to show the shipping form to the user. It has exclusive styles related to this example.</p>
<p>Apart from that, this example contains a generic CSS <em>phppot-styles.css</em>. It contains common template styles with a list of selectors. You can find this generic CSS in the downloadable source.</p>
<p class="code-heading">assets/css/shipping-api.css</p>
<pre class="prettyprint lang-php">.australian-api { background: #fff; border-radius: 4px; padding: 10px; width: 85%; margin: 20px 40px; } .page-heading { font-size: 2em; font-weight: bold; } .sub-heading { font-size: 1.2em; font-weight: bold; margin: 20px 0px; } .inline-block { display: inline-block; } .row { margin: 15px 0px; } .form-label { margin-bottom: 5px; text-align: left; } input.input-box-330 { width: 250px; } input.input-box-110 { width: 120px; margin-right: 5px; } .australian-api .error { color: #ee0000; padding: 0px; background: none; border: #ee0000; } .australian-api .error-field { border: 1px solid #d96557; } .australian-api .error:before { content: '*'; padding: 0 3px; color: #D8000C; } input.submit-button { background-color: #ffb932; border-color: #ffc87a #e2a348 #da9d0a; text-align: center; cursor: pointer; color: #000; width: 100px; } .input-right-margin { margin-right: 30px; } .shipping-result { font-weight: bold; color: #737171; padding: 15px 0px; } .error-message { color: #D8000C; } .units-style { font-size: 0.8em; color: #666; margin-left: 2px; } .loader-ic { display: none; } </pre>
<h3>jQuery script to validate the shipping details</h3>
<p>The <em>shipping.js </em>file contains the form validation function. It validates the mandatory fields and makes sure that they are not empty.</p>
<p>It returns boolean based on which the form-post carried forward to PHP. While returning <em>false</em>, it highlights what’s wrong with the entered data.</p>
<p>After successful validation, PHP will validate the shipping attributes sent via the form.</p>
<p class="code-heading">assets/js/shipping.js</p>
<pre class="prettyprint lang-php">function formValidation() { var valid = true; $("#length").removeClass("error-field"); $("#width").removeClass("error-field"); $("#height").removeClass("error-field"); $("#weight").removeClass("error-field"); $("#quantity").removeClass("error-field"); $("#to-postcode").removeClass("error-field"); var Length = $("#length").val(); var Width = $("#width").val(); var Height = $("#height").val(); var Weight = $("#weight").val(); var Quantity = $("#quantity").val(); var toPostcode = $("#to-postcode").val(); if (Length.trim() == "") { $("#length-info").html("").css("color", "#ee0000").show(); $("#length").addClass("error-field"); valid = false; } if (Width.trim() == "") { $("#width-info").css("color", "#ee0000").show(); $("#width").addClass("error-field"); valid = false; } if (Height.trim() == "") { $("#height-info").css("color", "#ee0000").show(); $("#height").addClass("error-field"); valid = false; } if (Weight.trim() == "") { $("#weight-info").css("color", "#ee0000").show(); $("#weight").addClass("error-field"); valid = false; } if (Quantity.trim() == "" || Quantity < 1) { $("#quantity-info").css("color", "#ee0000").show(); $("#quantity").addClass("error-field"); valid = false; } if (toPostcode.trim() == "") { $("#to-postcode-info").css("color", "#ee0000").show(); $("#to-postcode").addClass("error-field"); valid = false; } if (valid == false) { $('.error-field').first().focus(); valid = false; } if (valid == true) { $("#submit-btn").hide(); $("#loader-icon").show(); } return valid; } </pre>
<h2 id="php-code-with-australia-post-shipping-api-request-response-handlers">PHP code with Australia Post shipping API request-response handlers</h2>
<p>This is the configuration file of this example code. It has the constants defined for keeping the API key and shipping origin.</p>
<p class="code-heading">Common/Config.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class Config { const AUSTRALIAN_POST_API_KEY = 'REPLACE_WITH_THE_API_KEY'; const SHIPPING_ORIGION = '1000'; } ?> </pre>
<p>This is an exclusive service class for executing curl script. The <em>execute() </em>function is receiving URL, API KEY as its parameters.</p>
<p>It initiates curl object and set the URL. It sets the header with the API key to call the Australia Post live URL.</p>
<p>The <em>rawBody</em> will receive the API response in JSON format. You can use this as a sample to build an eCommerce website backed by a shopping cart with shipping API integration.</p>
<p class="code-heading">lib/CurlService.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class CurlService { public function execute($url, $apiKey, $ch = null) { if (is_null($ch)) { $ch = curl_init(); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'AUTH-KEY: ' . $apiKey )); return $rawBody = curl_exec($ch); } } ?> </pre>
<p>The <em>AusPost.php </em>PHP class handles the operation for preparing the API request.</p>
<p>The <em>getShipmentPrice() </em>function set the API key and form data to the PHP variables. It prepares the query parameters with these variables.</p>
<p>The class constructor instantiates the curlService created for this example.</p>
<p>Using the curl instance, it hits the Australia Post live <em>PAC</em> API URL. The API will validate the shipping criteria passed with the query parameters.</p>
<p>The request and response can be of either JSON or XML.</p>
<p class="code-heading">lib/AusPost.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class AusPost { private $curlService; private $api_url = 'https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate?'; public function __construct() { require_once __DIR__ . '/CurlService.php'; $this->curlService = new CurlService(); } public function getShipmentPrice() { require_once __DIR__ . '/../Common/Config.php'; $con = new Config(); $apiKey = $con::AUSTRALIAN_POST_API_KEY; $fromPostcode = $con::SHIPPING_ORIGION; $toPostcode = $_POST["to-postcode"]; $length = $_POST["length"]; $width = $_POST["width"]; $height = $_POST["height"]; $weight = $_POST["weight"]; $queryParams = array( "from_postcode" => $fromPostcode, "to_postcode" => $toPostcode, "length" => $length, "width" => $width, "height" => $height, "weight" => $weight, "service_code" => "AUS_PARCEL_REGULAR" ); // here use $curlService and execute $url = $this->api_url . http_build_query($queryParams); $result = $this->curlService->execute($url, $apiKey); $shippingResult = json_decode($result); return $shippingResult; } } ?> </pre>
<p class="code-heading">index.php (PHP Code)</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; if (! empty($_POST["submit-btn"])) { require_once __DIR__ . '/lib/AusPost.php'; $shippingApi = new AusPost(); $result = $shippingApi->getShipmentPrice(); if (isset($result->postage_result)) { $shippingPrice = $result->postage_result->total_cost; } else { $errorMsg = $result->error->errorMessage; } $quantity = $_POST["quantity"]; $address1 = $_POST["address1"]; $address2 = $_POST["address2"]; $state = $_POST["state"]; $country = $_POST["country"]; $city = $_POST["city"]; } ?> </pre>
<h2 id="australia-post-shipping-api-integration-output">Australia Post shipping API integration output</h2>
<p>The output screenshot below shows the payment and shipping form. It is to get the shipping details from the user.</p>
<p>It also has the fields to collect parameters like height, width and the dimension of the products.</p>
<p>You can also integrate this form into your <a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/">shopping cart checkout page</a> to calculate rates. For a shopping cart, it requires only the shipping address.</p>
<p>Because, the height, width, height will be a part of a product entity. And the quantity can be read from the <a href="https://phppot.com/php/php-shopping-cart-without-database/">cart session or database</a>. The below form is generic and with little customization can be used for any eCommerce website.</p>
<p><img class="alignnone size-large wp-image-11175" src="https://phppot.com/wp-content/uploads/2020/01/shipping-api-australia-post-user-interface-550x463.jpg" alt="Shipping API Australia Post User Interface" width="550" height="463" srcset="https://phppot.com/wp-content/uploads/2020/01/shipping-api-australia-post-user-interface-550x463.jpg 550w, https://phppot.com/wp-content/uploads/20...00x253.jpg 300w, https://phppot.com/wp-content/uploads/20...erface.jpg 640w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p><a class="download" href="https://phppot.com/downloads/shipping-api-auspost.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2020/01/...t-example/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/shipping-api-integration-in-php-with-australia-post-example.png" width="550" height="461" title="" alt="" /></div><div><p>Last modified on January 22nd, 2020 by Vincy.</p>
<p>In an eCommerce website, we use the shipping API to calculate shipping cost. We calculate based on the items added to the shopping cart.</p>
<p>Integrating Shipping API with an eCommerce website will optimize the logistics cost. It takes care of the shipping needs in an effective way.</p>
<p>Shipping API integration helps eCommerce website by charging the right amount for shipping. Imagine when we add a random fixed cost to each checkout. What will happen is that, we will either overcharge the customer or end up in direct loss.</p>
<p><a href="https://phppot.com/wp-content/uploads/2020/01/Australia-Post-Shipping-API-Integration-in-PHP.png"><img class="alignnone wp-image-11171 size-large" src="https://phppot.com/wp-content/uploads/2020/01/Australia-Post-Shipping-API-Integration-in-PHP-550x461.png" alt="Australia Post Shipping API Integration in PHP" width="550" height="461" srcset="https://phppot.com/wp-content/uploads/2020/01/Australia-Post-Shipping-API-Integration-in-PHP-550x461.png 550w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...in-PHP.png 940w" sizes="(max-width: 550px) 100vw, 550px"></a></p>
<p>In this article, we will see how to integrate Australia Post shipping API in a PHP application. You can use this <a href="https://phppot.com/php/simple-php-shopping-cart/">code in a shopping cart</a> checkout page to calculate shipping rates.</p>
<p>I have created code to request the Australia Post API to calculate the shipping rates. This rate is for the products on domestic shipping.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#what-is-shipping-api">What is Shipping API?</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#utilities-of-third-party-shipping-api">Utilities of third-party shipping API</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#existing-shipping-api-available">Existing shipping API available</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#about-australia-post-api">About Australia Post API</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#about-this-example">About this example</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#file-structure">File Structure</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#australia-post-shipping-api-integration-steps">Australia Post shipping API integration steps</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#payment-form-html-with-shipping-details">Web interface to get data to calculate shipping rates</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#php-code-with-australia-post-shipping-api-request-response-handlers">PHP code with Australia Post shipping API request-response handlers</a></li>
<li><a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#australia-post-shipping-api-integration-output">Australia Post shipping API integration output</a></li>
</ol>
<h2 id="what-is-shipping-api">What is Shipping API?</h2>
<p>Shipping API – a digital intermediate as like as other APIs. It resolves eCommerce website shipping needs.</p>
<p>Integratable extern responds to the queries generated by the application.</p>
<p>With the available services and capabilities, it help build the eCommerce website’s shipping needs.</p>
<p>This ready-made solution will smoothen the customer’s buying experience with your online store.</p>
<h2 id="utilities-of-third-party-shipping-api">Capabilities of Shipping APIs</h2>
<p>For each eCommerce website, the motive to integrate Shipping API differs. This variation depends on the utilities required by the shopping cart. </p>
<p>In general, the capabilities of Shipping APIs are,</p>
<ol>
<li>Verifying shipping zone</li>
<li>Multi-carrier support</li>
<li>Tracking the order traces during shipment.</li>
</ol>
<p>With these capability limit, the Shipping APIs provides ultimate services. And, they are huge in number. For example,</p>
<ol>
<li>Ensuring the shipping destination and thereby calculate the success probability of the delivery.</li>
<li>Request a quote for the carrier or shipment.</li>
<li>Receiving notification about tracking updates.</li>
</ol>
<p>The Australia Post shipping API provides services like,</p>
<ul>
<li>Postage assessment calculation</li>
<li>Postal code search </li>
<li>SecurePay online payments and more.</li>
</ul>
<h2 id="existing-shipping-api-available">Existing shipping API available</h2>
<p>Postal carrier APIs like DHL, USPS, Australia Post provides services for the eCommerce website. It offers services like calculating shipping rates, tracking shipped parcel and more.</p>
<p>There are numerous third-party shipping APIs available. For example <a href="https://www.postmen.com/" target="_blank" rel="noopener noreferrer">Postmen</a>, <a href="https://www.easypost.com/" target="_blank" rel="noopener noreferrer">EasyPost</a>, Shippo and more.</p>
<p>The third-party shipping API has a RESTful interface that connects postal service APIs. It creates a channel to read the API to access its functionalities.</p>
<h2 id="about-australia-post-api">About Australia Post API</h2>
<p>Australia Post API suite has the following list APIs. All these APIs help to fulfil the transactional needs of your <a href="https://phppot.com/wordpress/ecommerce-website-set-up-using-wordpress-woocommerce/">eCommerce website</a>.</p>
<ol>
<li>Postage assessment calculator – To get the cost for shipping a document or parcel.</li>
<li>Shipping and tracking – To get service on product dispatch and tracking. </li>
<li>SecurePay online payments – Payment solutions for an eCommerce website via SecurePay integration.</li>
<li>Delivery choices API – gives the delivery choices to the user to choose location, speed, day, date, time.</li>
</ol>
<p>For accessing the API, it requires the corresponding API key. As per the Australia Post API access requirements it asks to register with the API to get the key.</p>
<p>Australia Post provides an interface to <a href="https://developers.auspost.com.au/apis/explorer" target="_blank" rel="noopener noreferrer">explore the APIs</a>. You may generate live API requests via this explorer to see how it works.</p>
<h2 id="about-this-example">About this example</h2>
<p>In this example, it uses the <em>Postage assessment calculator API or PAC </em>of the Australia Post API suite.</p>
<p>This API provides services to calculate the shipping cost. This cost varies based on the parcel weight, dimension, and more parameters.</p>
<p>This API includes various endpoints returning resources data based on the access requests.</p>
<p>I am creating a request for calculating the shipping cost for a domestic parcel. This request needs the corresponding API key. In the next section, we will see how to get the API key for accessing the <em>PAC API</em>.</p>
<p>For this calculation, the API requires the parcel dimension, height, width. And also, it needs the shipping zone’s origin and destination postal codes. These are all common considering any eCommerce website.</p>
<p>I get the parameters from the user via an HTML form and send it with the API request.</p>
<p>This example uses PHP CURL to access the Australia Post Postage assessment calculator API.</p>
<h2 id="file-structure">File Structure</h2>
<p>The below screenshot shows the Australia Post shipping rate calculation example files.</p>
<p><img class="alignnone size-full wp-image-11180" src="https://phppot.com/wp-content/uploads/2020/01/shipping-api-auspost-files-structure.gif" alt="Shipping API AusPost Files Structure" width="400" height="396"></p>
<h2 id="australia-post-shipping-api-integration-steps">Australia Post shipping API integration steps</h2>
<p>The steps to integrate Australia Post in an eCommerce website are,</p>
<ol>
<li>Choose API from the Australia Post API suite.</li>
<li>Create a new account to get the API key.</li>
<li>Choose the postage service and set the endpoint.</li>
<li>Set the API key as the HTTP header AUTH-KEY.</li>
<li>Generate the PAC API request with the header set in step 4.</li>
</ol>
<h3>How to get the Australia Post PAC API key</h3>
<p>There are many APIs provided by the Australia Post in API suite. The first step is to choose the API based on the need of your eCommerce website.</p>
<p>As discussed in the last section, I choose PAC API for calculating the shipping cost.</p>
<p>The PAC API access requirements state that it need the API key. This key is for authenticating the service request generated from the application.</p>
<p><img class="alignnone size-large wp-image-11167" src="https://phppot.com/wp-content/uploads/2020/01/aus-post-pac-api-registration-550x346.jpg" alt="Aus Post PAC API Registration" width="550" height="346" srcset="https://phppot.com/wp-content/uploads/2020/01/aus-post-pac-api-registration-550x346.jpg 550w, https://phppot.com/wp-content/uploads/20...00x189.jpg 300w, https://phppot.com/wp-content/uploads/20...ration.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>On submitting valid information, it will send the API key to the registered email address. You can use this API then, to access the PAC API services.</p>
<p><img class="alignnone size-large wp-image-11165" src="https://phppot.com/wp-content/uploads/2020/01/getting-api-key-from-auspost-550x449.jpg" alt="Getting API Key from Auspost" width="550" height="449" srcset="https://phppot.com/wp-content/uploads/2020/01/getting-api-key-from-auspost-550x449.jpg 550w, https://phppot.com/wp-content/uploads/20...00x245.jpg 300w, https://phppot.com/wp-content/uploads/20...68x627.jpg 768w, https://phppot.com/wp-content/uploads/20...uspost.jpg 1078w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2 id="payment-form-html-with-shipping-details">Web interface to enter details to calculate shipping rates</h2>
<p>This is the code to show a form to collect the product and shipping details. </p>
<p>It has the fields to collect the width, height, weight, and length of the parcel. The form will show the units of these parameters to the user.</p>
<p> Also, it collects the shipping address. This is the shipping destination address. The zip code is a mandatory field among the shipping address fields.</p>
<p>The shipping origin and destination postal codes are mandatory to calculate the rates.</p>
<p>In this example, the postal code of the shipping origin is configurable. You can also move it to the HTML form to let the user enter the data.</p>
<p class="code-heading">index.php</p>
<pre class="prettyprint lang-php"><HTML> <HEAD> <TITLE>Shipping API</TITLE> <link href="./assets/css/phppot-style.css" type="text/css" rel="stylesheet" /> <link href="./assets/css/shipping-api.css" type="text/css" rel="stylesheet" /> <script src="./vendor/jquery/jquery-3.3.1.js" type="text/javascript"></script> </HEAD> <BODY> <div class="phppot-container"> <div class="australian-api"> <div class="page-heading">Australian Shipping API</div> <form name="australian-api" id="australian-api" action="" method="post" onsubmit="return formValidation()"> <div class="sub-heading">Product Details</div> <div class="row"> <div class="inline-block"> <div class="form-label"> Length<span class="units-style">(cm)</span><span class="required error" id="length-info"></span> </div> <input class="input-box-110" type="text" name="length" id="length" value="<?php if(! empty($_POST["length"])){ echo $_POST["length"];}?>"> </div> <div class="inline-block input-right-margin"> <div class="form-label"> Width<span class="units-style">(cm)</span><span class="required error" id="width-info"></span> </div> <input class="input-box-110" type="text" name="width" id="width" value="<?php if(! empty($_POST["width"])){ echo $_POST["width"];}?>"> </div> <div class="inline-block"> <div class="form-label"> Height<span class="units-style">(cm)</span><span class="required error" id="height-info"></span> </div> <input class="input-box-110" type="text" name="height" id="height" value="<?php if(! empty($_POST["height"])){ echo $_POST["height"];}?>"> </div> <div class="inline-block input-right-margin"> <div class="form-label"> Weight<span class="units-style">(kg)</span><span class="required error" id="weight-info"></span> </div> <input class="input-box-110" type="text" name="weight" id="weight" value="<?php if(! empty($_POST["weight"])){ echo $_POST["weight"];}?>"> </div> </div> <div class="row"> <div class="inline-block"> <div class="form-label"> Quantity<span class="required error" id="quantity-info"></span> </div> <input class="input-box-110" type="number" name="quantity" id="quantity" value="<?php if(! empty($_POST["quantity"])){ echo $_POST["quantity"];}else{echo 1;}?>"> </div> </div> <div class="sub-heading">Shipping Address</div> <div class="row"> <div class="inline-block input-right-margin"> <div class="form-label">Address1</div> <input class="input-box-330" type="text" name="address1" id="address1" value="<?php if(! empty($_POST["address1"])){ echo $_POST["address1"];}?>"> </div> <div class="inline-block"> <div class="form-label">Address2</div> <input class="input-box-330" type="text" name="address2" id="address2" value="<?php if(! empty($_POST["address2"])){ echo $_POST["address2"];}?>"> </div> </div> <div class="row"> <div class="inline-block input-right-margin"> <div class="form-label">Country</div> <input class="input-box-330" type="text" name="country" id="country" value="<?php if(! empty($_POST["country"])){ echo $_POST["country"];}?>"> </div> <div class="inline-block"> <div class="form-label">State</div> <input class="input-box-330" type="text" name="state" id="state" value="<?php if(! empty($_POST["state"])){ echo $_POST["state"];}?>"> </div> </div> <div class="row"> <div class="inline-block input-right-margin"> <div class="form-label">City</div> <input class="input-box-330" type="text" name="city" id="city" value="<?php if(! empty($_POST["city"])){ echo $_POST["city"];}?>"> </div> <div class="inline-block"> <div class="form-label"> Zip Code<span class="required error" id="to-postcode-info"></span> </div> <input class="input-box-330" type="text" name="to-postcode" id="to-postcode" value="<?php if(! empty($_POST["to-postcode"])){ echo $_POST["to-postcode"];}?>"> </div> </div> <div class="row"> <div id="inline-block"> <input type="submit" class="submit-button" name="submit-btn" id="submit-btn" value="Get Quote"><span><img src="img/loader.gif" class="loader-ic" id="loader-icon"></span> </div> </div> </form> <?php if (! empty($shippingPrice)) { ?><div> <div class="sub-heading">Shipping Details</div> <div class="row"> <label class="shipping-result">Address1:</label> <?php echo $address1;?></div> <div class="row"> <label class="shipping-result">Address2:</label> <?php echo $address2;?></div> <div class="row"> <label class="shipping-result">Country:</label> <?php echo $country;?></div> <div class="row"> <label class="shipping-result">State:</label> <?php echo $state;?></div> <div class="row"> <label class="shipping-result">City:</label> <?php echo $city;?></div> <div class="row"> <label class="shipping-result">Quantity:</label> <?php echo $quantity;?></div> <div class="row"> <label class="shipping-result">Shipping price:</label> $<?php echo $quantity * $shippingPrice;?></div> </div> <?php }else if(!empty($errorMsg)){?> <div class="error-message"><?php echo $errorMsg;?></div> <?php }?> </div> </div> <script src="./assets/js/shipping.js"></script> </BODY> </HTML> </pre>
<h3>CSS created to present the payment form</h3>
<p>This CSS includes basic styles to show the shipping form to the user. It has exclusive styles related to this example.</p>
<p>Apart from that, this example contains a generic CSS <em>phppot-styles.css</em>. It contains common template styles with a list of selectors. You can find this generic CSS in the downloadable source.</p>
<p class="code-heading">assets/css/shipping-api.css</p>
<pre class="prettyprint lang-php">.australian-api { background: #fff; border-radius: 4px; padding: 10px; width: 85%; margin: 20px 40px; } .page-heading { font-size: 2em; font-weight: bold; } .sub-heading { font-size: 1.2em; font-weight: bold; margin: 20px 0px; } .inline-block { display: inline-block; } .row { margin: 15px 0px; } .form-label { margin-bottom: 5px; text-align: left; } input.input-box-330 { width: 250px; } input.input-box-110 { width: 120px; margin-right: 5px; } .australian-api .error { color: #ee0000; padding: 0px; background: none; border: #ee0000; } .australian-api .error-field { border: 1px solid #d96557; } .australian-api .error:before { content: '*'; padding: 0 3px; color: #D8000C; } input.submit-button { background-color: #ffb932; border-color: #ffc87a #e2a348 #da9d0a; text-align: center; cursor: pointer; color: #000; width: 100px; } .input-right-margin { margin-right: 30px; } .shipping-result { font-weight: bold; color: #737171; padding: 15px 0px; } .error-message { color: #D8000C; } .units-style { font-size: 0.8em; color: #666; margin-left: 2px; } .loader-ic { display: none; } </pre>
<h3>jQuery script to validate the shipping details</h3>
<p>The <em>shipping.js </em>file contains the form validation function. It validates the mandatory fields and makes sure that they are not empty.</p>
<p>It returns boolean based on which the form-post carried forward to PHP. While returning <em>false</em>, it highlights what’s wrong with the entered data.</p>
<p>After successful validation, PHP will validate the shipping attributes sent via the form.</p>
<p class="code-heading">assets/js/shipping.js</p>
<pre class="prettyprint lang-php">function formValidation() { var valid = true; $("#length").removeClass("error-field"); $("#width").removeClass("error-field"); $("#height").removeClass("error-field"); $("#weight").removeClass("error-field"); $("#quantity").removeClass("error-field"); $("#to-postcode").removeClass("error-field"); var Length = $("#length").val(); var Width = $("#width").val(); var Height = $("#height").val(); var Weight = $("#weight").val(); var Quantity = $("#quantity").val(); var toPostcode = $("#to-postcode").val(); if (Length.trim() == "") { $("#length-info").html("").css("color", "#ee0000").show(); $("#length").addClass("error-field"); valid = false; } if (Width.trim() == "") { $("#width-info").css("color", "#ee0000").show(); $("#width").addClass("error-field"); valid = false; } if (Height.trim() == "") { $("#height-info").css("color", "#ee0000").show(); $("#height").addClass("error-field"); valid = false; } if (Weight.trim() == "") { $("#weight-info").css("color", "#ee0000").show(); $("#weight").addClass("error-field"); valid = false; } if (Quantity.trim() == "" || Quantity < 1) { $("#quantity-info").css("color", "#ee0000").show(); $("#quantity").addClass("error-field"); valid = false; } if (toPostcode.trim() == "") { $("#to-postcode-info").css("color", "#ee0000").show(); $("#to-postcode").addClass("error-field"); valid = false; } if (valid == false) { $('.error-field').first().focus(); valid = false; } if (valid == true) { $("#submit-btn").hide(); $("#loader-icon").show(); } return valid; } </pre>
<h2 id="php-code-with-australia-post-shipping-api-request-response-handlers">PHP code with Australia Post shipping API request-response handlers</h2>
<p>This is the configuration file of this example code. It has the constants defined for keeping the API key and shipping origin.</p>
<p class="code-heading">Common/Config.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class Config { const AUSTRALIAN_POST_API_KEY = 'REPLACE_WITH_THE_API_KEY'; const SHIPPING_ORIGION = '1000'; } ?> </pre>
<p>This is an exclusive service class for executing curl script. The <em>execute() </em>function is receiving URL, API KEY as its parameters.</p>
<p>It initiates curl object and set the URL. It sets the header with the API key to call the Australia Post live URL.</p>
<p>The <em>rawBody</em> will receive the API response in JSON format. You can use this as a sample to build an eCommerce website backed by a shopping cart with shipping API integration.</p>
<p class="code-heading">lib/CurlService.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class CurlService { public function execute($url, $apiKey, $ch = null) { if (is_null($ch)) { $ch = curl_init(); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'AUTH-KEY: ' . $apiKey )); return $rawBody = curl_exec($ch); } } ?> </pre>
<p>The <em>AusPost.php </em>PHP class handles the operation for preparing the API request.</p>
<p>The <em>getShipmentPrice() </em>function set the API key and form data to the PHP variables. It prepares the query parameters with these variables.</p>
<p>The class constructor instantiates the curlService created for this example.</p>
<p>Using the curl instance, it hits the Australia Post live <em>PAC</em> API URL. The API will validate the shipping criteria passed with the query parameters.</p>
<p>The request and response can be of either JSON or XML.</p>
<p class="code-heading">lib/AusPost.php</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; class AusPost { private $curlService; private $api_url = 'https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate?'; public function __construct() { require_once __DIR__ . '/CurlService.php'; $this->curlService = new CurlService(); } public function getShipmentPrice() { require_once __DIR__ . '/../Common/Config.php'; $con = new Config(); $apiKey = $con::AUSTRALIAN_POST_API_KEY; $fromPostcode = $con::SHIPPING_ORIGION; $toPostcode = $_POST["to-postcode"]; $length = $_POST["length"]; $width = $_POST["width"]; $height = $_POST["height"]; $weight = $_POST["weight"]; $queryParams = array( "from_postcode" => $fromPostcode, "to_postcode" => $toPostcode, "length" => $length, "width" => $width, "height" => $height, "weight" => $weight, "service_code" => "AUS_PARCEL_REGULAR" ); // here use $curlService and execute $url = $this->api_url . http_build_query($queryParams); $result = $this->curlService->execute($url, $apiKey); $shippingResult = json_decode($result); return $shippingResult; } } ?> </pre>
<p class="code-heading">index.php (PHP Code)</p>
<pre class="prettyprint lang-php"><?php namespace Phppot; if (! empty($_POST["submit-btn"])) { require_once __DIR__ . '/lib/AusPost.php'; $shippingApi = new AusPost(); $result = $shippingApi->getShipmentPrice(); if (isset($result->postage_result)) { $shippingPrice = $result->postage_result->total_cost; } else { $errorMsg = $result->error->errorMessage; } $quantity = $_POST["quantity"]; $address1 = $_POST["address1"]; $address2 = $_POST["address2"]; $state = $_POST["state"]; $country = $_POST["country"]; $city = $_POST["city"]; } ?> </pre>
<h2 id="australia-post-shipping-api-integration-output">Australia Post shipping API integration output</h2>
<p>The output screenshot below shows the payment and shipping form. It is to get the shipping details from the user.</p>
<p>It also has the fields to collect parameters like height, width and the dimension of the products.</p>
<p>You can also integrate this form into your <a href="https://phppot.com/php/one-page-checkout-script-free-with-example-template-in-php/">shopping cart checkout page</a> to calculate rates. For a shopping cart, it requires only the shipping address.</p>
<p>Because, the height, width, height will be a part of a product entity. And the quantity can be read from the <a href="https://phppot.com/php/php-shopping-cart-without-database/">cart session or database</a>. The below form is generic and with little customization can be used for any eCommerce website.</p>
<p><img class="alignnone size-large wp-image-11175" src="https://phppot.com/wp-content/uploads/2020/01/shipping-api-australia-post-user-interface-550x463.jpg" alt="Shipping API Australia Post User Interface" width="550" height="463" srcset="https://phppot.com/wp-content/uploads/2020/01/shipping-api-australia-post-user-interface-550x463.jpg 550w, https://phppot.com/wp-content/uploads/20...00x253.jpg 300w, https://phppot.com/wp-content/uploads/20...erface.jpg 640w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p><a class="download" href="https://phppot.com/downloads/shipping-api-auspost.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/shipping-api-integration-in-php-with-australia-post-example/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2020/01/...t-example/