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

相关推荐
文刀竹肃6 分钟前
DVWA -SQL Injection-通关教程-完结
前端·数据库·sql·安全·网络安全·oracle
LYFlied11 分钟前
【每日算法】LeetCode 84. 柱状图中最大的矩形
前端·算法·leetcode·面试·职场和发展
Bigger13 分钟前
Tauri(21)——窗口缩放后的”失焦惊魂”,游戏控制权丢失了
前端·macos·app
Bigger32 分钟前
Tauri (20)——为什么 NSPanel 窗口不能用官方 API 全屏?
前端·macos·app
bug总结33 分钟前
前端开发中为什么要使用 URL().origin 提取接口根地址
开发语言·前端·javascript·vue.js·html
一招定胜负2 小时前
网络爬虫(第三部)
前端·javascript·爬虫
Shaneyxs2 小时前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(13)
前端
半山烟雨半山青2 小时前
微信内容emoji表情包编辑器 + vue3 + ts + WrchatEmogi Editor
前端·javascript·vue.js
码途潇潇2 小时前
Vue 事件机制全面解析:原生事件、自定义事件与 DOM 冒泡完全讲透
前端·javascript
zmirror2 小时前
Monorepo 在 Docker 中的构建方案方案
前端