Commit 09c06ab0 by mingyuan

get tokens

parent 4a7f41b5
......@@ -12,3 +12,4 @@ gem 'viter', github: 'qinmingyuan/viter'
gem 'default_form', github: 'qinmingyuan/default_form'
gem 'pry'
gem 'amazing_print'
......@@ -106,6 +106,7 @@ GEM
zeitwerk (~> 2.3)
acts_as_list (1.0.4)
activerecord (>= 4.2)
amazing_print (1.3.0)
builder (3.2.4)
closure_tree (7.3.0)
activerecord (>= 4.2.10)
......@@ -231,6 +232,7 @@ PLATFORMS
x86_64-darwin-20
DEPENDENCIES
amazing_print
default_form!
pg
pry
......
module Dingtalk::Api
module Base
class Base
BASE = 'https://oapi.dingtalk.com/'
attr_reader :app, :client
def initialize(app)
@app = app
@client = HttpClient.new
@client = Dingtalk::HttpClient.new
end
def token
@client.get 'gettoken', params: { appkey: app.app_key, appsecret: app.app_secret }, base: BASE
end
def get(path, params: {}, headers: {}, base: nil, as: nil)
with_access_token(params) do |with_token_params|
@client.get path, headers: headers, params: with_token_params, base: base, as: as
end
end
def post(path, params: {}, headers: {}, base: nil, **payload)
with_access_token(params) do |with_token_params|
@client.post path, payload.to_json, headers: headers, params: with_token_params, base: base
end
end
def post_file(path, file, params: {}, headers: {}, base: nil)
with_access_token(params) do |with_token_params|
@client.post_file path, file, headers: headers, params: with_token_params, base: base
end
end
protected
def with_access_token(params = {}, tries = 2)
app.refresh_access_token unless app.access_token_valid?
yield params.merge!(access_token: app.access_token)
rescue Wechat::AccessTokenExpiredError
app.refresh_access_token
retry unless (tries -= 1).zero?
end
end
......
......@@ -6,7 +6,7 @@ module Dingtalk
attr_reader :http
def initialize
@http = HTTPX.with(**RailsWechat.config.httpx)
@http = HTTPX.with(**RailsDingtalk.config.httpx)
end
def get(path, headers: {}, params: {}, base: nil, **options)
......
......@@ -17,5 +17,25 @@ module Dingtalk
@api = Api::Base.new(self)
end
def refresh_access_token
r = api.token
if r['access_token']
store_access_token(r)
else
logger.debug " ==========> #{r['errmsg']}"
end
end
def store_access_token(token_hash)
self.access_token = token_hash['access_token']
self.access_token_expires_at = Time.current + token_hash['expires_in'].to_i
self.save
end
def access_token_valid?
return false unless access_token_expires_at.acts_like?(:time)
access_token_expires_at > Time.current
end
end
end
require 'rails_dingtalk/engine'
module RailsDingtalk
end
require 'rails_dingtalk/config'
module RailsDingtalk
include ActiveSupport::Configurable
configure do |config|
config.httpx = {
ssl: {
verify_mode: OpenSSL::SSL::VERIFY_NONE
}
}
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment