Skip to content

Instantly share code, notes, and snippets.

@minimul
Last active June 4, 2020 13:39
Show Gist options
  • Save minimul/a2c270ae5c5008326aae16c03a3b810b to your computer and use it in GitHub Desktop.
Save minimul/a2c270ae5c5008326aae16c03a3b810b to your computer and use it in GitHub Desktop.
QBO OAuth2 Helper Methods
module Qbo
module OAuth2
# gist id => a2c270ae5c5008326aae16c03a3b810b
def self.renew!(q)
cl = client
cl.refresh_token = q.refresh_token
if resp = cl.access_token!
attrs = { access_token: resp.access_token, refresh_token: resp.refresh_token }.merge(expires_in)
q.update!(attrs)
q.reload
else
msg = "FAILED_OAUTH2_RENEW_TOKEN: line: #{__LINE__} qbo_account: #{q.id} error_message: #{resp}"
Rails.logger.warn msg
end
rescue => e
msg = "FAILED_OAUTH2_RENEW_TOKEN: line: #{__LINE__} qbo_account: #{q.id} error_message: #{e.message}"
Rails.logger.warn msg
end
def self.revoke!(refresh_token)
revoke_endpoint = "https://developer.api.intuit.com/v2/oauth2/tokens/revoke"
http_client = Rack::OAuth2.http_client
http_client.post(revoke_endpoint, { "token" => refresh_token }, basic_auth_header)
end
def self.migrate!(qbo_account)
QboApi.request_id = false
api = Qbo.init(qbo_account)
prefix = Rails.env.production? ? 'developer' : 'developer-sandbox'
migration_uri = "https://#{prefix}.api.intuit.com/v2/oauth2/tokens/migrate"
params = { scope: 'com.intuit.quickbooks.accounting', redirect_uri: redirect_url,
client_id: client_id, client_secret: client_secret }
if resp = api.request(:post, path: migration_uri, payload: params)
attrs = { access_token: resp["access_token"], refresh_token: resp["refresh_token"] }.merge(expires_in)
qbo_account.update!(attrs)
end
ensure
QboApi.request_id = true
end
def self.client
Rack::OAuth2::Client.new(
identifier: client_id,
secret: client_secret,
redirect_uri: redirect_url,
authorization_endpoint: "https://appcenter.intuit.com/connect/oauth2",
token_endpoint: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"
)
end
def self.authorize_url(state:)
client.authorization_uri(
client_id: client_id,
scope: 'com.intuit.quickbooks.accounting',
redirect_uri: redirect_url,
response_type: 'code',
state: state
)
end
def self.redirect_url=(value)
# redirect_url is set in an initializer file
# e.g. Qbo::OAuth2.redirect_url = Rails.env.production? ? 'https://prod.com/oauth2-redirect' : 'http://dev.test/oauth2-redirect'
@redirect_url = value
end
def self.redirect_url
@redirect_url ||= false
end
def self.expires_in
{
access_token_expires_in: 1.hour.from_now,
refresh_token_expires_in: 101.days.from_now
}
end
def self.client_id
Rails.application.secrets.qbo_api_client_id
end
def self.client_secret
Rails.application.secrets.qbo_api_client_secret
end
def self.basic_auth_header
cred = ["#{client_id}:#{client_secret}"].pack('m').tr("\n", '')
{ 'Authorization' => "Basic #{cred}" }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment