Quickbooks Online REST API V3 - Ruby
On Nov 10, 2022 version 2 was released which no longer supports Ruby 2.5.
| quickbooks-ruby | branch | ruby |
|---|---|---|
| 1 | master | = 2.6.0 |
Integration with Quickbooks Online via the Intuit Data Services v3 REST API.
This library communicates with the Quickbooks Data Services v3 API, documented at:
0.1.0 introduced a backwards-incompatible change in how boolean attributes are handled. As of 0.1.0 any boolean like:
xml_accessor :active?, :from => 'Active'
will be accessible via active?. Thereby eliminating custom code like:
def active?
active.to_s == 'true'
endNow a call to active? that is not set will return nil. Otherwise it return true / false.
Moreover, there is no longer a getter method e.g. active (without the trailing ?).
This has been tested on 2.x
Ruby 1.9.x is not supported.
Gems:
oauth2roxml : Workhorse for (de)serializing objects between Ruby & XMLnokogiri : XML parsingactive_model : For validationsAdd this line to your application's Gemfile:
gem 'quickbooks-ruby'
And then execute:
$ bundle
Or install it yourself as:
$ gem install quickbooks-ruby
As of July 2025 75 is the minimum version supported. If not specified the QBO API will default to this version. You can specify another version of your choice via:
Quickbooks.minorversion = 75An API app provides two sets of OAuth key for production and development. Since October 22, 2014, only Sandbox Companies are allowed to connected to the QBO via the development key. The end-point for sandbox mode is https://sandbox-quickbooks.api.intuit.com.
By default, the gem runs in production mode. If you prefer to develop / test the integration with the development key, you need to config the gem to run in sandbox mode:
Quickbooks.sandbox_mode = trueWhat follows is an example using Rails but the principles can be adapted to any other framework / pure Ruby.
Create a Rails initializer (config/initializers/quickbooks-ruby.rb) with:
oauth_params = {
site: "https://appcenter.intuit.com/connect/oauth2",
authorize_url: "https://appcenter.intuit.com/connect/oauth2",
token_url: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"
}
oauth2_client = OAuth2::Client.new(ENV['OAUTH_CLIENT_ID'], ENV['OAUTH_CLIENT_SECRET'], oauth_params)Your Controller action (the grantUrl above) should look like this:
def authenticate
redirect_uri = quickbooks_oauth_callback_url
grant_url = oauth2_client.auth_code.authorize_url(redirect_uri: redirect_uri, response_type: "code", state: SecureRandom.hex(12), scope: "com.intuit.quickbooks.accounting")
redirect_to grant_url
endWhere quickbooks_oauth_callback_url is the absolute URL of your application that Intuit should send the user when authentication succeeds.
That action should look like:
def oauth_callback
if params[:state].present?
# use the state value to retrieve from your backend any information you need to identify the customer in your system
redirect_uri = quickbooks_oauth_callback_url
if resp = oauth2_client.auth_code.get_token(params[:code], redirect_uri: redirect_uri)
# save your tokens here. For example:
# quickbooks_credentials.update_attributes(access_token: resp.token, refresh_token: resp.refresh_token, realm_id: params[:realmId])
end
end
endYour Redirect URI needs to be publicly accessible. If you are still in development and running everything via localhost you will need to use a tool like Ngrok to expose your localhost to a public URL with HTTPS.
Most likely you will want to persist the OAuth access credentials so that users don't need to re-authorize your application in every session.
An example database table could have fields likes:
access_token text,
access_token_expires_at datetime,
refresh_token text,
refresh_token_expires_at datetime,
realm_id textOnce you have your user's OAuth access and refresh token string values you can create an access token object to issue requests:
qb_access_token = quickbooks_credentials.access_token
qb_refresh_token = quickbooks_credentials.refresh_token
access_token = OAuth2::AccessToken.new(oauth2_client, qb_access_token, refresh_token: qb_refresh_token)Each access token is only valid for one hour. The access token and refresh token can be refreshed directly by using OAuth Client:
new_access_token_object = access_token.refresh!The token must be assigned to a variable to prevent the loss of your new access token, which will void your credentials and a new set of credentials have to be acquired by authorizing the application again. You should then persist it to your storage.
Unauthorized (expired) access to the API will raise a OAuth2::Error error.
For more information on access token expiration and refresh token expiration, please refer to the official documentation.
You will need to continuously refresh access tokens and ensure token validity. Access Tokens expire after 1 hour.
My personal architecture in a Rails application is similar to this:
…And then I have an IntuitAccount model with attributes:
oauth2_access_token | text | | |
oauth2_access_token_expires_at | timestamp without time zone | | |
oauth2_refresh_token | text | | |
oauth2_refresh_token_expires_at | timestamp without time zone | | |
track_purchase_order_quantity | boolean | | not null | falseAnd then finally include this concern in the model:
class IntuitAccount "123", :access_token => access_token)
customers = service.query() # Called without args you get the first page of results
# yields
customers.entries = [ .. array of Quickbooks::Model::Customer objects .. ]
customers.start_position = 1 # the current position in the paginated set
customers.max_results = 20 # the maximum number of results in this query setUnder the hood Intuit uses a simple SQL-like dialect for retrieving objects, the above no-arg use of query() issued a Select * From Customer.
You can issue your own query by passing the complete and valid query as the first argument:
customers.query("Select Id, GivenName From Customer")Each Entity has different fields you can retrieve & filter on. Refer to Intuit documentation for details.
Do not pass pagination parameters in your query - pass them as additional options, using :page and :per_page:
# to use the default query
customers.query(nil, :page => 2, :per_page => 25)
# to use a custom query: find customers updated recently and only select a few attributes
query = "Select Id, GivenName From Customer Where Metadata.LastUpdatedTime>'2013-03-13T14:50:22-08:00' Order By Metadata.LastUpdatedTime"
customers.query(query, :page => 2, :per_page => 25)Often one needs to retrieve multiple pages of records of an Entity type
and loop over them all. Fortunately there is the query_in_batches collection method:
query = nil
Customer.query_in_batches(query, per_page: 1000) do |batch|
batch.each do |customer|
# ...
end
endThe first argument to query_in_batches is the query (which
can be nil to retrieve the default items in that collection).
If you're are running a custom Query then pass it instead.
The second argument is the options, which are optional.
By default, the options are per_page: 1000.
You may retrieve an array of objects like so:
customers = service.allUnlike other query functions which return a Quickbooks::Collection object, the all method returns an array of objects.
You can retrieve a specific Intuit object like so:
customer = service.fetch_by_id("99")
puts customer.company_name
=> "Acme Enterprises"The find_by(attribute, value) method allows you to retrieve objects with a simple WHERE query using a single attribute. The attribute may be given as a symbol or a string.
Symbols will be automatically camelcased to match the Quickbooks API field names.
customer = service.find_by(:family_name, "Doe")
or
customer = service.find_by("FamilyName", "Doe")By default updating an object will un-set any attributes that are NOT specified in the update request. That is, the update is NOT sparse by default. Thus, be careful as you might accidentally unset attributes that you did not specify.
Example:
# fetch a Customer to change their name
customer = service.fetch_by_id("99")
customer.company_name = "Neo Pets"
service.update(customer)In the above example since we retrieved all fields and then just changed a single attribute, we have given the "complete" entity back to Intuit and effectively only the name is changed.
If you don't have the complete object on hand and only want to change a couple of attributes without un-setting what you are not specifying than you want to use a sparse update:
# update a Customer's name when we only know their ID
customer = Quickbooks::Model::Customer.new
customer.id = 99
customer.company_name = "New Company Name"
service.update(customer, :sparse => true)Some models require a reference to be set, to a Customer, or an Item, etc. In the Quickbooks API these references
are labeled via a property like CustomerRef. In quickbooks-ruby the assignment of these references is done
by using the setter on the _id property.
For example, to specify a Customer with ID 99 on an Invoice you would do this:
invoice = Quickbooks::Model::Invoice.new
invoice.customer_id = 99This will automatically set a CustomerRef XML packet with a value of 99.
The QBO API documentation states that SalesReceipt has a ShipMethodRef attribute. Normally, all attributes of a Ref type
take an pseudo-integer argument, representing the foreign ID, which in turn point to a valid object with that ID.
I say pseudo because they look like Integers but Intuit has made it clear they should be handled as strings.
Anyways, its subtle but the value for a SalesReceipt#ShipMethodRef while it is a BaseReference needs to be set manually:
shipping_reference = Quickbooks::Model::BaseReference.new('FedEx', name: 'FedEx')
receipt.ship_method_ref = shipping_referenceA complete example on generating a basic invoice:
# Given a Customer with ID=99 lets invoice them for an Item with ID=500
invoice = Quickbooks::Model::Invoice.new
invoice.customer_id = 99
invoice.txn_date = Date.civil(2013, 11, 20)
invoice.doc_number = "1001" # my custom Invoice # - can leave blank to have Intuit auto-generate it
line_item = Quickbooks::Model::InvoiceLineItem.new
line_item.amount = 50
line_item.description = "Plush Baby Doll"
line_item.sales_item! do |detail|
detail.unit_price = 50
detail.quantity = 1
detail.item_id = 500 # Item ID here
end
invoice.line_items 234Notes: line_item.amount must equal the `
No open issues yet, or sync has not completed.