Code Samples: Ruby

Please note that C# is our Official client, and that is what we support. This Ruby code has been provided by another customer and we encourage you to let us know if you find any problems so that we can update accordingly.

Sendfax Method

Fax.rb
require './doxipher.rb'
require 'faraday'
require 'pp'
require 'time'
require 'json'
USERNAME = "" #Enter Valid Username
APIKEY = "" # Enter Valid ApiKey
VECTOR = "x49e*wJVXr8BrALE"
ENCRYPTIONKEY = ""# Enter Valid EncryptionKey
FAX_SERVER_URL = "https://api.sfaxme.com"
#FAX_SERVER_URL = "http://127.0.0.1:5000" # for testing you can use `nc -k -l 5000` on the cmd
def get_token
	timestr = Time.now.utc.iso8601()
  raw = "Username=#{USERNAME}&ApiKey=#{APIKEY}&GenDT=#{timestr}"
  dox = Doxipher.new(ENCRYPTIONKEY, {:base64=>true})
	cipher = dox.encrypt(raw)
	return cipher
end
def send_fax(fax_no, filename)
	tid = nil
	conn = Faraday.new(:url => FAX_SERVER_URL, :ssl => { :ca_file => 'C:/Ruby200/cacert.pem' }  ) do |faraday|#Certificate required
  #conn = Faraday.new(:url => FAX_SERVER_URL) do |faraday|# None SSL
		faraday.request :multipart				  # checks for files in the payload, otherwise leaves everything untouched
    faraday.request  :url_encoded            # form-encode POST params
		faraday.response :logger                  # log requests to STDOUT
		faraday.adapter Faraday.default_adapter  # make requests with Net::HTTP
	end
	#pp conn
	token = get_token()
	parts = ["sendfax?",  
           "token=#{CGI.escape(token)}",  
           "ApiKey=#{CGI.escape(APIKEY)}",
           "RecipientFax=#{fax_no}",  
           "RecipientName=Gene", 
           "OptionalParams=&"
  ]
	path = "/api/" + parts.join("&")
	response = conn.post path do |req|
		 req.body = {}
		 req.body['file'] = Faraday::UploadIO.new(filename, 'application/pdf', 'test2.pdf')
	end
	pp response
end
filename = 'C:/temp/test2.pdf'
fax_no = ""#Enter a valid 11 digit US Fax Number
send_fax(fax_no, filename)
Returned response
body="{\"SendFaxQueueId\":\"9A4CEBC407C247419DCAAB1D3BE55D6A\",\"isSuccess\":true,\"message\":\"Fax is received and being processed\"}",

SendfaxStatus Method

Faxstatus.rb
require './doxipher.rb'
require 'faraday'
require 'pp'
require 'time'
USERNAME = ""# Enter a valid Username
APIKEY = ""# Enter a valid ApiKey
VECTOR = "x49e*wJVXr8BrALE"
ENCRYPTIONKEY = ""#Enter a valid encryptionkey
FAX_SERVER_URL = "https://api.sfaxme.com"
def get_token
  timestr = Time.now.utc.iso8601()
  raw = "Username=#{USERNAME}&ApiKey=#{APIKEY}&GenDT=#{timestr}"
  dox = Doxipher.new(ENCRYPTIONKEY, {:base64=>true})
  cipher = dox.encrypt(raw)
  return cipher
end
def send_fax_status(faxid)
  #faxid = nil
  conn = Faraday.new(:url => FAX_SERVER_URL, :ssl => { :ca_file => 'C:/Ruby200/cacert.pem' }  ) do |faraday|
    faraday.request  :url_encoded            # form-encode POST params
    faraday.response :logger                  # log requests to STDOUT
    faraday.adapter Faraday.default_adapter  # make requests with Net::HTTP
  end
  #pp conn
  token = get_token()
  parts = ["sendfaxstatus?",  
           "token=#{CGI.escape(token)}",  
           "ApiKey=#{CGI.escape(APIKEY)}",
           "SendFaxQueueId=#{faxid}"  #Third
  ]
  path = "/api/" + parts.join("&")
  response = conn.get path do |req|
    req.body = {}
  end
  pp response
end
faxid = ''# Enter a valid FaxId from the SendFax JSON response returned in the body as SendFaxQueueId
send_fax_status(faxid)
Returned Response
body= "{\"RecipientFaxStatusItems\":[],\"isSuccess\":true,\"message\":\"Processing fax request\"}",
Check the status every 3 minutes thereafter. A successful response is shown next
body="{\"RecipientFaxStatusItems\":[{\"SendFaxQueueId\":\"CB7BE649CDB54D399F753F381F48D950\",\"IsSuccess\":true,\"ResultCode\":0,\"ErrorCode\":0,\"ResultMessage\":\"OK\",\"RecipientName\":\"Gene\",\"RecipientFax\":\"15123668506\",\"TrackingCode\":\"\",\"FaxDateUtc\":\"2013-07-29T13:19:20Z\",\"FaxId\":2130729131840997919,\"Pages\":2,\"Attempts\":1}],\"isSuccess\":true,\"message\":\"Fax request is complete\"}",

ReceiveInboundFax Method

ReceiveInboundFax.rb
require './doxipher.rb'
require 'faraday'
require 'pp'
require 'time'
USERNAME = ""#Enter a valid username
APIKEY = ""#Enter a valid ApiKey
VECTOR = "x49e*wJVXr8BrALE"
ENCRYPTIONKEY = ""#Enter a valid encryptionkey
FAX_SERVER_URL = "https://api.sfaxme.com"
def get_token
  timestr = Time.now.utc.iso8601()
   raw = "Username=#{USERNAME}&ApiKey=#{APIKEY}&GenDT=#{timestr}"
   dox = Doxipher.new(ENCRYPTIONKEY, {:base64=>true})
  cipher = dox.encrypt(raw)
  return cipher
end
def receive_inbound_fax(maxitems)
  conn = Faraday.new(:url => FAX_SERVER_URL, :ssl => { :ca_file => 'C:/Ruby200/cacert.pem' }  ) do |faraday|
    faraday.request  :url_encoded            # form-encode POST params
    faraday.response :logger                  # log requests to STDOUT
    faraday.adapter Faraday.default_adapter  # make requests with Net::HTTP
  end
  #pp conn
  token = get_token()
  parts = ["receiveinboundfax?",
           "token=#{CGI.escape(token)}",
           "ApiKey=#{CGI.escape(APIKEY)}",
           "StartDateUTC=#{}",
           "EndDateUTC=#{}",
           "MaxItems=#{maxitems}",
  ]
  path = "/api/" + parts.join("&")
  response = conn.get path do |req|
    req.body = {}
  end
  pp response
end
startdate = ''# Enter a valid Start Date in UTC time 
enddate = ''# Enter a valid End Date in UTC time to complete the date range criteria
maxitems = '500'#Enter a number from 1 to 500 to retrieve that number of results
receive_inbound_fax(maxitems)
Returned Response
body="{\"InboundFaxItems\":[{\"FaxId\":\"XXXXXXXXXXXXXXXXXXX\",\"Pages\":\"2\",\"ToFaxNumber\":\"15125314406\",\"FromFaxNumber\":\"5125314401\",\"FromCSID\":\"512.531.4401\",\"FaxDateUtc\":\"10/18/2012 2:56:04 PM\"},{\"FaxId\":\" XXXXXXXXXXXXXXXXXXX \",\"Pages\":\"2\",\"ToFaxNumber\":\"15125314407\",\"FromFaxNumber\":\"5125314401\",\"FromCSID\":\"512.531.4401\",\"FaxDateUtc\":\"10/18/2012 2:56:04 PM}],\"FaxCount\":101,\"LastWatermark\":\" XXXXXXXXXXXXXXXXXXX \",\"HasMoreItems\":\"false\",\"isSuccess\":true,\"message\":\"Success\"}",

Note: If there are more items to retrieve the HasMoreItems will be set to “true”.

DownloadInboundFaxAsPdf Method

DownloadInboundFaxAsPdf.rb
require './doxipher.rb'
require 'faraday'
require 'pp'
require 'time'
USERNAME = ""#Enter a valid Username
APIKEY = ""Enter a valid Apikey
VECTOR = "x49e*wJVXr8BrALE"
ENCRYPTIONKEY = ""#Enter a valid EncryptionKey
FAX_SERVER_URL = "https://api.sfaxme.com"
def get_token
  timestr = Time.now.utc.iso8601()
  raw = "Username=#{USERNAME}&ApiKey=#{APIKEY}&GenDT=#{timestr}"
  dox = Doxipher.new(ENCRYPTIONKEY, {:base64=>true})
  cipher = dox.encrypt(raw)
  return cipher
end
def download_inbound_fax_as_pdf(faxid)
  conn = Faraday.new(:url => FAX_SERVER_URL, :ssl => { :ca_file => 'C:/Ruby200/cacert.pem' }  ) do |faraday|
    faraday.request  :url_encoded            # form-encode POST params
    faraday.response :logger                  # log requests to STDOUT
    faraday.adapter Faraday.default_adapter  # make requests with Net::HTTP
end
  token = get_token()
  parts = ["downloadinboundfaxaspdf?",
           "token=#{CGI.escape(token)}",
           "ApiKey=#{CGI.escape(APIKEY)}",
           "FaxId=#{faxid}"
  ]
  path = "/api/" + parts.join("&")
  response = conn.get path
    a = response.body
    File.open('C:/temp/2121206215127980253.pdf', 'wb') do |f|
      f.write (a)
      f.close
  end
  pp response
end
faxid = '2121206215127980253'#Enter a faxid from the ReceiveInboundFax list
download_inbound_fax_as_pdf(faxid)

DownloadInboundFaxAsTif Method

DownloadInboundFaxAsTif.rb
require './doxipher.rb'
require 'faraday'
require 'pp'
require 'time'
USERNAME = ""#Enter a valid Username
APIKEY = ""#Enter a valid ApiKey
VECTOR = "x49e*wJVXr8BrALE"
ENCRYPTIONKEY = ""#Enter a valid EncryptionKey
FAX_SERVER_URL = "https://api.sfaxme.com"
def get_token
  timestr = Time.now.utc.iso8601()
  raw = "Username=#{USERNAME}&ApiKey=#{APIKEY}&GenDT=#{timestr}"
  dox = Doxipher.new(ENCRYPTIONKEY, {:base64=>true})
  cipher = dox.encrypt(raw)
  return cipher
end
def download_inbound_fax_as_tif(faxid)
  conn = Faraday.new(:url => FAX_SERVER_URL, :ssl => { :ca_file => 'C:/Ruby200/cacert.pem' }  ) do |faraday|
  #conn = Faraday.new(:url => FAX_SERVER_URL) do |faraday|
    faraday.request  :url_encoded            # form-encode POST params
    faraday.response :logger                  # log requests to STDOUT
    faraday.adapter  :net_http
  end
  token = get_token()
  parts = ["downloadinboundfaxastif?",
           "token=#{CGI.escape(token)}",
           "ApiKey=#{CGI.escape(APIKEY)}",
           "FaxId=#{faxid}"
  ]
  path = "/api/" + parts.join("&")
  response = conn.get path
  a = response.body
  File.open('C:/temp/2121206215127980253.tif', 'wb') do |f|
    #a.each do | byte |
    f.write (a)
    f.close
  end
  pp response
end
faxid = '2121206215127980253'#Enter a faxid from the ReceiveInboundFax list
download_inbound_fax_as_tif(faxid)

AES Encryption

doxifer.rb
require 'openssl'
require "base64"
class Doxipher
  #:iv =>  #Pass in a 16 byte value. Defaults to 16 0 bytes which is not good. class Doxipher
	def initialize( key, options = {} )
		@base64 = options[:base64] || false
		@key = key.clone
		#@iv = options[:iv] || "\0" * 16
    @iv = 'x49e*wJVXr8BrALE'
	end
	def encrypt( plain = nil, &block )
		if @base64
			Base64.encode64( cipher( plain, false, &block ))
		else
			cipher( plain, false, &block )
		end
	end
	def decrypt( cipher_text = nil, &block ) 
		cipher(cipher_text, true, &block)
	end
	def <<( data)
		@data << @cipher.update( decode_if_needed(data) )
	end
	private
	def decode_if_needed(data)
		@base64 && @decrypt ? Base64.decode64(data) : data
	end
	def cipher( data = nil, _decrypt = false, &block ) 
		@decrypt = _decrypt
		@cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
		if _decrypt
			@cipher.decrypt
		else 
			@cipher.encrypt
		end
		@cipher.key = @key
		@cipher.iv = @iv
		if block_given? 
			@data = ''
			block.call self
		else
			@data = @cipher.update decode_if_needed(data) rescue nil
			@data = data if @data.nil?
		end
		@data << @cipher.final
		@data
	end
end