quickbooks-ruby

repository·master·Indexed 18 days ago

https://github.com/ruckus/quickbooks-ruby

A Ruby integration library for the Intuit Data Services v3 REST API. It enables developers to interact with QuickBooks Online data, including managing entities like Customers and Invoices, handling OAuth 2.0 authentication, performing batch operations, and utilizing Change Data Capture (CDC) to track entity changes. The library supports querying via QueryBuilder, sparse and full updates, and access to the QuickBooks Reports API.

Tokens
14.3K
Snippets
57
Records
68
Agent score
54%

What's inside quickbooks-ruby

  1. Set object references using _id setters

    master

    In the Quickbooks API, many properties are references (e.g., CustomerRef). In quickbooks-ruby, you can assign these references easily by using the setter for the _id property of the attribute. For example, setting customer_id on an Invoice will automatically create the appropriate CustomerRef XML packet.

    invoice = Quickbooks::Model::Invoice.new
    invoice.customer_id = 99
  2. Debug using an HTTP proxy

    master

    For advanced debugging, it is recommended to use an HTTP proxy like Charles Proxy. To do this, pass connection_opts containing the proxy URI and SSL verification settings when initializing your OAuth2::Client.

    # Example configuration for using a proxy with OAuth2::Client
    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",
      connection_opts: {
        proxy: {uri: "http://127.0.0.1:8888"},
        ssl: {verify: false}  # Required if using a proxy with a self-signed cert
      }
    }
    
    oauth2_client = OAuth2::Client.new(ENV['OAUTH_CLIENT_ID'], ENV['OAUTH_CLIENT_SECRET'], oauth_params)
  3. Install quickbooks-ruby

    master

    To install the gem, add it to your Gemfile and run bundle, or install it directly via the command line.

    Requirements:

    • Ruby version: >= 2.6.0 (Version 2.x of the gem no longer supports Ruby 2.5 or below).
    • Ruby 1.9.x is not supported.
    # Add to Gemfile
    gem 'quickbooks-ruby'
    
    # Then run
    $ bundle

    Or via CLI:

    $ gem install quickbooks-ruby
  4. Implement OAuth 2.0 for QuickBooks Online

    master
    The sample application demonstrates how to implement the OAuth 2.0 flow required to access QuickBooks Online data. This includes handling the initial authentication and refreshing access tokens. For detailed implementation guidance on refreshing tokens, refer to the official Intuit documentation.
  5. Expose local development via ngrok

    master

    To test the QuickBooks Online OAuth 2.0 flow locally, you may need to expose your local server to the internet so Intuit can send webhooks or redirect callbacks to your machine. Use ngrok to create a tunnel to your local port (e.g., 4567).

    ngrok http -subdomain vinoqbwc 4567
  6. Initiate OAuth 2.0 Authentication Flow with Intuit

    master

    To start the authentication process, you need to configure an OAuth2::Client with Intuit's endpoints and redirect the user to the authorization URL.

    Endpoints:

    • 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
    # 1. Setup Client
    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)
    
    # 2. Generate Grant URL (in your controller)
    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
    
    # 3. Handle Callback
    def oauth_callback
      if params[:state].present? && resp = oauth2_client.auth_code.get_token(params[:code], redirect_uri: quickbooks_oauth_callback_url)
        # Use resp.token, resp.refresh_token, and params[:realmId] to persist credentials
      end
    end
  7. Configure logging for Quickbooks

    master

    You can enable global logging or configure logging for specific service instances. By default, logs are sent to STDOUT. You can redirect logs to a different target, such as Rails.logger.

    # Enable global logging
    Quickbooks.log = true
    
    # Redirect logs to Rails
    Quickbooks.logger = Rails.logger
    Quickbooks.log = true
    
    # Disable pretty-printing of XML
    Quickbooks.log_xml_pretty_print = false
    
    # Enable logging for a specific service instance only
    customer_service = Quickbooks::Service::Customer.new
    customer_service.log = true
  8. Configure Sandbox Mode and Minorversion

    master

    By default, the gem runs in production mode. To develop or test using a development key and Sandbox Companies, enable sandbox_mode.

    You can also specify a specific QBO API minorversion. As of July 2025, 75 is the minimum supported version.

    # Enable sandbox mode for development
    Quickbooks.sandbox_mode = true
    
    # Specify a specific API minor version
    Quickbooks.minorversion = 75
  9. Initialize a Quickbooks Service

    master

    To use a service class inheriting from BaseService, initialize it with an attributes hash. The service automatically determines the base URI based on whether Quickbooks.sandbox_mode is enabled. You must provide a company_id (also referred to as realm_id) to construct valid resource URLs.

    Note that company_id and realm_id are synonymous in this library.

    # Example initialization
    service = MyQuickbooksService.new(
      company_id: 'your_realm_id',
      oauth: oauth_access_token
    )
  10. Generate a SalesReceipt

    master

    SalesReceipts can be defined using a hash in the constructor. You can use auto_doc_number! to let Intuit generate the transaction number, provided that 'Custom Transaction Numbers' is unchecked in the Quickbooks Company Settings.

    salesreceipt = Quickbooks::Model::SalesReceipt.new({
      customer_id: 99,
      txn_date: Date.civil(2013, 11, 20),
      payment_ref_number: "111",
      deposit_to_account_id: 222,
      payment_method_id: 333
    })
    salesreceipt.auto_doc_number!
    
    line_item = Quickbooks::Model::Line.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
    end
    
    salesreceipt.line_items << line_item
    
    service = Quickbooks::Service::SalesReceipt.new({access_token: access_token, company_id: "123" })
    created_receipt = service.create(salesreceipt)
  11. Generate an Invoice containing a Bundle

    master

    When adding a bundle to an invoice, use the group_line_detail! block. You must provide the group_item_ref using a BaseReference and iterate through the bundle's item_group_details.line_items to populate the nested line items.

    items = service.find_by(:sku, 'AHH_SWEETS')
    bundle = items.entries.first
    
    line_item = Quickbooks::Model::InvoiceLineItem.new
      line_item.description = bundle.description
    
      line_item.group_line_detail! do |detail|
        detail.id = bundle.id
        detail.group_item_ref = Quickbooks::Model::BaseReference.new(bundle.name, value: bundle.id)
        detail.quantity = 1
    
        bundle.item_group_details.line_items.each do |l|
          g_line_item = Quickbooks::Model::InvoiceLineItem.new
          g_line_item.amount = 50
    
          g_line_item.sales_item! do |gl|
            gl.item_id    = l.id
            gl.quantity   = 1
            gl.unit_price = 50
          end
    
          detail.line_items << g_line_item
        end
      end
    
      invoice.line_items << line_item
  12. Generate a basic Invoice

    master

    To create an invoice, instantiate Quickbooks::Model::Invoice, add InvoiceLineItem objects, and use the corresponding service to create it.

    Important: The line_item.amount must exactly equal unit_price * quantity, otherwise Intuit will raise an exception.

    # 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"
    
    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
    end
    
    invoice.line_items << line_item
    
    service = Quickbooks::Service::Invoice.new
    service.company_id = "123"
    service.access_token = access_token
    created_invoice = service.create(invoice)
    puts created_invoice.id