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 错误

相关推荐
(⊙o⊙)~哦1 小时前
JavaScript substring() 方法
前端
无心使然云中漫步1 小时前
GIS OGC之WMTS地图服务,通过Capabilities XML描述文档,获取matrixIds,origin,计算resolutions
前端·javascript
Bug缔造者1 小时前
Element-ui el-table 全局表格排序
前端·javascript·vue.js
xnian_2 小时前
解决ruoyi-vue-pro-master框架引入报错,启动报错问题
前端·javascript·vue.js
麒麟而非淇淋3 小时前
AJAX 入门 day1
前端·javascript·ajax
2401_858120533 小时前
深入理解MATLAB中的事件处理机制
前端·javascript·matlab
阿树梢3 小时前
【Vue】VueRouter路由
前端·javascript·vue.js
随笔写4 小时前
vue使用关于speak-tss插件的详细介绍
前端·javascript·vue.js
史努比.4 小时前
redis群集三种模式:主从复制、哨兵、集群
前端·bootstrap·html
快乐牌刀片885 小时前
web - JavaScript
开发语言·前端·javascript