Commit e1e5da83 by lanrion

can get access_token for weixin

parent 2c6a522c
require "rest-client"
require "weixin_authorize/version" require "weixin_authorize/version"
require "weixin_authorize/client" require "weixin_authorize/client"
......
# encoding: utf-8
module WeixinAuthorize module WeixinAuthorize
class Client class Client
attr_accessor :app_id, :app_secret attr_accessor :app_id, :app_secret, :expired_at # Time.now + expires_in
attr_accessor :access_token attr_accessor :access_token
def initialize(&block) def initialize(app_id="", app_secret="", expired_at=nil)
instance_eval(&block) @app_id = app_id
@app_secret = app_secret
@expired_at = (expired_at.to_i || Time.now.to_i)
yield self if block_given?
end
# return token
def get_access_token
# 如果当前token过期时间小于现在的时间,则重新获取一次
if @expired_at < Time.now.to_i
authenticate
end
@access_token
end
# authenticate access_token
def authenticate
hash_infos = JSON.parse(RestClient.get(authenticate_url))
self.access_token = hash_infos["access_token"]
self.expired_at = Time.now.to_i + hash_infos["expires_in"]
end end
private
def authenticate_url
"#{endpoint}/token?grant_type=client_credential&appid=#{app_id}&secret=#{app_secret}"
end
def endpoint
"https://api.weixin.qq.com/cgi-bin"
end
end end
end end
...@@ -2,8 +2,20 @@ require "spec_helper" ...@@ -2,8 +2,20 @@ require "spec_helper"
describe WeixinAuthorize::Client do describe WeixinAuthorize::Client do
describe "#get access_token" do describe "#get access_token" do
it "returns a access_token value" do it "return a access_token nil value before authenticate" do
expect($client.app_id).not_to eq("ss") expect($client.access_token).to eq(nil)
end
it "return access_token after authenticate" do
$client.authenticate
expect($client.access_token).not_to eq(nil)
end
it "return the same access_token in the same thing twice" do
access_token_1 = $client.get_access_token
sleep 5
access_token_2 = $client.get_access_token
expect(access_token_1).to eq(access_token_2)
end end
end end
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