You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
educoder/app/controllers/weapps/code_sessions_controller.rb

39 lines
1.3 KiB

5 years ago
class Weapps::CodeSessionsController < Weapps::BaseController
def create
return render_error('code不能为空') if params[:code].blank?
reset_session
logged = false
5 years ago
result = Wechat::Weapp.jscode2session(params[:code])
5 years ago
# 能根据 code 拿到 unionid
open_user = OpenUsers::Wechat.find_by(uid: result['unionid'])
5 years ago
if open_user.present? && open_user.user
successful_authentication(open_user.user)
5 years ago
set_session_unionid(result['unionid'])
logged = true
5 years ago
else
5 years ago
# 根据 code没拿到 unionid
5 years ago
user_info = Wechat::Weapp.decrypt(result['session_key'], params[:encrypted_data], params[:iv])
5 years ago
# 老用户,已绑定
open_user = OpenUsers::Wechat.find_by(uid: user_info['unionId'])
5 years ago
if open_user.present? && open_user.user
successful_authentication(open_user.user)
logged = true
end
5 years ago
set_session_unionid(user_info['unionId'])
user_info['nickname'] = user_info['nickName']
session[:wechat_user_extra] = user_info
5 years ago
end
5 years ago
set_session_openid(result['openid'])
set_weapp_session_key(result['session_key']) # weapp session_key写入缓存 后续解密需要
render_ok(openid: result['openid'], logged: logged) unless logged
5 years ago
rescue Wechat::Error => ex
render_error(ex.message)
5 years ago
end
end