Sha256: 889334647ba228d760f6aadfae8e0d7fc95a9b0efe3a72ceaa7dee5b87862158
Contents?: true
Size: 1.58 KB
Versions: 8
Compression:
Stored size: 1.58 KB
Contents
module SolidusBling class Api attr_reader :account, :headers def initialize account @account = account 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) response_has_error? 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 = SolidusBling::Account.find_by(app_name: app_name) raise 'Conta de aplicativo inexistente' if account.nil? account end end end
Version data entries
8 entries across 8 versions & 1 rubygems