module WechatKit

Constants

TicketUrl
TokenUrl
VERSION

Attributes

access_token[R]
access_token_expired_at[R]
app_id[R]
app_secret[R]
jsapi_ticket[R]
jsapi_ticket_expired_at[R]

Public Instance Methods

get_access_token() click to toggle source
# File lib/wechat_kit.rb, line 42
def get_access_token
  if @access_token_expired_at and @access_token_expired_at > Time.now
    @access_token
  else
    url = "#{TokenUrl}?grant_type=client_credential&appid=#{@app_id}&secret=#{@app_secret}"
    response = response_from_url(url)
    @access_token = response["access_token"]
    @access_token_expired_at = Time.now + 7000
    @access_token
  end
end
get_js_api_ticket() click to toggle source
# File lib/wechat_kit.rb, line 54
def get_js_api_ticket
  if @jsapi_ticket_expired_at and @jsapi_ticket_expired_at > Time.now
    @jsapi_ticket
  else
    url = "#{TicketUrl}?type=jsapi&access_token=#{get_access_token}"
    response = response_from_url(url)
    @jsapi_ticket = response["ticket"]
    @jsapi_ticket_expired_at = Time.now + 7000
  end
  @jsapi_ticket
end
response_from_url(url) click to toggle source
# File lib/wechat_kit.rb, line 66
def response_from_url(url)
  response = {}
  Timeout::timeout(3) do
    open(url) {|f|
      response = JSON.parse f.read
    }  rescue {}
  end
  response
end
setup(app_id, app_secret) click to toggle source
# File lib/wechat_kit.rb, line 17
def setup(app_id, app_secret)
  @app_id = app_id
  @app_secret = app_secret
end
signature(url, jsApiList=[], debug=false) click to toggle source
# File lib/wechat_kit.rb, line 22
def signature(url, jsApiList=[], debug=false)
  jsapi_ticket =  get_js_api_ticket
  timestamp = Time.now.to_i.to_s
  nonce = SecureRandom.hex 16
  # 这里参数的顺序要按照 key 值 ASCII 码升序排序
  string = "jsapi_ticket=#{jsapi_ticket}&noncestr=#{nonce}&timestamp=#{timestamp}&url=#{url}"
  signature = Digest::SHA1.hexdigest(string)

  sign_package = {
    "debug"     => debug,
    "appId"     => @app_id,
    "nonceStr"  => nonce,
    "timestamp" => timestamp,
    "url"       => url,
    "signature" => signature,
    "jsApiList" => jsApiList
   }
  return sign_package.to_json
end