44 lines
1.6 KiB
HTML
44 lines
1.6 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>微信登录示例</title>
|
|
</head>
|
|
|
|
<body>
|
|
<button id="loginBtn">微信登录</button>
|
|
|
|
<script>
|
|
const APP_ID = 'wx364b8ebf17fe45fe';
|
|
const REDIRECT_URI = encodeURIComponent(window.location.origin + '/callback.html');
|
|
const STATE = Math.random().toString(36).substring(2, 12);
|
|
const SCOPE = 'snsapi_userinfo';
|
|
|
|
document.getElementById('loginBtn').onclick = () => {
|
|
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${SCOPE}&state=${STATE}#wechat_redirect`;
|
|
window.location.href = url;
|
|
};
|
|
|
|
// 在 callback.html 中获取 code 并调用后端
|
|
if (window.location.search.includes('code=')) {
|
|
const params = new URLSearchParams(window.location.search);
|
|
const code = params.get('code');
|
|
const state = params.get('state');
|
|
|
|
fetch('/api/wechat-login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ code })
|
|
})
|
|
.then(res => res.json())
|
|
.then(data => {
|
|
console.log('登录结果:', data);
|
|
// data.userInfo 就是微信用户信息
|
|
})
|
|
.catch(err => console.error(err));
|
|
}
|
|
</script>
|
|
</body>
|
|
|
|
</html> |