一个微信小程序登录实现

本文只是某项目的一个记录。 

需求:

官方给出的流程如下:

我们先按这个图中流程实现。 

第一步:获取open_id,首先得获取一个code,根据code进一步查询open_id。

		wx.login({
			success: res => {
				//获取code
				resolve(res.code)
			}
		})

我们把这个方法封装为getcode()

 ps:wx.login(Object object) | 微信开放文档

第二步:在微信小程序首页的onload中,调用getWechatInfo方法,把code传到后台服务,进一步查询open_id:

	async getWeChatInfo() {
			//获取code
			const code = await getCode()
			let  that=this;
			//将code发给后端请求token
			await uni.request({
				url: loginRequest.baseURL + "getWeChat",
				method: 'POST',
				data: {
					code
				},
				success: res => {
					if (res.data.code === 200) {
						this._openId = res.data.data.openId;
						//自定义登录状态存入缓存
						wx.setStorageSync('token', res.data.data.token);
						//后面2个最好不要存在缓存中  xj
						wx.setStorageSync('openId', res.data.data.openId);
						wx.setStorageSync('loginFlag', res.data.data.loginFlag);

						that.getUserInfoByOpenId();   
						//this.getUserInfoByOpenId();
					} else {
						this._openId = "-1";
						uni.showToast({
							title: res.data.msg,
							icon: 'error',
							duration: 2000
						})
						return;
					}
				}
			})
		},

 第三步:服务端进行登录凭证校验接口appid+appsect+code:

我们通过集成第三方 WxMaService 在服务端进行登录凭证校验(参数:appid+appsect+code),从而获取session_key及openid。

服务端具体代码如下:

   public JSONObject getWeChat(WeChatDTO weChatDTO) {
        String code = weChatDTO.getCode();
        log.info("code: {}", code);
        if (StrUtil.isBlank(code)) {
            throw new BizException("非法的授权码信息!");
        }
        WxMaProperties.Config config = wxMaProperties.getConfigs().stream().findFirst().get();

        if (!wxMaService.switchover(config.getAppid())) {
            throw new BizException(String.format("未找到对应appid=[%s]的配置,请核实!", config.getAppid()));
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String sessionKey = session.getSessionKey();
            String openid = session.getOpenid();
            String unionid = session.getUnionid();
            if (!StrUtil.isAllNotBlank(sessionKey, openid)) {
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值