Nuxt3 页面嵌入微信扫码登录

Nuxt页面内嵌微信扫码登录

微信扫码登录主要通过扫码用用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code和state参数,在重定向页面通过code等参数请求后端接口,后端返回登录成功与否(后端用code去微信那获取access_token等)。若用户禁止授权,则不会发生重定向。
参考微信官网文档 网站应用微信登录开发指南
1、准备一个div

<div class="wxcode-con" id="login_container"></div>

2、引入微信js


id这里填写你装微信二维码的容器id
appid:把appid这样写本地不安全,目前没想到其他处理办法,先将就一下吧
redirect_url: 跳转的中间页面,得是正式环境得时候得地址,所以我这当时本地测不了。我这地址也就是http://www.xxx.com/loginRedirect
具体参数的意义及其配置请参考官方文档。

3、准备loginRedirect.vue

<template>
  <div class="text-center">欢迎登录</div>
</template>

<script lang="ts" setup>
import { getUserInfo, getScComplate } from "@/utils/api"
const route = useRoute()
const code = ref(route.query.code)
const state = ref(route.query.state)
const userInfo = useCookie('userInfo', { maxAge: 3600 * 24 * 30 })
const token = useCookie('token', { maxAge: 3600 * 24 * 30 })
const loginWx = async () => {
  const { data } = await useFetch(
    'http://xxx/login-with-wechat',
    {
      method: 'post',
      body: {
        code: code.value
      },
    }
  );
  // 根据自己后端的返回判断
  // 如果登录成功,但是未绑定微信,跳转绑定页面。如果已经绑定,去请求用户信息
  // 如果登录失败。。。。
}
if (!code) {
  navigateTo('/login')
} else {
  loginWx()
}

</script>

<style lang="scss" scoped></style>

你可能感兴趣的:(nuxt3,前端,微信,javascript,typescript)