vue-微信登录
2023-05-11 本文已影响0人
云高风轻
1. 前言
- vue第三方登录 这个简单的写下 微信登录的流程 ,其实哪个都行 有接口前端就能做
2. 安装 插件
- npm install vue-wechat-login
3. 登录流程
<template>
<div>
<button @click="wechatLogin">微信登录</button>
</div>
</template>
<script>
import { WechatLogin } from 'vue-wechat-login'
import { ref } from 'vue'
export default {
components: {
WechatLogin
},
setup() {
const authUrl = ref('')
const wechatLogin = () => {
// 在这里调用后端接口,获取微信授权链接,然后跳转到该链接进行微信登录
// 例如:
axios.get('/api/wechat/getAuthUrl')
.then(response => {
authUrl.value = response.data.authUrl
})
.catch(error => {
console.log(error)
})
}
return {
authUrl,
wechatLogin
}
}
}
</script>
- 这里使用vue-wechat-login插件提供的WechatLogin组件来展示微信登录按钮,
3.当点击按钮时会调用wechatLogin方法。
4.使用ref函数创建了一个authUrl响应式变量,用于保存微信授权链接。
4. 创建一个路由,用于处理微信登录回调
- 核心代码
import { createRouter, createWebHistory } from 'vue-router'
import WechatLoginCallback from '@/views/WechatLoginCallback.vue'
const routes = [
{
path: '/wechatLoginCallback',
name: 'WechatLoginCallback',
component: WechatLoginCallback
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
- 这里创建了一个名为
WechatLoginCallback
的组件,用于处理微信登录回调。- 当用户从微信登录页面回调到该组件时,可以从回调URL中获取到授权码,
- 然后调用后端接口,获取用户的微信信息。
5. 后端实现
- 首先需要在微信公众平台或者开放平台中创建应用,并获取到应用的
AppID
和AppSecret
。- 同时需要在平台中配置回调URL,用于接收微信登录回调
- 在后端实现一个API,用于获取微信授权链接。该API需要使用应用的AppID和回调URL构建授权链接,并返回给前端。
app.get('/api/wechat/getAuthUrl', (req, res) => {
const redirectUrl = encodeURIComponent('http://example.com/wechatLoginCallback')
const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP