引言
一、微信授权概述
- 用户点击授权按钮,进入微信授权页面。
- 用户在微信授权页面同意授权。
- 第三方应用获取到用户授权的信息。
二、环境准备
- 微信公众账号:在微信公众平台申请一个公众账号,并获取AppID和AppSecret。
- Vue项目:一个已经搭建好的Vue项目。
三、实现步骤
1. 创建授权链接
function createWechatAuthUrl() {
const appid = '你的AppID';
const redirectUri = '你的回调地址';
const scope = 'snsapi_userinfo'; // snsapi_userinfo:弹出式微信授权,可以获取用户信息
const state = '任意值'; // 防止CSRF攻击
return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
}
2. 处理授权回调
function handleAuthCallback(code) {
// 向微信服务器发送请求,获取access_token
fetch(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=你的AppID&secret=你的AppSecret&code=${code}&grant_type=authorization_code`)
.then(response => response.json())
.then(data => {
if (data.access_token && data.openid) {
// 获取用户信息
fetch(`https://api.weixin.qq.com/sns/userinfo?access_token=${data.access_token}&openid=${data.openid}&lang=zh_CN`)
.then(response => response.json())
.then(userInfo => {
console.log('用户信息:', userInfo);
// 处理用户信息
});
} else {
console.error('授权失败');
}
});
}
3. 添加授权按钮
在你的Vue组件中,添加一个授权按钮,并绑定点击事件,调用createWechatAuthUrl
函数生成授权链接,并使用iframe或新窗口打开。
<template>
<button @click="openAuth">微信授权</button>
</template>
<script>
export default {
methods: {
openAuth() {
const authUrl = createWechatAuthUrl();
window.open(authUrl, '_blank');
}
}
};
</script>