Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Fetching contributors…
Cannot retrieve contributors at this time
289 lines (181 sloc) 10.6 KB

Xero API wrapper


This library is designed to help ruby / rails based applications communicate with the publicly available API for Xero. If you are unfamiliar with the API, you should first read the documentation, located here


    require 'xero_gateway'

Authenticating with OAuth

OAuth is built into this library in a very similar manner to the Twitter gem by John Nunemaker ( So if you’ve used that before this will all seem familiar.

Consumer Key & Secret

First off, you’ll need to get a Consumer Key/Secret pair for your application from Xero.
Head to, log in and then click My Applications > Add Application.

If you want to create a private application (that accesses your own Xero account rather than your users), you’ll need to generate an RSA keypair and an X509 certificate. This can be done with OpenSSL as below:

    openssl genrsa –out privatekey.pem 1024
    openssl req –newkey rsa:1024 –x509 –key privatekey.pem –out publickey.cer –days 365
    openssl pkcs12 –export –out public_privatekey.pfx –inkey privatekey.pem –in publickey.cer

On the right-hand-side of your application’s page there’s a box titled “OAuth Credentials”. Use the Key and Secret from this box in order to set up a new Gateway instance.

(If you’re unsure about the Callback URL, specify nothing – it will become clear a bit later)

Xero Gateway Initialization

    require 'xero_gateway'

or for private applications

    require 'xero_gateway'

Request Token

You’ll then need to get a Request Token from Xero.

    request_token = gateway.request_token

You should keep this around – you’ll need it to exchange for an Access Token later. (If you’re using Rails, this means storing it in the session or something similar)

Next, you need to redirect your user to the authorisation url for this request token. In Rails, that looks something like this:

    redirect_to request_token.authorize_url

(Note that Xero doesn’t support the OAuth Callback parameter here)

Retrieving an Access Token

If you’ve specified a Callback URL when setting up your application, your user will be redirected to that URL with an OAuth Verifier as a GET parameter. You can then exchange your Request Token for an Access Token like this (assuming Rails, once again):

    gateway.authorize_from_request(request_token.token, request_token.secret, :oauth_verifier => params[:oauth_verifier])

(If you haven’t specified a Callback URL, the user will be presented with a numeric verifier which they must copy+paste into your application; see examples/oauth.rb for an example)

Now you can access Xero API methods:


Storing Access Tokens

You can also store the Access Token/Secret pair so that you can access the API without user intervention. Currently, these access tokens are only valid for 30 minutes, and will raise a XeroGateway::OAuth::TokenExpired exception if you attempt to access the API beyond the token’s expiry time.

    access_token, access_secret = gateway.access_token


Open examples/oauth.rb and change CONSUMER_KEY and CONSUMER_SECRET to the values for a Test OAuth Application in order to see an example of OAuth at work.

If you’re working with Rails, a controller similar to this might come in handy:

  class XeroSessionsController < ApplicationController
    before_filter :get_xero_gateway

    def new
      session[:request_token]  = @xero_gateway.request_token.token
      session[:request_secret] = @xero_gateway.request_token.secret

      redirect_to @xero_gateway.request_token.authorize_url

    def create
      @xero_gateway.authorize_from_request(session[:request_token], session[:request_secret],
                                           :oauth_verifier => params[:oauth_verifier])

      session[:xero_auth] = { :access_token  => @xero_gateway.access_token.token, 
                              :access_secret => @xero_gateway.access_token.secret };

    def destroy
      def get_xero_gateway
        @xero_gateway =, YOUR_OAUTH_CONSUMER_SECRET)


Note that I’m just storing the Access Token + Secret in the session here – you could equally store them in the database if you felt like refreshing them every 30 minutes ;)

Implemented interface methods

GET /api.xro/2.0/contact (get_contact_by_id)

Gets a contact record for a specific Xero organisation

    result = gateway.get_contact_by_id(contact_id)
    contact = if result.success?

GET /api.xro/2.0/contact (get_contact_by_number)

Gets a contact record for a specific Xero organisation


GET /api.xro/2.0/contacts (get_contacts)

Gets all contact records for a particular Xero customer.

    gateway.get_contacts(:type => :all, :sort => :name, :direction => :desc)
    gateway.get_contacts(:type => :all, :updated_after => 1.month.ago) # modified since 1 month ago

PUT /api.xro/2.0/contact

Saves a contact record for a particular Xero customer.

    contact = gateway.build_contact = "The contacts name" = "" = "555 123 4567"
    contact.address.line_1 = "LINE 1 OF THE ADDRESS"
    contact.address.line_2 = "LINE 2 OF THE ADDRESS" = "WELLINGTON"
    contact.address.region = "WELLINGTON" = "NEW ZEALAND"
    contact.address.post_code = "6021"

POST /api.xro/2.0/contact

Updates an existing contact record. = ""

POST /api.xro/2.0/contacts

Creates a list of contacts or updates them if they have a matching contact_id, contact_number or name.
This method uses only a single API request to create/update multiple contacts.

    contacts = [ => 'Joe Bloggs'), => 'Jane Doe')]
    result = gateway.update_contacts(contacts)

GET /api.xro/2.0/invoice (get_invoice_by_id)

Gets an invoice record for a specific Xero organisation


GET /api.xro/2.0/invoice (get_invoice_by_number)

Gets an invoice record for a specific Xero organisation


GET /api.xro/2.0/invoices (get_invoices)

Gets all invoice records for a particular Xero customer.

    gateway.get_invoices(1.month.ago) # modified since 1 month ago

PUT /api.xro/2.0/invoice

Inserts an invoice for a specific organization in Xero (Currently only adding new invoices is allowed).

Invoice and line item totals are calculated automatically.

    invoice = gateway.build_invoice({
      :invoice_type => "ACCREC",
      :due_date => 1.month.from_now,
      :invoice_number => "YOUR INVOICE NUMBER",
      :tax_inclusive => true,
      :includes_tax => false
    }) = "THE NAME OF THE CONTACT" = "12345" = "LINE 1 OF THE ADDRESS"    
      :description => "THE DESCRIPTION OF THE LINE ITEM",
      :unit_amount => 1000,
      :tax_amount => 125,
      :tracking_category => "THE TRACKING CATEGORY FOR THE LINE ITEM",
      :tracking_option => "THE TRACKING OPTION FOR THE LINE ITEM"


PUT /api.xro/2.0/invoices

Inserts multiple invoices for a specific organization in Xero (currently only adding new invoices is allowed).
This method uses only a single API request to create/update multiple contacts.

    invoices = [,]
    result = gateway.create_invoices(invoices)

GET /api.xro/2.0/accounts

Gets all accounts for a specific organization in Xero.


For more advanced (and cached) access to the accounts list, use the following.

    accounts_list = gateway.get_accounts_list

Finds account with code of ‘200’

    sales_account = accounts_list.find_by_code(200)

Finds all EXPENSE accounts. For a list of valid account types see XeroGateway::Account::TYPE

   all_expense_accounts = accounts_list.find_all_by_type('EXPENSE')

Finds all accounts with tax_type == ‘OUTPUT’. For a list of valid tax types see XeroGateway::Account::TAX_TYPE

   all_output_tax_accounts = accounts_list.find_all_by_tax_type('OUTPUT')

GET /api.xro/2.0/tracking

Gets all tracking categories and their options for a specific organization in Xero.


GET /api.xero/2.0/Organisation

Retrieves organisation details for the authorised application.


GET /api.xero/2.0/Currencies

Retrieves currencies in use for the authorised application.


GET /api.xero/2.0/TaxRates

Retrieves Tax Rates in use for the authorised application.



You can specify a logger to use (so you can track down those tricky exceptions) by using:

  gateway.logger ="log_file_name.log")

It doesn’t have to be a buffered logger – anything that responds to “info” will do just fine.

Jump to Line
Something went wrong with that request. Please try again.