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

相关推荐
明远湖之鱼1 分钟前
浅入理解流式SSR的性能收益与工作原理
前端·ios
IT_陈寒40 分钟前
Python性能提升50%:这5个隐藏技巧让你的代码快如闪电⚡
前端·人工智能·后端
懒人村杂货铺1 小时前
微前端QianKun的使用以及坑点问题
前端
qq_366577511 小时前
Vue3创建项目,只能localhost访问问题处理
前端·javascript·vue.js
一个处女座的程序猿O(∩_∩)O1 小时前
React Router 路由模式详解:HashRouter vs BrowserRouter
前端·react.js·前端框架
Caster_Z2 小时前
WinServer安装NPM(Nginx Proxy Manager),并设置反向代理和开启https
前端·nginx·npm
顾安r2 小时前
11.22 脚本 手机termux项目分析(bash)
前端·python·stm32·flask·bash
是你的小橘呀2 小时前
JavaScript 原型链解密:原来 proto 和 prototype 这么好懂
前端·javascript·前端框架
ohyeah2 小时前
使用 LocalStorage 实现本地待办事项(To-Do)列表
前端·javascript
Jing_Rainbow2 小时前
【前端三剑客-6/Lesson11(2025-10-28)构建现代响应式网页:从 HTML 到 CSS 弹性布局再到 JavaScript 交互的完整指南 🌈
前端·javascript