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