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

相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万4 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋4 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁4 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
汉堡大王95274 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大4 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师4 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端
沙蒿同学4 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端