From 1b171e414c9d679fdd38a8fda9d61f71c94bd0ec Mon Sep 17 00:00:00 2001 From: guange <8863824@gmail.com> Date: Tue, 1 Mar 2016 17:31:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=8F=9C=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/wechats_controller.rb | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/app/controllers/wechats_controller.rb b/app/controllers/wechats_controller.rb index b05099139..937b6af5f 100644 --- a/app/controllers/wechats_controller.rb +++ b/app/controllers/wechats_controller.rb @@ -157,10 +157,6 @@ class WechatsController < ActionController::Base end def sendBind(request) - openid = request[:FromUserName] - attrs = wechat.user(openid) - UserWechat.delete_all(openid: openid) - uw = UserWechat.create!(attrs) news = (1..1).each_with_object([]) { |n, memo| memo << { title: '绑定登录', content: "您还未绑定确实的用户,请先绑定." } } request.reply.news(news) do |article, n, index| # article is return object url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{login_wechat_url}&response_type=code&scope=snsapi_base&state=#{uw.id}#wechat_redirect" @@ -173,14 +169,21 @@ class WechatsController < ActionController::Base def bind begin - raise "非法操作, 微信ID不存在" unless params[:state] + raise "非法操作, 用户ID不存在" unless params[:state] + raise "非法操作, code不存在" unless params[:code] + openid = get_openid(params[:code]) + raise "无法获取到openid" unless openid + user, last_login_on = User.try_to_login(params[:username], params[:password]) raise "用户名或密码错误,请重新登录" unless user #补全用户信息 - uw = UserWechat.find_by_id(params[:state]) - uw.user_id = user.id - uw.save! + raise "此用户已经绑定了公众号" if user.user_wechat + + UserWechat.create!( + openid: openid, + user: user + ) render :text => {status:0, msg: "绑定成功"}.to_json rescue Exception=>e render :text => {status: -1, msg: e.message}.to_json @@ -193,6 +196,12 @@ class WechatsController < ActionController::Base end private + def get_openid(code) + url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=#{Wechat.config.appid}&secret=#{Wechat.config.secret}&code=#{code}&grant_type=authorization_code" + JSON.parse(URI.parse(url).read)["openid"] + end + + def user_binded?(openid) uw = UserWechat.where(openid: openid).first end