A PHP library, easypost_api.php has been made available to facilitate use of the EasyPost Web API services.  It is intended to be used by web site developers to provide Bing document delivery services (postal, sms, email & fax) from within their websites. The library can be downloaded from downloads and includes working examples of using the EasyPost Web API.

EasyPost Web API Overview

The EasyPost Web API establishes an authenticated session allowing upload of a document or set of documents and associated metadata. After completing the session the Bing backend systems will validate, process, print and lodge your mail.
Addressing information is provided to the API via a metadata file or alternatively, the auto processor can extract address and other metadata from within the documents.  Documentation describing the full EasyPost Web API is available here.

Prerequisites

To use the EasyPost Web API you will need:

  • A Bing customer account.
  • A Bing portal user account and password.
  • The easypost_api.php library requires PHP with PCRE support enabled. Min v5.5,  recommended v7.x.

File Formats

The metadata file can be presented to the EasyPost Web API in either JSON (Java Script Object Notation) or XML (eXtensible Markup Language) format. 
Each session may contain a metadata file along with document files to be uploaded and processed. The EasyPost Web API currently supports PDF, XPS and Postscript document files.

If no metadata is provided or the metadata provided does not include letter information, the uploaded files will be processed through the auto processor which extracts address and other metadata from within the documents.

The following example illustrates a metadata file in JSON format.  Example XML metadata files can be found in the EasyPost Web API documentation.

{
	"duplex": true,
	"colour_model": 1,
	"title": "Test Easypost API",
	"department": "Sales",
	"orientation": "portrait",
	"confirmation_email": true,
	"customer_email": "somebody@example.com",
	"customer_hold": true,
	"letters": [{
		"fax": "88888888"
	},
	{
		"email": "dave@somedomain.com.au"
	},
	{
		"postal": ["Mr A B Sample",
		"123 Sample Street",
		"SUBURB NSW 2999"]
	}]
}

This metadata file requests that the accompanying single uploaded document be sent to three recipients.  The first recipient would be sent the document via facsimile transmission to the phone number 88888888.  The second recipient, dave@somedomain.com.au, would be sent the document via electronic mail.  The third recipient, John Smith, would be sent the document via postal mail.  The document would be produced in colour, in portrait orientation, duplexed.  The mailing would be associated with the customer's Sales department.  The receipt of the upload by Bing would be acknowledged via email to somebody@example.com

The PHP library includes a helper function, make_json_file(), to assist you in creating well formed JSON metadata files.  See the Class ep_uploader Public Methods Reference section below.
A complete description of the metadata understood by the EasyPost Web API can be viewed here.

In a meta-data file, a pack refers to a set of letters.  Attributes defined at the pack scope of meta-data apply to all letters.

Configuration of easypost_api.php

The library uses several parameters to control access and authentication.
Required parameters:

  • AUTH_USER - a user name.
  • AUTH_PASS - a user password.
  • ACCOUNT - an account  that AUTH_USER has been authorised to use.   A user can be associated with multiple accounts.

Optional parameters:

  • VERIFY_CERTIFICATE - if true then in https mode the library checks the server certificate (default true).
  • PROXY - a proxy address <ip>:<port>

These parameters are presented to the library either as a  PHP file that defines a PHP class ep_api_conf  or an INI file using simple name=value entries.
The choice of which type of file is used is entirely up to your programming preference.

Configuration File Examples

PHP file - the configuration is represented by a php class ep_api_conf with constants, i.e.

<?php
class ep_api_conf {
    const AUTH_USER = "user";
    const AUTH_PASS="password";
    const ACCOUNT = 'account1';
    const VERIFY_CERTIFICATE = FALSE;
    const PROXY = '192.168.1.1:3128';
};
?>

INI file - the configuration is represented in a simple name=value form, i.e.

AUTH_USER = "user"
AUTH_PASS="password"
ACCOUNT = 'account'
VERIFY_CERTIFICATE=false
PROXY=192.168.1.1:3128

Using easypost_api.php

The following PHP code illustrates how to use the easypost_api.php library to upload a single document file with associated metadata file.  This script is included in the download of the easypost_api.php library.

#!/usr/bin/env -S php -q
 
<?php
 
require(__DIR__ . '/easypost_api.php');                // load the easypost_api.php library
 
$obj = new ep_uploader();                              // create instance of ep_uploader class
 
$obj->load_config_php(__DIR__ . '/ep_api_conf.php');   // load configuration file
 
$FILENAMES =  array('example.json', 'example.pdf');    // form array of files for upload
 
$reply = $obj->do_upload($FILENAMES);                  // process the upload
 
var_dump($reply);                                      // see the results
 
?>

A successful upload returns an array describing the files uploaded. If there is a failure or problem, the library will throw an Exception with a message describing the fault. See the Class ep_uploader Public Methods Reference section below for details.

Class ep_uploader Public Methods Reference

The easypost_api.php library provides a class ep_uploader which has the following public methods:
 
    load_config_ini( <ini file path> )

Loads configuration from an INI like config file. If you prefer to use a PHP file for your configuration see load_config_php() .

    load_config_php( <php file path> )

Loads configuration from the specified php file that declares a class ep_api_conf.  If you prefer to use an INI file see load_config_ini() .

    make_json_file( <input array> )

A helper function that creates a json metadata file from a metadata array.   An example of the use of this function would be:

$letters = array(
    "duplex" => true,
    "colour_model" => 1,
    "orientation" => 'portrait',
    'letters' => array(
        array(
            "postal" => array(
                "Mr A B Sample",
                "123 Sample Street",
                "SUBURB NSW 2999"
            )
        ),
        array(
            "postal" => array(
                "Mr C D Jones",
                "456 Sample Street",
                "SUBURB NSW 2999"
            )
        ),
        array(
            "fax" => "8888888"
        ),
        array(
            "email" => "dave@somedomain.com.au"
        )
    )
);
$jsonfname = $obj->make_json_file($letters);

This would result in a temporary file containing the following JSON content:

{
	"duplex": true,
	"colour_model": 1,
	"orientation": "portrait",
	"letters": [{
		"postal": ["Mr A B Sample",
		"123 Sample Street",
		"SUBURB NSW 2999"]
	},
	{
		"postal": ["Mr C D Sample",
		"456 Sample Street",
		"SUBURB NSW 2999"]
	},
	{
		"fax": "8888888"
	},
	{
		"email": "dave@somedomain.com.au"
	}]
}

Note that you are not required to use this helper function.  You are at liberty to create well-formed XML or JSON metadata files using whatever tools you prefer.

    do_upload( <file name array> [, <options array> ] )

This is the main method for establishing a session and uploading files to the EasyPost Web API.  The file name array parameter contains the set of files you want to upload. You may supply a single metadata file with zero or more document files in the file name array.  For the simplest case, your array would have a document file.

The options array allows you to override the libray's defaults.  The following is a list of possible keys in the option array:

  • 'http_hosts' - array of EasyPost Web API URIs to use for uploading
  • 'chunk_size' - size of a single uploaded block, default: 65535
  • 'auth_user' - user name, default comes from the config file
  • 'auth_pass' - password, default comes from the config file
  • 'account' - account, default comes from the config file

An example of an override using the options array might be where you are working behind an uncooperative firewall which disallows https. This would be done like so.

$opts = array( 'http_hosts' => array('http://easymail.com', 'http://alt.easymail.com'));

A successful upload will return an array with information about the files that have been uploaded.

array(
    "session_id" => "WK3448BYPK3C8V7P4JDD992C8DQ8", // pack id
    "files" => array ( // an array of uploaded files
        array (
            "sz" => 249, //uploaded file size
            "sha1" => "9b40fa44e83c37f505dc6e0f585b97eb5d44f11e", //hash value
            "name" => "example.json" //file name
        ),
        array (
            "sz" => 17575,
            "sha1" => "04148ab995db6eee94c027cefc37b7e84d76ad41",
            "name" => "example.pdf"
        )
    ),
    "result" => "OK"
)

The following errors are reported on failure cases by throwing an Exception with the following messages and codes:

  •   AUTH_USER or/and AUTH_PASS are wrong,  code 401.
  •   Wrong account ACCOUNT, code 403.
  •   File not found,  code 404.
  •   No connectable host found.
  •   Digest authentication response header expected.
  •   Operating system errors return the OS error message and error code e.g. I/O errors etc .
  •   Empty response

The do_upload() method sanitises the destination file names derived from the file name array. The standard PHP basename() function is used  to strip any path information, then any events of spaces, tabs or  other problematic characters are replaced with an underscore character _.  The following is the set of non-whitespace characters that are considered problematic:

^ * ! $ " ' ` ( ) , < > [ ] \ / | { }

The array returned from a successful do_upload() call will contain the adjusted file names.

The do_upload() method also has built-in support for  specifically renaming files during their upload.  You may wish to use this feature when the files you intend to upload have inconvenient names i.e. temporary files with random names that must be renamed to have a correct extension for processing.  To use this feature you are permitted to give a two element array as a "filename" in the file name array.  The first element of one of the nested arrays is the path to the file you want to upload. The second element of the nested array is the name you want the file to have when uploaded.

Examples:      

  • Array with file name pairs: array( array('./file1.tmp', 'example.json'), array('./file2.tmp', 'example.pdf'));                  
  • Mixed array: array( 'example.json', array('./file2.tmp', 'example.pdf'));                          
It is also possible to have your metadata reference a file that has been previously uploaded.  See the EasyPost Web API documentation for details of how this is done.
 
The do_upload() method does not throw exceptions on file upload errors.  Instead the array returned from do_upload() will include an array of strings named errs describing the files that failed.  The array errs will not appear in the response for a completely successful upload session.
 
    allow_debug( <true or false> )

Allow or dis-allow echoing of debug information during the library operation. Debugging output will go to the browser window when the library is used within a webserver.

    set_debug_echo_line_separator( [<separator>] )

Change the separator used between debugging output.  This function should be used when producing HTML output.  If no separator is stated with the call a HTML <br/> will be emitted between debug lines.  When using the library in a command line environment, debug output lines will be separated by a CR/LF.

    echo_log( <line> )

Output <line> when debugging mode is enabled (see allow_debug() above).

    version()

Returns version of the PHP EasyPost Web API Library as a string.


Need More Help ?

Please contact Bing Customer Service if you have problems using the library.