微信小程序登陆

官方登陆流程:

小程序前端: wx.login获取登陆code   wx.getUserInfo获取用户信息   将信息传入到后端服务器

 wxLogin: function(_fun) {
    var that = this;
    //微信登陆
    wx.login({
      success: function(res) {
        that.setData({
          code: res.code
        });
        if (typeof _fun == 'function') _fun()

      }
    });
  },
  wxGetUserInfo: function(_fun) {
    var that = this;
    //获取用户信息
    wx.getUserInfo({
      success: function (res) {
        that.setData({
          userInfo: res
        });
        if (typeof _fun == 'function') _fun()
      }
    })
  },
  //服务器登陆
  serviceLogin: function() {
    var that = this;
    var data = {
      "code": that.data.code,
      "wxUserInfo": that.data.userInfo
    };
    var success = function (res) {
      wx.setStorageSync('userId', res.id);
      wx.setStorageSync('accessToken', res.accessToken);
      wx.switchTab({
        url: app.common.indexUrl,
      })
    }
    myajax.post("login", data, success);
  },

  服务器后端处理:根据code按照api拼装url请求微信服务接口 获得返回数据的openid (微信的唯一标识) ,我的业务处理是用户不存在,根据userinfo(微信头像 昵称信息)自动注册。

 public GlobalResult<CommonUserBo> customerLogin(CustomerLoginVo customerLoginVo) {
        WxUserInfo wxUserInfo = customerLoginVo.getWxUserInfo();
        if (null == wxUserInfo) {
            throw new LookException(300,"登录失败");
        }
        // 微信个人信息
        UserInfo userInfo = wxUserInfo.getUserInfo();
        // 构建请求url,获取openid
        String requestUrl = String.format(wechatConfig.getWebAccessTokenhttps(), wechatConfig.getAppId(), wechatConfig.getSecret(), customerLoginVo.getCode());
        logger.info("》》》请求url为:" + requestUrl);
        String response = HttpClientUtil.doGet(requestUrl);
        JSONObject responseJson=JSONObject.parseObject(response);
        if (null == responseJson || (responseJson.getString("openid").equals(""))) {
            throw new LookException("登录失败");
        }
        //回调信息验证
        String sha1 = EncryptionUtil.getSha1(wxUserInfo.getRawData() + responseJson.getString("session_key"));
        if (!wxUserInfo.getSignature().equals(sha1)) {
            throw new LookException("登录失败");
        }
        String openId = responseJson.getString("openid");
        logger.info("openId==>"+openId);
        UserCustomer userCustomer = customerMapper.selectByOpenId(openId);
        if (userCustomer ==null){
            //首次登录自动注册
            String token= UUID.randomUUID().toString();
            UserCustomer customer = new UserCustomer();
            customer.setWechatId(openId);
            customer.setNickName(userInfo.getNickName());
            customer.setPhoto(userInfo.getAvatarUrl());
            customer.setSex(userInfo.getGender());
            customer.setAccessToken(token);
            String maxId=customerMapper.getMaxId();
            customer.setUserNo(IDUtil.getID(maxId));
            int i= customerMapper.insertCustomer(customer);
            CommonUserBo commonUserBo=new CommonUserBo();
            commonUserBo.setId(customer.getId());
            commonUserBo.setUserName(customer.getUserName());
            commonUserBo.setUserNo(customer.getUserNo());
            commonUserBo.setUserType((short)2);
            commonUserBo.setAccessToken(token);
            redisTemplate.opsForValue().set("LOGIN_USER:"+token, JSONObject.toJSONString(commonUserBo));
            return new GlobalResult<CommonUserBo>().success("登录成功",commonUserBo);
        }else {
            if(userCustomer.getAccessToken()!=null){
                redisTemplate.delete("LOGIN_USER:"+userCustomer.getAccessToken());
            }
            String token= UUID.randomUUID().toString();
            UserCustomer userCustomer1=new UserCustomer();
            userCustomer1.setId(userCustomer.getId());
            userCustomer1.setAccessToken(token);
            userCustomer1.setLastLoginTime(new Date());
            customerMapper.updateByPrimaryKeySelective(userCustomer1);
            CommonUserBo commonUserBo=new CommonUserBo();
            commonUserBo.setId(userCustomer.getId());
            commonUserBo.setUserName(userCustomer.getUserName());
            commonUserBo.setUserNo(userCustomer.getUserNo());
            commonUserBo.setUserType((short)2);
            commonUserBo.setAccessToken(token);
            redisTemplate.opsForValue().set("LOGIN_USER:"+token, JSONObject.toJSONString(commonUserBo));
            return new GlobalResult<CommonUserBo>().success("登录成功",commonUserBo);
        }
    }

  后面小程序就可以根据token进行登陆验证了

猜你喜欢

转载自www.cnblogs.com/yongxiangliu123/p/11411275.html