uniapp转H5 实现微信登录

uniapp转H5 实现微信登录

微信官方文档: 微信官方文档.

在这里插入图片描述
在这里插入图片描述

前端的任务
第一步

开发者需要先到公众平台官网中开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名(这一步是我们项目经理操作的)

第二步

在需要进行微信登录的页面 记性官方第一步的操作

// #ifdef H5
				let url = encodeURIComponent("tsn.dujiaoyu.net"); // 注意一定要encodeURIComponent
				console.log(url);
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx819aaa71e2c19c91&redirect_uri="授权成功后进入的页面,该页面的域名要和第一步设置的回调域名一致"&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
                // #endif
                
第三步

上一步授权成功,在跳转之后的页面链接地址上,会返回code,

// var currentSrc = "https://tsn.dujiaoyu.net/?code="你拿到的code"r&state="
// 拿到code之后
// 调用后端接口,根据后端返回的状态,进行正常的流程
$.ajax({
              type: 'POST',
              contentType: "application/json;charset=UTF-8",
              // dataType: 'jsonp',
              url: `https://tsn.dujiaoyu.net/api/users/weixin/getUserInfoInCode`,
              data: JSON.stringify({
                  code: searchHref
              }),
              success: (res => {
                  console.log(res);
                  if (res.code == 3001) {
                      //去注册
                      if (res.data) {
                          var headimgurl = res.data.headimgurl
                          var openId = res.data.openId
                          var nickname=res.nickname
                          window.location.href = ``
                      }else {
                          showToast(res.message,1000)
                      }
                  }else if(res.code==200){
                      //直接登录 
                      var token=res.data.token
                      var shopId=res.data.shopId
                      var nickName=res.data.nickname
                      var avatarUrl=res.data.avatar
                      var uid=res.data.uid
                      window.location.href=""
                  }
              }),
              error: (error => {
                  console.log(error);

              })
          })

最后
因为项目是用unaipp 转的H5,在写的时候一直不清楚回调返回的那个页面是从哪里来的,我又要怎么才能进入到正常流程的页面,最后的解决办法就是写一个H5页面,进行拿到code之后吊起后端接口的操作 ,然后在跳到项目中的H5链接地址,那自己后来写的H5页面就需要步到那个域名下面.这样就实现了整个流程,但又总觉得不应该是这样的处理办法,希望有大神指点一下下.