Overview

You use the FAX API to send fax in any fax numbers anywhere in the world. The workflow for sending fax messages using the Fax API is:

  1. Create a request to send Fax.
  2. Check the response codes and ensure that you sent the request correctly.
  3. Your fax is delivered to the fax number.
  4. If you set callback in the request, check that your app received the callback correctly.

Implementing the Fax API workflow with Delete File

To use the Fax API:

  1. Create a request and send the Fax:
    #!/bin/bash
    
    base_url='https://fax.to/api/v2'
    action='/fax'
    key='API_KEY'
    fax_number='+441224459292'
    document_id='112601'
    delete_file='1'
    
    curl -X POST "$base_url$action" \
    -d api_key=$key \
    -d fax_number=$fax_number \
    -d document_id="$document_id"
    -d delete_file="$delete_file"
    
    <?php
    
    $params = [
    	'fax_number' => '+441224459292',
    	'document_id' => '112601'
            'delete_file' => '1'
    ];
    
    $defaults = [
    	CURLOPT_URL => 'https://fax.to/api/v2/fax?api_key=API_KEY',
    	CURLOPT_POST => true,
    	CURLOPT_POSTFIELDS => $params
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, $defaults);
    
    $response = curl_exec($ch);
    
    echo $response;
    
    import urllib
    import urllib2
    
    params = {
        'api_key': 'API_KEY',
        'fax_number': '+441224459292',
        'document_id': '112601'
        'delete_file': '1'
    }
    
    url = 'https://fax.to/api/v2/fax?' + urllib.urlencode(params)
    
    request = urllib2.Request(url)
    request.add_header('Accept', 'application/json')
    request.add_header('Content-Type', 'multipart/form-data')
    request.add_data('')
    response = urllib2.urlopen(request)
    
    require "net/http"
    require "uri"
    
    uri = URI.parse("https://fax.to/api/v2/fax")
    params = {
        'api_key' => 'API_KEY',
        'fax_number' => '+441224459292',
        'document_id' => '112601',
        'delete_file' => '1'
    }
    
    response = Net::HTTP.post_form(uri, params)
    
    puts response.body
    

    For setting up the libraries please checkout

    using System;
    using System.Diagnostics;
    using IO.Swagger.Api;
    using IO.Swagger.Client;
    using IO.Swagger.Model;
    
    namespace Example
    {
        public class FaxPostExample
        {
            public void main
            {
                var apiInstance = new FaxApi();
                var apiKey = API_KEY;
                var faxNumber = +441224459292;
                var documentId = 56;
                var tsiNumber = +441224459292;
                var file = new System.IO.Stream();
                var deleteFile = 1;  // int? | Whether to delete file after fax transaction. (put 1 to delete) (optional) 
                
                try
                {
                    apiInstance.FaxPost(apiKey, faxNumber, documentId, tsiNumber, file, deleteFile);
                }
                catch (Exception e)
                {
                    Debug.Print("Exception when calling FaxApi.FaxPost: " + e.Message );
                }
            }
        }
    }
    
  2. Check the response to ensure that you sent the request to Fax.to correctly:
    <?php
      // Decode the json object you retrieved when you ran the request.
      $decodedResponse = json_decode($response, true);
      var_dump($decodedResponse);
    
      
    
      
    
    import json
    
    # Using the response object from the request
    
    if response.code == 200 :
        data = response.read()
        # Decode JSON response from UTF-8
        decoded_response = json.loads(data.decode('utf-8'))
        # Check if your messages are succesful
        status = decoded_response["status"]
        fax_job_id = decoded_response["fax_job_id"]
        user_cash_balance = decoded_response["user_cash_balance"]
        cost = decoded_response["cost"]
        
    else :
        # Check the errors
        print "unexpected http {code} response from Fax.to api". response.code
    
    require 'json'
    
    # Decode the json object from the response object you retrieved from the request.
    if response.kind_of? Net::HTTPOK
      decoded_response = JSON.parse(response.body )
    
      
      status = decoded_response["status"]
      fax_job_id = decoded_response["fax_job_id"]
      user_cash_balance = decoded_response["user_cash_balance"]
      cost = decoded_response["cost"]
      
    else
      puts response.code + " error sending fax"
    end
    
    //Decode the json object you retrieved when you ran the request.
    
    var decodedResponse = JSON.parse(responseData);
    
    console.log('You sent ' + decodedResponse['message-count'] + ' messages.\n');
    
    decodedResponse['messages'].forEach(function(message) {
        if (message['status'] === "0") {
          console.log('Success ' + decodedResponse['message-id']);
        }
        else {
          console.log('Error ' + decodedResponse['status']  + ' ' +  decodedResponse['error-text']);
        }
    });
    
  3. Your fax is delivered to the fax number.
  4. If you set callback in the API settings, use the Data sent to your webhook endpoint to update your own record:
    <?php
    // Work with get or post
    $request = $_POST;
    
    // Check that this is a delivery receipt.
    if (!isset($request['fax_job_id']) OR !isset($request['fax_job_id'])) {
        error_log('This is not a delivery receipt');
        return;
    }
    
    //Check if your message has been delivered correctly.
    if ($request['status'] == 'success') {
        error_log("Success {$request['msg_code']} {$request['message']}");
    } elseif ($request['status'] == 'failed') {
        error_log("Failed {$request['msg_code']} {$request['message']}");
    } else {
        error_log("Failed {$request['msg_code']} {$request['message']}");
    }
    
    #To run this code, replace the MyHandler in
    # https://wiki.python.org/moin/BaseHttpServer With the following code,
    from urlparse import urlparse, parse_qs
    class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
        def do_GET(s):
            """Tell Fax.to that you have recieved the GET request."""
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            """Parse parameters in the GET request"""
            parsed_path = urlparse(s.path)
            try:
                    delivery_receipt = dict(
                    [p.split('=') for p in parsed_path[4].split('&')])
            except:
                    delivery_receipt = {}
    
                """Check the is a delivery receipt"""
            if 'text' in delivery_receipt:
                print ("This is not a delivery receipt")
            elif delivery_receipt['status'] != "success":
                print "Fail:" + delivery_receipt['status']
                + ": " + delivery_receipt['msg_code'] +  ".\n"
            else:
                print "success"
                    
    
    require 'socket'
    require 'uri'
    
    def handle_delivery_receipt(request_line)
    #Parse the parameters and check if the message was delivered
      params = URI::decode_www_form(request_line).to_h
      if params["status"].nil? or params["fax_job_id"].nil?
        p ('This is not a delivery receipt')
      elsif params["status"] != 'success'
        p ("Your request " + params["status"] +
        "because of " + params["msg_code"] );
      else
        p ("Success for request " + params['fax_job_id'] )
      end
    end