百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
Q

quickbooks-ruby

> 编程语言
开源

Quickbooks Online REST API V3 - Ruby

390 stars0 点赞4 次浏览
访问官网GitHub

工具介绍

Quickbooks Online REST API V3 - Ruby

Important: Potential Breaking Changes

On Nov 10, 2022 version 2 was released which no longer supports Ruby 2.5.

quickbooks-ruby branch ruby
1 master = 2.6.0

Quickbooks-Ruby

Integration with Quickbooks Online via the Intuit Data Services v3 REST API.

This library communicates with the Quickbooks Data Services v3 API, documented at:

Data Services v3

Changes in 0.1.x from 0.0.x

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:

ruby
def active?
  active.to_s == 'true'
end

Now 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 ?).

Requirements

This has been tested on 2.x

Ruby 1.9.x is not supported.

Dependencies

Gems:

  • oauth2
  • roxml : Workhorse for (de)serializing objects between Ruby & XML
  • nokogiri : XML parsing
  • active_model : For validations

Installation

Add this line to your application's Gemfile:

gem 'quickbooks-ruby'

And then execute:

$ bundle

Or install it yourself as:

$ gem install quickbooks-ruby

Minorversion

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:

ruby
Quickbooks.minorversion = 75

Sandbox Mode

An 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:

ruby
Quickbooks.sandbox_mode = true

Getting Started & Initiating Authentication Flow with Intuit

What 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:

ruby
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:

ruby
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
end

Where 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:

ruby
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
end

Your 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:

sql
access_token text,
access_token_expires_at datetime,
refresh_token text,
refresh_token_expires_at datetime,
realm_id text

Creating an OAuth Access Token

Once you have your user's OAuth access and refresh token string values you can create an access token object to issue requests:

ruby
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)

Access Token Validity and Token Refresh

Each access token is only valid for one hour. The access token and refresh token can be refreshed directly by using OAuth Client:

ruby
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.

Refreshing Tokens

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 | false

And then finally include this concern in the model:

ruby
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 set

Under 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:

ruby
customers.query("Select Id, GivenName From Customer")

Each Entity has different fields you can retrieve & filter on. Refer to Intuit documentation for details.

Pagination

Do not pass pagination parameters in your query - pass them as additional options, using :page and :per_page:

ruby
# 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)

Querying in Batches

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:

ruby
query = nil
Customer.query_in_batches(query, per_page: 1000) do |batch|
  batch.each do |customer|
    # ...
  end
end

The 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.

Retrieving all objects

You may retrieve an array of objects like so:

ruby
customers = service.all

Unlike other query functions which return a Quickbooks::Collection object, the all method returns an array of objects.

Retrieving a single object

You can retrieve a specific Intuit object like so:

ruby
customer = service.fetch_by_id("99")
puts customer.company_name
=> "Acme Enterprises"

Retrieving objects with matching attributes

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.

ruby
customer = service.find_by(:family_name, "Doe")
or
customer = service.find_by("FamilyName", "Doe")

Updating an object

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:

ruby

# 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:

ruby
# 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)

Reference Setters

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:

ruby
invoice = Quickbooks::Model::Invoice.new
invoice.customer_id = 99

This will automatically set a CustomerRef XML packet with a value of 99.

SalesReceipts & Ship Methods

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:

ruby
shipping_reference = Quickbooks::Model::BaseReference.new('FedEx', name: 'FedEx')
receipt.ship_method_ref = shipping_reference

Generating an Invoice

A complete example on generating a basic invoice:

ruby
# 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  234

Notes: line_item.amount must equal the `

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言