### Ruby: Install Quickbooks-Ruby Gem Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Instructions for adding the quickbooks-ruby gem to your application's Gemfile and installing it using Bundler, or installing it directly via the command line. ```Ruby gem 'quickbooks-ruby' ``` ```Ruby $ bundle ``` ```Ruby $ gem install quickbooks-ruby ``` -------------------------------- ### Downloading PDF Documents from Quickbooks in Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Provides an example of how to download a PDF representation of an Invoice, SalesReceipt, or Payment using the respective Quickbooks service. It shows how to retrieve the raw PDF data and then write it to a local file. ```Ruby service = Quickbooks::Service::Invoice.new # or use the SalesReceipt service # +invoice+ is an instance of Quickbooks::Model::Invoice raw_pdf_data = service.pdf(invoice) # write it to disk File.open("invoice.pdf", "wb") do |file| file.write(raw_pdf_data) end ``` -------------------------------- ### Release Ruby Gem using gem-release Source: https://github.com/ruckus/quickbooks-ruby/blob/master/RELEASE.md Executes the gem release process for the quickbooks-ruby gem. This command requires the `gem-release` gem to be installed and configured. ```Shell gem release quickbooks-ruby.gemspec ``` -------------------------------- ### Ruby: Initialize OAuth2 Client for Intuit Authentication Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Example of setting up an OAuth2 client in a Rails initializer. This client is configured with the necessary Intuit OAuth2 endpoints for authorization and token exchange, using environment variables for client ID and secret. ```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) ``` -------------------------------- ### SQL: Example Schema for OAuth Credentials Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md A suggested SQL database table schema for persisting OAuth access and refresh tokens, their expiration times, and the associated realm ID. This allows applications to store and reuse credentials without requiring users to re-authorize frequently. ```SQL access_token text, access_token_expires_at datetime, refresh_token text, refresh_token_expires_at datetime, realm_id text ``` -------------------------------- ### Retrieving a Single Quickbooks Object by ID Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Illustrates how to fetch a specific Quickbooks object, such as a Customer, by its unique ID using `service.fetch_by_id`. The example also shows how to access an attribute like `company_name`. ```Ruby customer = service.fetch_by_id("99") puts customer.company_name # => "Acme Enterprises" ``` -------------------------------- ### Assign Email Address to Quickbooks Customer (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This example demonstrates how to assign an email address to a Quickbooks `Customer` model. Unlike simple strings, email attributes are top-level `EmailAddress` objects, but the `Customer` model provides a convenient setter method for direct assignment. ```Ruby customer = Quickbooks::Model::Customer.new customer.email_address = "foo@example.com" ``` -------------------------------- ### Retrieve Recent Vendor Changes (Quickbooks Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Illustrates how to use the `Quickbooks::Service::VendorChange` service to get vendors that have changed within the last 5 days, using QuickBooks' Change Data Capture. ```Ruby vendor_service = Quickbooks::Service::VendorChange.new ... vendor_changed = vendor_service.since(Time.now.utc - 5.days) ``` -------------------------------- ### Email Quickbooks Invoice to Alternate Address (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This example shows how to send an invoice to an email address different from the default `bill_email`. By providing the alternate email as a second parameter to the `invoice_service.send` method, the returned invoice model will have its `bill_email` updated to the new address. ```Ruby invoice = invoice_service.fetch_by_id("1") sent_invoice = invoice_service.send(invoice, "name@domain.com") puts send_invoice.bill_email.address #=> name@domain.com ``` -------------------------------- ### Performing Authenticated QuickBooks API Request in Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Illustrates the usage of the `perform_authenticated_request` method from the `QuickbooksOauth` concern. It shows how to execute QuickBooks API calls within a block, ensuring that the access token is automatically refreshed if it expires during the request. An example of querying customers is included. ```Ruby intuit_account = IntuitAccount.find(x) intuit_account.perform_authenticated_request do |access_token| # do something here, like service = Quickbooks::Service::Customer.new service.company_id = "123" # also known as RealmID service.access_token = access_token # the OAuth Access Token you have from above customers = service.query() end ``` -------------------------------- ### Add Bundle Line Item to Quickbooks Invoice (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This example illustrates how to add a bundled item as a line item to an invoice. It involves finding the bundle, setting its description, and then iterating through its `item_group_details` to add individual items within the bundle to the invoice's line items. ```Ruby items = service.find_by(:sku, 'AHH_SWEETS') bundle = items.entries.first # be sure to check if you found the bundle you want # ... 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 ``` -------------------------------- ### Voiding a Quickbooks Invoice by ID and SyncToken (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/HISTORY.md This example illustrates how to void an existing Quickbooks Invoice using its ID and SyncToken. It shows two methods: voiding a fetched invoice object, or constructing a new invoice instance with just the required ID and SyncToken for the void operation. ```Ruby # Both Invoice ID and SyncToken are required - you can either fetch an invoice to void or construct a new # instance and specify those two parameters invoice_service = Quickbooks::Service::Invoice.new(...) # void from a fetched invoice invoice = invoice_service.fetch_by_id(invoice_id) invoice_service.void(invoice) # or construct new instance with the required parameters invoice = Quickbooks::Model::Invoice.new invoice.id = 99 invoice.sync_token = 23 invoice_service.void(invoice) ``` -------------------------------- ### Instantiating QuickBooks Customer Service and Querying Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Shows how to initialize a `Quickbooks::Service::Customer` object, set the `company_id` (RealmID) and `access_token`, and then perform a query to retrieve a list of customers. This is a fundamental step for interacting with QuickBooks entities. ```Ruby service = Quickbooks::Service::Customer.new service.company_id = "123" # also known as RealmID service.access_token = access_token # the OAuth Access Token you have from above # Equivalent to Quickbooks::Service::Customer.new(:company_id => "123", :access_token => access_token) customers = service.query() # Called without args you get the first page of results ``` -------------------------------- ### Expose Local Development with ngrok Source: https://github.com/ruckus/quickbooks-ruby/blob/master/webapp/README.md This command exposes a local development server running on port 4567 to the internet using ngrok, assigning it a specific subdomain ('vinoqbwc') for easy access and webhook reception, which is crucial for OAuth 2.0 callbacks. ```bash ngrok http -subdomain vinoqbwc 4567 ``` -------------------------------- ### Configure Logging for a Specific Quickbooks Service Instance Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to enable logging for a particular service instance, such as `CustomerService`, allowing independent control over logging behavior for different parts of the application. ```Ruby customer_service = Quickbooks::Service::Customer.new customer_service.log = true ``` -------------------------------- ### Create an Annotated Git Tag for Release Source: https://github.com/ruckus/quickbooks-ruby/blob/master/RELEASE.md Creates an annotated Git tag for a specific version (e.g., v0.5.0) with a descriptive message. This tag marks a specific point in the repository's history as a release. ```Shell git tag -a v0.5.0 -m "0.5.0" ``` -------------------------------- ### Paginating Quickbooks Queries Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Illustrates how to apply pagination parameters (`:page`, `:per_page`) to both default and custom Quickbooks queries. This allows retrieving data in manageable chunks, such as the second page with 25 results. ```Ruby # to use the default query customers.query(nil, :page => 2, :per_page => 25) ``` ```Ruby # 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) ``` -------------------------------- ### Configure OAuth2 Client with HTTP Proxy for Debugging (Quickbooks Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Illustrates how to set up an `OAuth2::Client` with proxy connection options, including a proxy URI and SSL verification settings. This is useful for debugging API requests using tools like Charles Proxy. ```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", connection_opts: { proxy: {uri: "http://127.0.0.1:8888"}, ssl: {verify: false} # assuming a self-signed cert is used by your proxy } } oauth2_client = OAuth2::Client.new(ENV['OAUTH_CLIENT_ID'], ENV['OAUTH_CLIENT_SECRET'], oauth_params) ``` -------------------------------- ### Uploading Files as Attachments to Quickbooks in Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to use the `Quickbooks::Service::Upload` service to upload an actual file to Quickbooks. It takes the local file path, MIME type, and optional `Attachable` metadata, returning an `Attachable` model instance upon successful upload. ```Ruby upload_service = Quickbooks::Service::Upload.new # args: # local-path to file # file mime-type # (optional) instance of Quickbooks::Model::Attachable - metadata result = upload_service.upload("tmp/monkey.jpg", "image/jpeg", attachable_metadata) ``` -------------------------------- ### Push Git Tags to Remote Origin Source: https://github.com/ruckus/quickbooks-ruby/blob/master/RELEASE.md Pushes all local Git tags to the remote repository named 'origin'. This makes the release tags available to other collaborators and systems. ```Shell git push origin --tags ``` -------------------------------- ### Querying Quickbooks Customers with Custom SQL-like Query Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to execute a custom SQL-like query against the Quickbooks API using the `query` method. This allows selecting specific fields from an entity, such as `Id` and `GivenName` from `Customer`. ```Ruby customers.query("Select Id, GivenName From Customer") ``` -------------------------------- ### Querying Quickbooks Entities in Batches Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Shows how to use the `query_in_batches` collection method to efficiently retrieve and iterate over multiple pages of records for an entity type. It supports custom queries or default retrieval, with a configurable `per_page` option. ```Ruby query = nil Customer.query_in_batches(query, per_page: 1000) do |batch| batch.each do |customer| # ... end end ``` -------------------------------- ### Retrieving All Quickbooks Objects Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates fetching all objects of a specific entity type using the `service.all` method. Unlike other query functions, this method returns a standard Ruby array of objects, not a `Quickbooks::Collection`. ```Ruby customers = service.all ``` -------------------------------- ### Ruby: Configure Quickbooks-Ruby for Sandbox Mode Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This snippet shows how to configure the quickbooks-ruby gem to operate in sandbox mode. This is essential for development and testing purposes, allowing connection to Quickbooks Online via a development key and the sandbox API endpoint. ```Ruby Quickbooks.sandbox_mode = true ``` -------------------------------- ### Create Invoice with Quickbooks Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This snippet demonstrates how to create a new invoice in Quickbooks using the Ruby gem. It covers setting customer ID, transaction date, a custom document number, and adding a single line item with a sales detail. Note that `line_item.amount` must equal `unit_price * quantity` to avoid Intuit exceptions. ```Ruby 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 << 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 #=> 234 ``` -------------------------------- ### Building Complex Queries for Quickbooks API in Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Explains how to use `Quickbooks::Util::QueryBuilder` to construct complex, escaped queries required by the Intuit API. It demonstrates creating individual clauses for fields, operators, and values, and then combining them into a full SQL-like query string for the service. ```Ruby util = Quickbooks::Util::QueryBuilder.new # the method signature is: clause(field, operator, value) clause1 = util.clause("DisplayName", "LIKE", "%O'Halloran") clause2 = util.clause("CompanyName", "=", "Smith") service.query("SELECT * FROM Customer WHERE #{clause1} AND #{clause2}") ``` -------------------------------- ### Updating a Quickbooks Object (Full Update) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Shows how to perform a full update on an existing Quickbooks object. By fetching the complete object, modifying an attribute, and then calling `service.update`, only the specified attribute is changed, preserving others. ```Ruby # fetch a Customer to change their name customer = service.fetch_by_id("99") customer.company_name = "Neo Pets" service.update(customer) ``` -------------------------------- ### Retrieve Recent Customer Changes (Quickbooks Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Shows how to use the `Quickbooks::Service::CustomerChange` service to fetch customers that have been modified in the last 5 days, leveraging QuickBooks' Change Data Capture. ```Ruby customer_service = Quickbooks::Service::CustomerChange.new ... customer_changed = customer_service.since(Time.now.utc - 5.days) ``` -------------------------------- ### Performing Batch Operations with Quickbooks Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Illustrates how to use the `BatchRequest` service to group multiple operations (e.g., creating a customer and an item) into a single API call. It shows how to add operations to the batch request and process the responses, handling both success and error cases. The maximum batch size is 25 objects. ```Ruby batch_req = Quickbooks::Model::BatchRequest.new customer = Quickbooks::Model::Customer.new # build the customer as needed ... item = Quickbooks::Model::Item.new # build the item as needed ... batch_req.add("bId1", customer, "create") batch_req.add("bId2", item, "create") # Add more items to create/update as needed, up to 25 batch_service = Quickbooks::Service::Batch.new batch_response = batch_service.make_request(batch_req) batch_response.response_items.each do |res| puts res.bId puts res.fault? ? "error" : "success" end ``` -------------------------------- ### Creating Metadata-Only Attachments in Quickbooks Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Shows how to create an `Attachable` model instance to describe a file without actually uploading it. This is useful for associating metadata like file name, note, and content type with an entity (e.g., a Customer) in Quickbooks. ```Ruby meta = Quickbooks::Model::Attachable.new meta.file_name = "monkey.jpg" meta.note = "A note" meta.content_type = "image/jpeg" entity = Quickbooks::Model::BaseReference.new(3, type: 'Customer') meta.attachable_ref = Quickbooks::Model::AttachableRef.new(entity) ``` -------------------------------- ### Ruby: Create OAuth2 Access Token Object Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This snippet demonstrates how to instantiate an `OAuth2::AccessToken` object using previously saved access and refresh token strings. This token object is then ready to be used for making authenticated API requests to Quickbooks Online. ```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) ``` -------------------------------- ### Setting SalesReceipt Ship Method Reference Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Illustrates the specific method for setting the `ShipMethodRef` attribute on a `SalesReceipt` object. Unlike typical ID references, this requires manually creating a `Quickbooks::Model::BaseReference` instance with both the ID and name. ```Ruby shipping_reference = Quickbooks::Model::BaseReference.new('FedEx', name: 'FedEx') receipt.ship_method_ref = shipping_reference ``` -------------------------------- ### QuickBooks Online Entity API Operations Matrix Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This table outlines the supported API operations (Create, Update, Query, Delete, Fetch by ID) for various QuickBooks Online entities within the quickbooks-ruby gem. It indicates whether each operation is available for a given entity, providing a quick reference for integration capabilities. ```APIDOC Entity | Create | Update | Query | Delete | Fetch by ID | Other --- | --- | --- | --- | --- | --- | --- Account | yes | yes | yes | yes | yes | Attachable | no | no | no | no | no | Bill | yes | yes | yes | yes | yes | Bill Payment | yes | yes | yes | yes | yes | Class | yes | yes | yes | yes | yes | Company Info | n/a | n/a | yes | n/a | yes | Credit Memo | yes | yes | yes | yes | no | Customer | yes | yes | yes | yes | yes | Department | yes | yes | yes | yes | yes | Deposit | yes | yes | yes | yes | yes | Employee | yes | yes | yes | yes | yes | Entitlements | no | no | no | no | no | Estimate | yes | yes | yes | yes | yes | Invoice | yes | yes | yes | yes | yes | Item | yes | yes | yes | yes | yes | Journal Entry | yes | yes | yes | yes | yes | Payment | yes | yes | yes | yes | yes | PaymentMethod | yes | yes | yes | yes | yes | Preferences | n/a | no | yes | n/a | yes | Purchase | yes | yes | yes | yes | yes | Purchase Order | yes | yes | yes | yes | yes | Refund Receipt | yes | yes | yes | yes | yes | Sales Receipt | yes | yes | yes | yes | yes | Sales Rep | no | no | no | no | no | Sales Tax | no | no | no | no | no | Sales Term | no | no | no | no | no | Tax Agency | yes | yes | yes | yes | yes | Tax Code | no | no | yes | no | no | Tax Rate | yes | yes | yes | no | no | *Tax Service | yes | yes | no | no | no | Term | yes | yes | yes | yes | yes | Time Activity | yes | yes | yes | yes | yes | Tracking Class | no | no | no | no | no | Vendor | yes | yes | yes | yes | yes | Vendor Credit | yes | yes | yes | yes | yes | ``` -------------------------------- ### Enable Global Logging for Quickbooks Ruby Gem Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Sets the global logging flag for the Quickbooks Ruby gem to `true`, directing all log output to the default target (STDOUT). ```Ruby Quickbooks.log = true ``` -------------------------------- ### Finding Quickbooks Objects by Matching Attributes Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Explains how to use the `find_by(attribute, value)` method to retrieve objects based on a simple WHERE query. The attribute can be provided as a symbol (automatically camelcased) or a string (direct API field name). ```Ruby customer = service.find_by(:family_name, "Doe") ``` ```Ruby customer = service.find_by("FamilyName", "Doe") ``` -------------------------------- ### Configure Faraday HTTP Adapter for Quickbooks Ruby Gem Source: https://github.com/ruckus/quickbooks-ruby/blob/master/HISTORY.md Demonstrates how to configure the `quickbooks-ruby` gem to use a specific Faraday HTTP adapter, such as `Net::HTTP::Persistent`, for thread-safe operations. This setting overrides the default adapter, which is useful for environments requiring persistent connections or specific HTTP client behaviors. ```Ruby Quickbooks.http_adapter = :net_http_persistent # defaults to :net_http ``` -------------------------------- ### Setting Quickbooks Model References Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Explains how to assign references to other Quickbooks entities (e.g., Customer, Item) on a model. The `quickbooks-ruby` gem simplifies this by allowing direct assignment to the `_id` property (e.g., `customer_id`), which automatically generates the correct `Ref` XML structure. ```Ruby invoice = Quickbooks::Model::Invoice.new invoice.customer_id = 99 ``` -------------------------------- ### Instantiating and Setting Physical Addresses in Quickbooks Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to create and assign a `PhysicalAddress` object to a customer's billing address within the Quickbooks Ruby gem. This involves instantiating `Quickbooks::Model::PhysicalAddress` and setting its properties like line1, city, state (country subdivision code), and postal code. ```Ruby address = Quickbooks::Model::PhysicalAddress.new address.line1 = "2200 Mission St." address.line2 = "Suite 201" address.city = "Santa Cruz" address.country_sub_division_code = "CA" # State, in United States address.postal_code = "95060" customer.billing_address = address ``` -------------------------------- ### Ruby on Rails Concern for QuickBooks OAuth Token Management Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Provides a comprehensive Ruby on Rails `ActiveSupport::Concern` module (`QuickbooksOauth`) for handling QuickBooks OAuth token refresh logic. It includes methods for performing authenticated requests with automatic token refresh on `OAuth2::Error` or `Quickbooks::AuthorizationFailure`, refreshing the token, constructing the OAuth client, and creating an access token object. It also defines class methods for client construction. ```Ruby module QuickbooksOauth extend ActiveSupport::Concern #== Instance Methods def perform_authenticated_request(&block) attempts = 0 begin yield oauth_access_token rescue OAuth2::Error, Quickbooks::AuthorizationFailure => ex Rails.logger.info("QuickbooksOauth.perform: #{ex.message}") # to prevent an infinite loop here keep a counter and bail out after N times... attempts += 1 raise "QuickbooksOauth:ExceededAuthAttempts" if attempts >= 3 # check if its an invalid_grant first, but assume it is for now refresh_token! retry end end def refresh_token! t = oauth_access_token refreshed = t.refresh! if refreshed.params['x_refresh_token_expires_in'].to_i > 0 oauth2_refresh_token_expires_at = Time.now + refreshed.params['x_refresh_token_expires_in'].to_i.seconds else oauth2_refresh_token_expires_at = 100.days.from_now end update!( oauth2_access_token: refreshed.token, oauth2_access_token_expires_at: Time.at(refreshed.expires_at), oauth2_refresh_token: refreshed.refresh_token, oauth2_refresh_token_expires_at: oauth2_refresh_token_expires_at ) end def oauth_client self.class.construct_oauth2_client end def oauth_access_token OAuth2::AccessToken.new(oauth_client, oauth2_access_token, refresh_token: oauth2_refresh_token) end def consumer oauth_access_token end module ClassMethods def construct_oauth2_client options = { 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.new(ENV['INTUIT_OAUTH2_CLIENT_ID'], ENV['INTUIT_OAUTH2_CLIENT_SECRET'], options) end end end ``` -------------------------------- ### Create Sales Receipt with Quickbooks Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This code demonstrates how to create a sales receipt in Quickbooks. It covers initializing a sales receipt with customer, date, payment details, and adding a line item. The `auto_doc_number!` method allows Intuit to auto-generate the transaction number, provided 'Custom Transaction Numbers' is unchecked in Quickbooks company settings. ```Ruby #Invoices, SalesReceipts etc can also be defined in a single command salesreceipt = Quickbooks::Model::SalesReceipt.new({ customer_id: 99, txn_date: Date.civil(2013, 11, 20), payment_ref_number: "111", #optional payment reference number/string - e.g. stripe token deposit_to_account_id: 222, #The ID of the Account entity you want the SalesReceipt to be deposited to payment_method_id: 333 #The ID of the PaymentMethod entity you want to be used for this transaction }) salesreceipt.auto_doc_number! #allows Intuit to auto-generate the transaction 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 # Item (Product/Service) ID here end salesreceipt.line_items << line_item service = Quickbooks::Service::SalesReceipt.new({access_token: access_token, company_id: "123" }) created_receipt = service.create(salesreceipt) ``` -------------------------------- ### Updating a Quickbooks Object (Sparse Update) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to perform a sparse update, allowing modification of only specific attributes without un-setting others. This is achieved by creating a new model instance with the ID and desired changes, then passing `:sparse => true` to `service.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) ``` -------------------------------- ### Ruby: Handling Boolean Attributes in Quickbooks-Ruby 0.1.x Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This snippet illustrates a backwards-incompatible change introduced in quickbooks-ruby version 0.1.0 regarding boolean attribute handling. Previously, custom getter methods like this were used; now, `xml_accessor :active?, :from => 'Active'` directly supports `active?`, returning `nil` if not set, or `true`/`false` otherwise. ```Ruby def active? active.to_s == 'true' end ``` -------------------------------- ### Retrieve Recent Invoice Changes (Quickbooks Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to use the `Quickbooks::Service::InvoiceChange` service to retrieve invoices that have changed within the last 5 days. This utilizes QuickBooks' Change Data Capture mechanism. ```Ruby service = Quickbooks::Service::InvoiceChange.new ... changed = service.since(Time.now.utc - 5.days) ``` -------------------------------- ### Retrieve Recent Item Changes (Quickbooks Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to use the `Quickbooks::Service::ItemChange` service to retrieve items that have been modified in the last 5 days, utilizing QuickBooks' Change Data Capture. ```Ruby item_service = Quickbooks::Service::ItemChange.new ... item_changed = item_service.since(Time.now.utc - 5.days) ``` -------------------------------- ### Ruby: Redirect for Intuit OAuth2 Authorization Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md A Rails controller action demonstrating how to initiate the Intuit OAuth2 authentication flow. It constructs the authorization URL with the redirect URI, response type, state, and scope, then redirects the user to Intuit's authorization page. ```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 ``` -------------------------------- ### IntuitAccount Model Database Schema Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Defines the database schema for the `IntuitAccount` model, including fields for storing OAuth2 access tokens, refresh tokens, their expiration times, and a boolean flag for tracking purchase order quantity. These fields are crucial for persisting QuickBooks OAuth credentials. ```SQL Schema 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 ``` -------------------------------- ### Ruby: Handle Intuit OAuth2 Callback and Token Exchange Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This Rails controller action handles the callback from Intuit after user authorization. It checks for the presence of a state parameter, exchanges the authorization code for access and refresh tokens, and suggests saving these tokens for future use. ```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 ``` -------------------------------- ### Creating Description-Only Line Items for Quickbooks Invoices (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/HISTORY.md This snippet demonstrates how to create a line item for a Quickbooks Invoice that only contains a description, without a specific product or service. This is useful for adding custom, descriptive charges or notes to an invoice. ```Ruby line_item = Quickbooks::Model::InvoiceLineItem.new line_item.description = "Plush Baby Doll" line_item.description_only! invoice.line_items << line_item ``` -------------------------------- ### Refreshing an OAuth Access Token in Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates the basic method call to refresh an existing OAuth access token. The new token object must be assigned to a variable and persisted to avoid losing credentials, which would void the current credentials. ```Ruby new_access_token_object = access_token.refresh! ``` -------------------------------- ### Customize Quickbooks Ruby Logger and XML Pretty Printing Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Shows how to assign a custom logger (e.g., Rails.logger) to the Quickbooks gem and disable pretty-printing of logged XML, providing more control over log output format and destination. ```Ruby Quickbooks.logger = Rails.logger Quickbooks.log = true # Pretty-printing logged xml is true by default Quickbooks.log_xml_pretty_print = false ``` -------------------------------- ### Using Change Data Capture (CDC) in Quickbooks Ruby Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Explains how to utilize the Quickbooks Change Data Capture API to retrieve entities that have recently changed or been deleted, up to 30 days prior. It demonstrates querying for changes across specified entity types and parsing the XML response into a hash of Quickbooks models, identifying deleted items. ```Ruby service = Quickbooks::Service::ChangeDataCapture.new ... # define the list of entities to query entities = ["Invoice", "Bill", "Payment"] #etc changed = service.since(entities, Time.now.utc - 5.days) ... # parse the XML to a list of Quickbooks::Models changed_as_hash = changed.all_types ``` -------------------------------- ### Correcting Reference Assignment in Quickbooks Ruby Models Source: https://github.com/ruckus/quickbooks-ruby/blob/master/HISTORY.md This snippet illustrates a backwards-incompatible change introduced in version 0.0.3 regarding how reference types (e.g., parent_ref) are set on Quickbooks models. Direct assignment to `_ref` properties is no longer supported; instead, use the `_id` setter, which automatically creates the appropriate `BaseReference` instance. ```Ruby account = Quickbooks::Model::Account.new account.parent_ref = 2 ``` ```Ruby account = Quickbooks::Model::Account.new account.parent_id = 2 ``` -------------------------------- ### Including QuickbooksOauth Concern in Rails Model Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Demonstrates how to include the `QuickbooksOauth` concern into an `IntuitAccount` ActiveRecord model. This integration allows the model instances to utilize the token management functionalities provided by the concern. ```Ruby class IntuitAccount < ActiveRecord::Base include QuickbooksOauth end ``` -------------------------------- ### Delete Quickbooks Object (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This snippet shows how to delete an object using the `Service#delete` method. This method takes the object to be deleted as an argument and returns a boolean value indicating whether the deletion operation was successful. ```Ruby service.delete(customer) #=> returns boolean ``` -------------------------------- ### Email Quickbooks Invoice (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md This snippet demonstrates how to send an invoice via email using the Quickbooks API's `send` feature. By default, the email is sent to the `bill_email` associated with the invoice. The method returns an updated invoice model with `email_status` and `delivery_info`. ```Ruby invoice = invoice_service.fetch_by_id("1") sent_invoice = invoice_service.send(invoice) puts sent_invoice.email_status #=> EmailSent puts sent_invoice.delivery_info.delivery_type #=> Email puts sent_invoice.delivery_info.delivery_time #=> Wed, 25 Feb 2015 18:56:04 UTC +00:00 ``` -------------------------------- ### Assign Telephone Number to Quickbooks Customer (Ruby) Source: https://github.com/ruckus/quickbooks-ruby/blob/master/README.md Similar to email addresses, telephone numbers in Quickbooks are represented as top-level objects, specifically `TelephoneNumber`. This snippet shows how to create a `TelephoneNumber` object and assign it to a customer's mobile phone attribute. ```Ruby phone1 = Quickbooks::Model::TelephoneNumber.new phone1.free_form_number = "97335530394" customer.mobile_phone = phone1 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.