TNT ExpressConnect with PHP 5.3

I had a project recently where I had to integrate TNT’s popular ExpressConnect module. This is a well developed module that has been generating Consignments over an Web API for years. Brilliant for allowing e-commerce sites to:

  • Price
  • Book
  • Track
  • Ship
  • Manifest

All from your website. I’ve recently had to integrate it along with one of our LAMP Stack websites; normally APIs in the past I’ve worked with are a straight forward API cURL request; although this had to entail a little different way of working. I never 100% understood why, although I think it’s something to do with the headers generated from cURL module which were being rejected by TNT, instead resorted to stream_get_contents to collect the $_POST response.

    
    /**
     *  Submit XML to the TNT
     *  server via a Stream instead
     *  of cURL. 
     *
     *  @Returns String (XML)
    **/
    function sendToTNTServer( $Xml ) {

       $postdata = 
         http_build_query(
                       array(
                         //For Future reference
                         //the xml_in= ( the = ) is appended
                         //Automatically by PHP
                        'xml_in' => $Xml 
                       )
            );

       $opts = array(
                'http' => array(
                   'method'  => 'POST',
                   'header'  => 'Content-type: application/x-www-form-urlencoded',
                   'content' => $postdata
                 )
             );

        $context  = stream_context_create( $opts );
        $output = file_get_contents( 
              'https://express.tnt.com/expressconnect/pricing/getprice', 
              false, 
              $context 
          );

        return $output;
    }