Vue如何在本地调试,实现微信公众号H5授权登录

前言

最近在学习Vue3 + TS,实现后端管理系统。有一个新设计的需求,需要实现在微信公众号的页面中,实现微信授权登录。于是整理一篇笔记,整理趟坑记录。

准备工作

  1. 申请测试账号

mp.weixin.qq.com/debug/cgi-b...

  1. 找到网页服务,修改配置
  1. 配置内容

特别说明 这里需要配置的是ip或者域名,切记不要添加 http:// 或者 https://

实现逻辑

第一步:用户同意授权,获取code。如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE

第二步:通过code换取网页授权access_token。

第三步:刷新access_token(如果需要)

第四步:拉取用户信息(需scope为 snsapi_userinfo)

微信参考文档

代码示例

xml 复制代码
<!-- 注册页面 -->
<template>
  <view class="bottom-side-otherLogin" @click="getWeChatCode" v-if="isWeixin">
    <text>微信号号登录</text>
  </view>
</template>
<script>
export default {
  data() {
    return {
      isWeixin: false,
    };
  },
  onLoad() {
    this.isWeixin = this.isWechat()
    if(this.isWeixin){
      this.checkWeChatCode()//通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
    }
  },
  onShow() {
  },
  mounted() {

  },
  methods: {
    /*微信登录相关  start*/
    //方法:用来判断是否是微信内置的浏览器
    isWechat() {
      return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
    },
    //方法:用来提取code
    getUrlCode(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
        .replace(/+/g, '%20')) || null
    },
    //检查浏览器地址栏中微信接口返回的code
    checkWeChatCode() {
      let code = this.getUrlCode('code')
      uni.showToast({
        title:`微信code=${code}`
      })
      if (code) {

        this.getOpenidAndUserinfo(code)
      }
    },
    //请求微信接口,用来获取code
    getWeChatCode() {
      let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
      let appid = '自己的appid'

      //通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appid +
        "&redirect_uri=" +
        local +
        "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    },
    //把code传递给后台接口,静默登录
    getOpenidAndUserinfo(code) {
      this.$http({
        url:'api/login',
        data:{
          code:code
        }
      }).then((res) => {
        console.log(res)
        if (res.code != 0) {
          uni.showToast({
            title: res.msg,
            duration: 3000,
            icon: 'none'
          });
          return
        }else{
          this.afterLogin(res)
        }
      })
    },
    /*微信登录相关  end*/
    afterLogin(res){
      let user = res.data.user
      uni.setStorageSync('token', res.data.token);
      let u = {
        avatar: user.avatar ? user.avatar : this.avatar,
        mobile: user.mobile,
        nickname: user.nickname ? user.nickname : '稀土'
      }
      uni.setStorage({
        key: 'u',
        data: u,
        success: () => {

          let url = uni.getStorageSync('redirect')
          uni.reLaunch({
            url: url ? url : '/pages/index'
          })
        }
      });
    },
  },

}
</script>

拼接地址参数说明

特别注意

1.scope等于snsapi_userinfo时才会弹出授权页面

2.拼接的地址需要 http:// 或者 https:// ,根据自己的情况来填写。同时需要进行encodeURIComponent转码才可以使用。

一定确保后台配置的回调的域名或IP是同样的内容,不然会提示 redirect_uri 错误

相关推荐
PineappleCoder20 小时前
性能数据别再瞎轮询了!PerformanceObserver 异步捕获 LCP/CLS,不卡主线程
前端·性能优化
PineappleCoder20 小时前
告别字体闪烁 / 首屏卡顿!preload 让关键资源 “高优先级” 提前到
前端·性能优化
m0_4711996320 小时前
【vue】通俗详解package-lock文件的作用
前端·javascript·vue.js
GIS之路20 小时前
GDAL 读取KML数据
前端
今天不要写bug21 小时前
vue项目基于vue-cropper实现图片裁剪与图片压缩
前端·javascript·vue.js·typescript
用户479492835691521 小时前
记住这张时间线图,你再也不会乱用 useEffect / useLayoutEffect
前端·react.js
咬人喵喵21 小时前
14 类圣诞核心 SVG 交互方案拆解(附案例 + 资源)
开发语言·前端·javascript
问君能有几多愁~1 天前
C++ 日志实现
java·前端·c++
咬人喵喵1 天前
CSS 盒子模型:万物皆是盒子
前端·css