【vue3+vite应用从0到1】3.对接微信认证及微信本地调试

364 阅读2分钟

收录专栏:一个Vue3项目的从0到1

简介:微信认证 微信公众号本地调试

现在的前端移动应用,一般分为两种:1. 自有APP内嵌H5 2. 微信公众号。 文章以微信公众号对接为例

在现实的开发中我们的授权并不是这么简单,我们可能很多需要和自己的后端进行api对接,将微信的AppId和 AppSecret存在后端服务器,唤起授权前端做但是获取AccessToken是由后端完成,前端只从后端取数据以保证数据的安全性

微信公众号授权的本地调试请看VCR


准备


Code it

先理清微信登录步骤,官方文档已经很清楚了:

image.png

graph TD
带着appId及回调页面url后location跳转唤起微信授权,获取code --> 使用code发送Ajax请求得到accessToken及OpenId

写个微信授权的承接页,用来承接和跳转微信授权

ps:这个代码只是示意,比如说code失效或者多次请求需要从当前href上replace,或者再次重试唤起授权等

warning:微信的appSecret和返回的AccessToken及openId,在生产环境中是不能放在前端的,请在实际的生产项目请千万千万**【不要参考本示例】**

<template>
  <div class="wechatauth-container">正在认证中,请稍候...</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";";
import { useRouter } from "vue-router";
import { getURLParams } from "@/utils/common";
import { getAccessToken, gotoWxAuth } from "@/utils/wxAuth
const router = useRouter();
let urlParams = getURLParams();
const { code, state } = urlParams;
// 如果存在code 即表示当前是微信授权跳转过来的。如果不存在则表示是直接进入的授权页
if (code) {
  getAccessToken(code).then((res) => {
    // 获取到token后跳转到首页
    router.push({ name: "home" });
  }).catch(()=>{
  // 如果获取token失败,后续处理是重新唤起还是怎么,自行处理
  // todo ...
  });
} else {
  // 这一步拼接跳转url唤起授权
  gotoWxAuth();
}
</script>
<style lang="less" scoped>
.wechatauth-container {
}
</style>


  • 微信帮助方法类:
import { wxAppId, wxAppSecret, wxRedirectUrl } from "@/const";
import axios from "axios";
const scope_base = "snsapi_base";

// 获取微信授权
export function gotoWxAuth(state) {
  const wxAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxAppId}&redirect_uri=${encodeURIComponent(wxRedirectUrl)}&response_type=code&scope=${scope_base}&state=${state}#wechat_redirect`;
  window.location.href = wxAuthUrl;
}

// 根据Code获取Token
// 实际生产中`api.weixin.qq.com/sns/oauth2/access_token?` 这个接口是后端去调用的,不是前端调的,这里只是示例

export function getAccessToken(code) {
  return new Promise((resolve, reject) => {
  // 再次申明,这里只是示例,实际生产应用不能这样放在前端调用
    axios
      .get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wxAppId}&secret=${wxAppSecret}&code=${code}&grant_type=authorization_code`)
      .then((res) => {
        const { access_token } = res.data || {};
        if (access_token) {
          resolve(res.data);
        } else {
          reject(new Error("get access_token error"));
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}