Sha256: 60f1a94b33218364ee9303253a35b18838d24d94158c378ca7e5a15158d60025

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

module SolidusMelhorEnvio
  class Api

    attr_reader :account
    def initialize account
      @account = account
      verify_token
    end

    private
    def refresh_token
      headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "User-Agent": "Aplicação #{@account.user_agent}"
      }
      request_body = {
        "grant_type": "refresh_token",
        "refresh_token": @account.refresh_token,
        "client_id": @account.client_id,
        "client_secret": @account.client_secret
      }
      request = ::Typhoeus.post("#{@account.api_base_url}/oauth/token", headers: headers, body: JSON.dump(request_body))
      body = JSON.parse(request.body)
      response_has_error? body
      expire_datetime = request.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 response_has_error? json
      raise "ERROR: #{json}" if json.include? "error"
    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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
solidus_melhor_envio-1.0.4 app/models/solidus_melhor_envio/api.rb