diff --git a/app/api/mobile/apis/new_comment.rb b/app/api/mobile/apis/new_comment.rb index 0dacef8f5..10ec47a23 100644 --- a/app/api/mobile/apis/new_comment.rb +++ b/app/api/mobile/apis/new_comment.rb @@ -42,12 +42,29 @@ module Mobile login = openid[0..10]+openid[openid_length-3..openid_length-1]+Time.now.to_i.to_s access_token = session[:access_token] + refresh_token = session[:refresh_token] Rails.logger.info "session!!!!!!!!!" Rails.logger.info session - if access_token - userinfo = Wechat.api.web_userinfo(access_token,openid) + if access_token && refresh_token + refreshinfo = Wechat.api.web_refresh_access_token(refresh_token) + + access_token = refreshinfo["access_token"] + refresh_token = refreshinfo["refresh_token"] + session[:access_token] = access_token + session[:refresh_token] = refresh_token + + require "open-uri" + #如果有GET请求参数直接写在URI地址中 + uri = 'https://api.weixin.qq.com/sns/userinfo?access_token='+access_token+'&openid='+openid+'&lang=zh_CN' + html_response = nil + open(uri) do |http| + userinfo = http.read + end + + # userinfo = Wechat.api.web_userinfo(access_token,openid) + Rails.logger.info userinfo name = userinfo["nickname"] else diff --git a/app/controllers/wechats_controller.rb b/app/controllers/wechats_controller.rb index 2dab17703..cd2846a85 100644 --- a/app/controllers/wechats_controller.rb +++ b/app/controllers/wechats_controller.rb @@ -442,6 +442,18 @@ class WechatsController < ActionController::Base def get_openid_from_code(code) return 'oCnvgvz8R7QheXE-R9Kkr39j8Ndg' if code =='only-for-test' openid = session[:wechat_openid] + + info = wechat.web_access_token(code) + openid =info["openid"] + access_token =info["access_token"] + if access_token + session[:access_token] = access_token + end + refresh_token = info["refresh_token"] + if refresh_token + session[:refresh_token] = refresh_token + end + unless openid if code #不能联系调两次web_access_token 否则会提示请在微信客户端打开次链接 @@ -451,6 +463,10 @@ class WechatsController < ActionController::Base if access_token session[:access_token] = access_token end + refresh_token = info["refresh_token"] + if refresh_token + session[:refresh_token] = refresh_token + end end end diff --git a/lib/wechat/lib/wechat/api.rb b/lib/wechat/lib/wechat/api.rb index db1248ab0..76890a833 100644 --- a/lib/wechat/lib/wechat/api.rb +++ b/lib/wechat/lib/wechat/api.rb @@ -122,6 +122,15 @@ module Wechat get 'access_token', params: params, base: OAUTH2_BASE end + def web_refresh_access_token(refresh_token) + params = { + appid: access_token.appid, + grant_type: 'refresh_token', + refresh_token: refresh_token + } + get 'refresh_token', params: params, base: OAUTH2_BASE + end + def web_userinfo(access_token,openid) params = { access_token: access_token,