Nuxt3 页面嵌入微信扫码登录

Nuxt页面内嵌微信扫码登录

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

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

2、引入微信js

<script setup lang="ts">
// import { WxLogin } from ''
definePageMeta({
  layout: false
})
useHead({
  title: '登录_注册',
  script: [
    { src: 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js', type: 'text/javascript' },
    { children: 'var obj = new WxLogin({self_redirect: false, id: "login_container", appid: "xxxx", scope: "snsapi_login", redirect_uri: "https%3A%2F%2Fwww.xxxx.com%2FloginRedirect", state: "", style: "white", href: ""});', body: true }
  ]
})
</script>

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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值