42 lines
1.1 KiB
JavaScript
42 lines
1.1 KiB
JavaScript
|
// src/composables/useWeChatAuth.js
|
||
|
import { ref } from 'vue';
|
||
|
import request from '@/request/index.js';
|
||
|
|
||
|
const APPID = 'wx8fc3e4305d2fbf0b';
|
||
|
const REDIRECT_URI = encodeURIComponent('https://www.focusnu.com/wechat/thd/#/pages/index/callback');
|
||
|
|
||
|
export function useWeChatAuth() {
|
||
|
const code = ref('');
|
||
|
const openid = ref('');
|
||
|
const userInfo = ref(null);
|
||
|
|
||
|
function login(scope = 'snsapi_userinfo', state = '') {
|
||
|
const url =
|
||
|
`https://open.weixin.qq.com/connect/oauth2/authorize` +
|
||
|
`?appid=${APPID}` +
|
||
|
`&redirect_uri=${REDIRECT_URI}` +
|
||
|
`&response_type=code` +
|
||
|
`&scope=${scope}` +
|
||
|
`&state=${state}` +
|
||
|
`#wechat_redirect`;
|
||
|
window.location.href = url;
|
||
|
}
|
||
|
|
||
|
async function fetchUserInfo(authCode) {
|
||
|
code.value = authCode;
|
||
|
try {
|
||
|
// 使用全局封装请求
|
||
|
const data = await request({
|
||
|
url: '/api/auth',
|
||
|
method: 'post',
|
||
|
data: { code: authCode }
|
||
|
});
|
||
|
openid.value = data.openid;
|
||
|
userInfo.value = data;
|
||
|
} catch (e) {
|
||
|
console.error('获取用户信息失败', e);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return { code, openid, userInfo, login, fetchUserInfo };
|
||
|
}
|