Sha256: 3c05a53ccd2c0f013e109ffa291aeb89016f916c9c1a91f8d2e00c407ef946eb
Contents?: true
Size: 1.54 KB
Versions: 2
Compression:
Stored size: 1.54 KB
Contents
module Bling class Api def initialize app_name = SolidusBling.config.app_name @account = find_account(app_name) verify_token @headers = { "Content-Type": "application/json", "Authorization": "Bearer #{@account.access_token}" } end def refresh_token basic_encoded = Base64.strict_encode64("#{@account.client_id}:#{@account.client_secret}") headers = { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Basic #{basic_encoded}" } body = "grant_type=refresh_token&refresh_token=#{@account.refresh_token}" res = ::Typhoeus.post("#{@account.api_base_url}/oauth/token", headers: headers, body: body) body = JSON.parse(res.body) expire_datetime = res.headers["date"].to_datetime.utc + body["expires_in"].seconds @account.update( access_token: body["access_token"], refresh_token: body["refresh_token"], token_expires_in: expire_datetime ) end def need_refresh_token? return true if @account.token_expires_in.nil? DateTime.now.utc > (@account.token_expires_in - 2.hours) end def verify_token refresh_token if need_refresh_token? end def response_has_error? json if json.include? "error" error = json["error"] raise "ERROR: #{json}" end end private def find_account app_name account = ErpAccount.find_by(app_name: app_name) raise 'Conta de aplicativo inexistente' if account.nil? account end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
solidus_bling-1.0.1 | app/models/bling/api.rb |
solidus_bling-1.0.0 | app/models/bling/api.rb |