后台需要做好俩个接口:
ticket
凭证和id
的接口 :xxx/weixin_qrcode_ticketopenid
获取用户信息、生成token
、保存token
到数据库的接口:xxx/check_login// React + Typescript 示例
export default function MxLogin() {
const [wechat, setWechat] = useState<{ ticket: string; id: string }>({
ticket: '',
id: ''
})
const [checkLogin, setCheckLogin] = useState(false)
useEffect(() => {
initWechatQrcode()
}, [])
// 轮训验证登录
useEffect(() => {
let intervalId = null
if (!checkLogin) {
return () => {
intervalId && clearTimeout(intervalId)
}
}
// 轮训是否有扫码登录
const fetchData = async () => {
try {
const response = await axios.post('xxx/check_login', { id: wechat.id })
// todo 设置用户信息与token
} catch (error) {
// todo 处理错误
}
}
fetchData()
intervalId = setInterval(fetchData, 1000)
return () => {
intervalId && clearTimeout(intervalId)
}
}, [checkLogin])
// 获取微信 ticket 凭证 和 id
const initWechatQrcode = async () => {
axios.post('xxx/weixin_qrcode_ticket')
.then((res: any) => {
if (res.ticket) {
const wechatUrl =
'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='
setWechat({ ticket: wechatUrl + res.ticket, id: res.id })
setCheckLogin(true)
return
}
message.error('获取微信授权失败!')
})
.catch(() => {
message.error('获取微信授权失败!')
})
}
return (
<>
<div className="login-wechat-qrcode">
{wechat.ticket && <img src={wechat.ticket} />}
</div>
</>
)
}