selimppc

RTT - TNT Express

Jun 16th, 2016
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.67 KB | None | 0 0
  1. /***  Config File  **/
  2. [credentials]
  3. account     = 'CIT00000000000079384'
  4. ;Username is not the same as your log in to TNT Online
  5. username    =   '[email protected]'
  6. password    =   "Jafking1981"
  7.  
  8.  
  9. [collectionAddress]
  10. suburb      = "Melbourne"
  11. post_code   = 3000
  12. state       = vic
  13.  
  14. [tnt_urls]
  15. ;TNT may change this URL - so this is set here for ease of update
  16. request_url         = "https://www.tntexpress.com.au/Rtt/inputRequest.asp"
  17. xmlnsurl            = "http://www.tntexpress.com.au"
  18.  
  19.  
  20.  
  21.  
  22.  /** ====================== TNT Enquiry Class   ========================== **/
  23. <?php
  24. /**
  25.  * TNT Rate and Transit Time Class
  26.  *
  27.  * TNT provide an API to retrieve Rate and Transit Times
  28.  * for a given account, collection address, delivery address and
  29.  * item type, weight and dimensions.
  30.  *
  31.  * This class constructs the required XML and handles sending and
  32.  * receiving messages, as well as some error handling and validation
  33.  *
  34.  * @author Patrick O'Sullivan>
  35.  * @copyright 2015 Smarter Better Business
  36.  */
  37.  
  38.  
  39. class TntEnquiry
  40. {
  41.  
  42.     /** As this is account specific, the TntConfig.ini must be
  43.      *  updated with credentials and default collection address
  44.      *  This can be placed outside the webroot and given 0600 permissions
  45.      *  for security.  Use a relative path e.g. '../'
  46.      */
  47.    
  48.     public $configLocation = 'TntConfig.ini';
  49.    
  50.     public $config;
  51.    
  52.     public $xmlnsurl;
  53.    
  54.  
  55.     public $senderAccount;
  56.     public $username;
  57.     public $password;
  58.    
  59.     /* Get request URL and namespace */
  60.     public $requestURL;
  61.    
  62.     public function __construct(){
  63.        
  64.         /* Set some defaults at run time */
  65.         if (!$config = parse_ini_file($this->configLocation, TRUE)) throw new exception('Unable to open ' . $configLocation . '.');
  66.        
  67.         $this->xmlnsurl = $config['tnt_urls']['xmlnsurl'];
  68.        
  69.         $this->requestURL = $config['tnt_urls']['request_url'];
  70.        
  71.         $this->collectAddress  = array(
  72.             'suburb'    =>$config['collectionAddress']['suburb'],
  73.             'postCode'  =>$config['collectionAddress']['post_code'],
  74.             'state'     =>$config['collectionAddress']['state']
  75.         );
  76.            
  77.                
  78.         $this->shipDate       = date("Y-m-d"); //Default to today
  79.        
  80.          /* Get credentials */
  81.         $this->senderAccount  = $config['credentials']['account'];
  82.         $this->username       = $config['credentials']['username'];
  83.         $this->password       = $config['credentials']['password'];
  84.        
  85.         /* Get request URL */
  86.         $this->requestURL     = $config['tnt_urls']['request_url'];
  87.  
  88.     }
  89.  
  90.     public $shipDate;
  91.      
  92.     /* Set some other defaults that aren't defined at runtime*/
  93.     public $deliveryAddress = array(
  94.     );
  95.  
  96.     public $dangerous      = "false";
  97.    
  98.     public $packageType    = "N"; //N=NonDocs D=Docs
  99.    
  100.     public $payer          = "S"; //S=Sender R=Receiver
  101.    
  102.    
  103.    
  104.     /* Create some setters and getters for the properties */
  105.    
  106.     public function setCollectAddress($collectAddress){
  107.         /* Expects an array */
  108.        
  109.         if(!$this->$collectAddress['suburb']=$collectAddress['suburb']) throw new exception('Collect address does not include suburb.');
  110.         if(!$this->$collectAddress['postCode']=$collectAddress['postCode']) throw new exception('Collect address does not include postcode.');
  111.         if(!$this->$collectAddress['state']=$collectAddress['state']) throw new exception('State address does not include postcode.');
  112.  
  113.     }
  114.     public function getCollectAddress(){
  115.        
  116.         return $this->collectAddress;
  117.     }  
  118.     public function setDeliveryAddress($deliveryAddress){
  119.         /* Expects an array */
  120.  
  121.         $this->deliveryAddress['suburb']   =$deliveryAddress['suburb'];
  122.         $this->deliveryAddress['postCode'] =$deliveryAddress['postCode'];
  123.         $this->deliveryAddress['state']    =$deliveryAddress['state'];
  124.         return $this->deliveryAddress;
  125.     }
  126.     public function getDeliveryAddress(){
  127.        
  128.         return $this->deliveryAddress;
  129.     }
  130.     public function setDangerous($dangerous){
  131.        
  132.         return  $this->dangerous = $dangerous;
  133.     }
  134.     public function getDangerous(){
  135.         return $this->dangerous;
  136.     }
  137.     public function setPackageType($packageType){  
  138.         return $this->packageType = $packageType;
  139.     }
  140.     public function getPackageType(){
  141.         return $this->packageType;
  142.     }
  143.     public function setShipDate($shipDate){
  144.          //Must be in format 'date("Y-m-d")
  145.          return $this->shipDate = $shipDate;
  146.     }
  147.     public function setPayer($payer){
  148.         /*Only use S or R */
  149.         return($this->payer=$payer);
  150.     }
  151.     public function getShipDate(){
  152.         return $this->shipDate;
  153.     }
  154.    
  155.     public function createBaseXML(){
  156.        
  157.         /* create a dom document with encoding utf8 */
  158.         $dom = new DOMDocument('1.0');
  159.         $dom->formatOutput = true;
  160.  
  161.         /* create the root element of the xml tree */
  162.         $xmlRoot = $dom->createElement('enquiry');
  163.        
  164.         /* add attribute */
  165.         $xmlRootAttribute = $dom->createAttribute('xmlns');
  166.        
  167.         /* Value for the attribute */
  168.         $xmlRootAttribute->value=$this->xmlnsurl;
  169.        
  170.        
  171.         /* add the attribute to the document */
  172.         $xmlRoot->appendChild($xmlRootAttribute);
  173.        
  174.         /* append it to the document created */
  175.         $xmlRoot = $dom->appendChild($xmlRoot);
  176.        
  177.         /* build the core XML */
  178.        
  179.    
  180.         $ratedTransitTimeEnquiry    = $this->addNode($dom,$xmlRoot,"ratedTransitTimeEnquiry");
  181.        
  182.         $cutOffTimeEnquiry          = $this->addNode($dom,$ratedTransitTimeEnquiry,"cutOffTimeEnquiry");
  183.  
  184.        
  185.         /* add the variable XML data */
  186.         $collectionAddress          = $this->addNode($dom,$cutOffTimeEnquiry,"collectionAddress");
  187.        
  188.         $this->addNodeElement($dom,$collectionAddress,"suburb",$this->collectAddress['suburb']);
  189.        
  190.         $this->addNodeElement($dom,$collectionAddress,"postCode",$this->collectAddress['postCode']);
  191.        
  192.         $this->addNodeElement($dom,$collectionAddress,"state",$this->collectAddress['state']);
  193.          
  194.         $deliveryAddress = $this->addNode($dom,$cutOffTimeEnquiry,"deliveryAddress");
  195.        
  196.         $this->addNodeElement($dom,$deliveryAddress,"suburb",$this->deliveryAddress['suburb']);
  197.        
  198.         $this->addNodeElement($dom,$deliveryAddress,"postCode",$this->deliveryAddress['postCode']);
  199.        
  200.         $this->addNodeElement($dom,$deliveryAddress,"state",$this->deliveryAddress['state']);
  201.        
  202.         $this->addNodeElement($dom,$cutOffTimeEnquiry,"shippingDate",$this->shipDate);
  203.        
  204.         /* this sets the date a little early. If the send request is sent later, it might be worth having a setter */
  205.         $this->addNodeElement($dom,$cutOffTimeEnquiry,"userCurrentLocalDateTime",date(DATE_ATOM));
  206.        
  207.         $dangerous = $this->addNode($dom,$cutOffTimeEnquiry,"dangerousGoods");
  208.        
  209.         $this->addNodeElement($dom,$dangerous,"dangerous",$this->dangerous);
  210.        /* add a placeholder for items to ship */
  211.         $packageLines               = $this->addNodeWithAttribute($dom,$cutOffTimeEnquiry,"packageLines","packageType","N");
  212.  
  213.        
  214.         $termsOfPayment = $this->addNode($dom,$ratedTransitTimeEnquiry,"termsOfPayment");
  215.        
  216.         $this->addNodeElement($dom,$termsOfPayment,"senderAccount",$this->senderAccount);
  217.         /* we only care about shipping on our account. Other people might want to get a price for
  218.          * receiver pays.  This can be added to the TntConfig.ini file */
  219.         $this->addNodeElement($dom,$termsOfPayment,"payer","S");
  220.        
  221.         return $dom;
  222.     }
  223.    
  224.     private function addNode(&$dom,&$parent,$node){
  225.         $newNode = $dom->createElement($node);
  226.         $newNode = $parent->appendChild($newNode);
  227.         return $newNode;
  228.     }
  229.    
  230.     private function addNodeElement(&$dom,$node,$element,$value){
  231.         $element=$dom->createElement($element,$value);
  232.         return $node->appendChild($element);
  233.     }
  234.    
  235.     private function addNodeWithAttribute(&$dom,&$parent,$node,$attribute,$value){
  236.        
  237.         $node = $dom->createElement($node);
  238.        
  239.         $nodeAttribute = $dom->createAttribute($attribute);
  240.        
  241.         $nodeAttribute->value = $value;
  242.        
  243.         $node->appendChild($nodeAttribute);
  244.        
  245.         return $parent->appendChild($node);
  246.        
  247.     }  
  248.  
  249.     public function addItem($dom,$numberOfPackages=1,$packWeight=1,$lenght=1,$width=1,$height=1,$dimensionUnit="cm",$weightUnit="kg"){
  250.         /*This function does not access the dom by ref.  This allows for the base XML to be reused in loops */
  251.      
  252.         /* set package lines */
  253.         $packageLines = $dom->getElementsByTagName('packageLines')->item(0);
  254.  
  255.         /* add packageLine */
  256.         $packageLine = $this->addNode($dom,$packageLines,"packageLine");
  257.        
  258.                
  259.         /* add number of packages */
  260.         //$packageLine = $this->addNodeElement($dom,$packageLine,"numberOfPackages",(int)ceil($numberOfPackages));
  261.       /* add number of packages */
  262.         $packageLine->appendChild($dom->createElement("numberOfPackages",ceil($numberOfPackages)));
  263.        
  264.    
  265.         /* add dimensions for packages */
  266.         $dimensions = $this->addNodeWithAttribute($dom,$packageLine,"dimensions","unit",$dimensionUnit);
  267.      
  268.         /* add dimensions */
  269.         $this->addNodeElement($dom,$dimensions,"length",ceil($lenght));
  270.         $this->addNodeElement($dom,$dimensions,"width",ceil($width));
  271.         $this->addNodeElement($dom,$dimensions,"height",ceil($height));
  272.        
  273.         /* create weight */
  274.         $weight = $this->addNodeWithAttribute($dom,$packageLine,"weight","unit",$weightUnit);
  275.        
  276.         /* add weight */
  277.         $weight = $this->addNodeElement($dom,$weight,"weight",$packWeight);
  278.        
  279.        
  280.         return $dom;
  281.     }  
  282.    
  283.     public function send($xml){
  284.          
  285.          $data = array ('xmlRequest' => $xml,  'username' => $this->username, 'password' => $this->password);
  286.          
  287.          $data = http_build_query($data);
  288.          $data = str_replace('&amp;','&',$data);
  289.          $data = str_replace('+','%20',$data) ;
  290.          $data = str_replace('%2F','/',$data) ;
  291.          echo '<!--'.$xml.'-->';
  292.          $TNTURL = $this->requestURL;
  293.          $ch = curl_init($TNTURL);
  294.          curl_setopt($ch, CURLOPT_POST, 1);
  295.          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  296.          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  297.          curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  298.          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  299.          curl_setopt($ch, CURLOPT_VERBOSE, true);
  300.          $output = curl_exec($ch);
  301.          
  302.          return $output;
  303.          curl_close($ch);  
  304.        
  305.     }
  306.  
  307. }
  308.  
  309.  
  310. /**  ============  Call the Function  ================ **/
  311.  
  312. <?php
  313.  
  314. include 'TntEnquiry.php';
  315.  
  316. $enquiry = new TntEnquiry();
  317.  
  318.  
  319. var_dump($enquiry->setShipDate("2015-08-19"));
  320.  
  321.  
  322. $deliveryAddress = array(
  323.     'suburb'=>'Brighton',
  324.     'postCode'=>'3186',
  325.     'state'=>'vic'
  326. );
  327. $enquiry->setDeliveryAddress($deliveryAddress);
  328.  
  329.  
  330. $dom = $enquiry->createBaseXML();
  331.  
  332. $dom = $enquiry->addItem($dom,2,5,22,33,10);
  333.  
  334. $dom = $dom->saveXML();
  335. $output = $enquiry->send($dom);
  336.  
  337. var_dump($output);
  338. ?>
  339.  
  340.  
  341.  
  342.  
  343.  
  344. /** ========= OUT PUT =========== ***/
  345.  
  346. string '2015-08-19' (length=10)
  347. string '<?xml version="1.0"?>
  348. <response>
  349.   <error>
  350.     <code>004</code>
  351.     <description>Username and password combination is incorrect.</description>
  352.   </error>
  353. </response>' (length=171)
Add Comment
Please, Sign In to add comment