class Weapps::CodeSessionsController < Weapps::BaseController def create logged = false return render_error('code不能为空') if params[:code].blank? result = Wechat::Weapp.jscode2session(params[:code]) set_session_openid(result['openid']) set_weapp_session_key(result['session_key']) # weapp session_key写入缓存 后续解密需要 # 已授权,绑定过账号 open_user = OpenUsers::Wechat.find_by(uid: result['unionid']) if open_user.present? && open_user.user set_session_unionid(result['unionid']) successful_authentication(open_user.user) logged = true else # 新用户 user_info = Wechat::Weapp.decrypt(result['session_key'], params[:encrypted_data], params[:iv]) set_session_unionid(user_info['unionId']) end render_ok(openid: result['openid'], logged: logged) end end