Code Monkey home page Code Monkey logo

phaxio-dotnet's Introduction

📠 Phaxio

A Ruby gem for interacting with the Phaxio API.

Ruby Documentation

Installation

Add to your application's Gemfile:

gem 'phaxio', '~> 2.0.0'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install phaxio

Usage

Set up your API Key, API Secret, and, optionally, Webhook Token.

require 'phaxio'

Phaxio.api_key = '11111'
Phaxio.api_secret = '22222'
Phaxio.webhook_token = '33333'

Try sending a fax:

fax_file = File.open 'test.pdf', 'rb'
Phaxio::Fax.create to: '+15558675309', file: fax_file

You can include Phaxio::Resources to pull in the resource classes for convenience:

include Phaxio::Resources

fax_file = File.open 'test.pdf', 'rb'
Fax.create to: '+15558675309', file: fax_file

Currently Supported API Calls

Faxes

Fax.create

Create and send a fax.

fax_file = File.open 'test.pdf', 'rb'
ref = Fax.create to: '+15558675309', file: fax_file
# => Fax::Reference(id: 1234)
fax = ref.get
# => Fax(id: 1234, num_pages: 1, ...)
Fax.list

List faxes in date range.

start = 2.weeks.ago
stop = 1.week.ago
faxes = Fax.list created_after: start, created_before: stop
# => Phaxio::Resource::Collection([Fax(id: 1234, ...), ...])
faxes.length
# => 5
faxes.map(&:cost).inject(&:+)
# => 35
Fax.get

Get information about a specific fax.

fax = Fax.get 1234
# => Fax(id: 1234, ...)
Fax.cancel

Cancel a fax.

Fax.cancel 1234
# => Fax::Reference(id: 1234)
Fax.resend

Resend a fax.

Fax.resend 1234
# => Fax::Reference(id: 5678)
Fax.delete

Delete a fax. Only test faxes are allowed to be deleted.

Fax.delete 1234
# => true
Fax.delete_file

Delete fax file.

Fax.delete_file 1234
# => true
Fax.file
Fax.file 1234
# => File
Fax.test_receive

Test receiving a fax.

fax_file = File.open 'test.pdf', 'rb'
Fax.test_receive file: fax_file
# => true

Countries

Public::Country.list

Get a list of supported countries.

Public::Country.list
# => Phaxio::Resource::Collection([Public::Country(alpha2: 'US', ...), ...])

Phone Numbers

PhoneNumber.create

Provision a new phone number.

PhoneNumber.create country_code: 1, area_code: 555
# => PhoneNumber(phone_number: '+15558675309', ...)
PhoneNumber.list

List phone numbers that you own on Phaxio.

PhoneNumber.list
# => Phaxio::Resource::Collection([PhoneNumber(phone_number: '+15558675309', ...), ...])
PhoneNumber.get

Get information about a specific phone number.

PhoneNumber.get '+15558675309'
# => PhoneNumber(phone_number: '+15558675309', ...)
PhoneNumber.delete

Release a phone number.

PhoneNumber.delete '+15558675309'
# => true

Area Codes

Public::AreaCode.list

Lists available area codes for purchasing Phaxio numbers.

area_codes = Public::AreaCode.list toll_free: true
# => Phaxio::Resource::Collection([Public::AreaCode(city: 'Toll Free Service', ...), ...], page: 1)

PhaxCodes

PhaxCode.create

Creates a PhaxCode. Returns data about the PhaxCode by default, or a .png file if type: 'png' is passed.

PhaxCode.create metadata: 'test_phax_code'
# => PhaxCode(identifier: 'phax-code-identifier')
PhaxCode.create type: 'png'
# => File
PhaxCode.get

Gets a PhaxCode. Returns data about the PhaxCode by default, or a .png file if type: 'png' is passed.

PhaxCode.get 'phax-code-identifier'
# => PhaxCode(identifier: 'phax-code-identifier', metadata: 'phax-code-metadata')
PhaxCode.get 'phax-code-identifier', type: 'png'
# => File

Account

Account.get

Get information about your Phaxio account.

Account.get
# => Account(balance: 1000, faxes_today: 0, faxes_this_month: 100)

Webhook

Webhook.valid_signature?

Validate the webhook signature sent with a Phaxio webhook. Requires that Phaxio.webhook_token be set.

Webhook.valid_signature? received_signature, webhook_url, received_params, received_files
# => true

Webhook Validation Example with Sinatra

require 'sinatra/base'
require 'phaxio'

class PhaxioWebhookExample < Sinatra::Base
  Phaxio.webhook_token = 'YOUR WEBHOOK TOKEN HERE'

  post '/webhook' do
    signature = request.env['HTTP_X_PHAXIO_SIGNATURE']
    url = request.url
    file_params = params[:file]
    if Phaxio::Webhook.valid_signature? signature, url, webhook_params, file_params
      'Success'
    else
      'Invalid webhook signature'
    end
  end

  def webhook_params
    params.select do |key, _value|
      %w(success is_test direction fax metadata message event_type).include?(key)
    end
  end
end

Webhook Validation Example with Rails Controller

class WebhookController < ApplicationController
  skip_before_action :verify_authenticity_token

  def index
    signature = request.headers['X-Phaxio-Signature']
    Phaxio.webhook_token = 'YOUR WEBHOOK TOKEN HERE'
    url = request.original_url

    Rails.logger.debug "URL: " + url
    Rails.logger.debug "Signature: " + signature
    Rails.logger.debug "params: " + params.inspect
    Rails.logger.debug "webhook_params: " + webhook_params.to_h.inspect

    if Phaxio::Webhook.valid_signature? signature, url, webhook_params.to_h, file_params
      Rails.logger.debug "Success"
      render plain: 'Success'
    else
      Rails.logger.debug "Invalid webhook signature"
      render plain: 'Invalid webhook signature'
    end
  end

  def webhook_params
    params.permit(:success, :is_test, :direction, :fax, :metadata, :event_type, :message)
  end

  def file_params
    if params[:file]
      [{ :name => 'file', :tempfile => params[:file].tempfile }]
    end
  end
end

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

phaxio-dotnet's People

Contributors

jnankin avatar noelherrick avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

phaxio-dotnet's Issues

Specifying any FaxOptions in the fax.Send causes RuntimeBinderException

var testOptions = new FaxOptions
            {
                HeaderText = "headertext",
                StringData = "somedata",
                StringDataType = "html",
                IsBatch = true,
                BatchDelaySeconds = 10,
                AvoidBatchCollision = true,
                CallbackUrl = "https://example.com/callback",
                CancelTimeoutAfter = 20,
                CallerId = "3213214321",
                FailureErrorType = "failure_type"
            };

            fax.Send(document.Address, file, testOptions);

{"Cannot perform runtime binding on a null reference"}

at CallSite.Target(Closure , CallSite , Object , String )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at Phaxio.PhaxioClient.SendFax(IEnumerable1 toNumbers, IEnumerable1 files, FaxOptions options)
at Phaxio.Entities.Fax.Send(IEnumerable1 toNumbers, IEnumerable1 files, FaxOptions options)
at Phaxio.Entities.Fax.Send(String toNumber, FileInfo file, FaxOptions options)
at Oviss.EmailSender.Program.SendFax(Documents document) in C:\projects\Oviss.EmailSender\Oviss.EmailSender\Oviss.EmailSender\Program.cs:line 94
at Oviss.EmailSender.Program.Main(String[] args) in C:\projects\Oviss.EmailSender\Oviss.EmailSender\Oviss.EmailSender\Program.cs:line 55
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

But Send works fine if I don't specify FaxOptions.

Sample app returns 500 errors

From a customer:

If you load the phaxio-dotnet project, fire it up and point Phaxio webhooks to it, right away you’ll get “503 Service Unavailable” if you send a test fax ([I] published the URL through the firewall to my local desktop so I could step through the code). Sending a live fax does a little better but you still get HTTP/1.1 500 Internal Server Error.

Sending to Multiple Numbers, Multiple Content URLs, and Multiple Tags is broken

A bug exists in the AddParameter function of the RestRequest class on line number 40. The intended purpose of this line is to add on extra values to parameters that accept collections. This is used when trying to send a fax to multiple phone numbers, with multiple content URLs, or with multiple tags. The current code actually just overwrites the parameter instead of adding to it. As a result, it is not possible to send a fax to multiple phone numbers, multiple content URLs, or with multiple tags with the current .net library. It will only end up sending the last parameter in the collection to the Phaxio API, such as the last phone number when sending a fax to a list of 2 or more numbers.

Target .NET Standard

The Phaxio library currently targets .NET Framework v4.6. We should target multiple frameworks, including .NET Standard.

Accounting for nulls when retrieving a failed fax

In the current Phaxio API, if you retrieve a failed fax, it's bitrate and resolution on the failed recipient will be null. Currently, the Recipient class does not account for this and will throw an exception when retrieving any failed fax job by ID. Either these two properties on the Recipient class need to be null-able or the value needs to be checked for null and set to 0 if null.

Doesn't support v2.1 Phaxio API

The code doesn't work for the current v2.1 API version. One reason it breaks is v2.1 doesn't support parameter authorization and that's the only authorization method the Phaxio Client exposes. I think we need to add HTTP Authorization option to the client library.

add an implementation of Fax.Create which allows submission of files by Byte[]

Users should be able to pass an array of Byte[]s and an array of strings which will be POSTed to Phaxio without having to use File objects.

The 1st Byte[] will contain the image data for a file with a filename that is the 1st string in the filenames string array, etc.

The current implementation using Files can simply call the Byte[] implementation and pass in Byte[]s for the files

'FaxReceipt; does not contain a definition for 'json'

When you download the solution and try to run Phaxio.Examples.ReceiveCallback you get the error 'Phaxio.Examples.ReceiveCallback.Models.FaxReceipt' does not contain a definition for 'Json'. In the FaxReceipt class, json is not defined. It's an easy fix but I wanted to point it.

Missing fax parameters

When sending a Phaxio fax, we're missing several parameters with the dotnet client such as header_page_nums, header_timezone, and callback_url. All are important but especially the callbackURL. Are there plans to update the dotnet package?

John

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.