Files
YGChatCS/src/hooks/useGoLogin.js
2025-12-25 22:45:55 +08:00

95 lines
2.4 KiB
JavaScript

import { wxLogin } from "../request/api/LoginApi";
import { loginAuth, bindPhone, checkPhone } from "@/manager/LoginManager";
import { clientId } from "@/constant/base";
import { NOTICE_EVENT_LOGIN_SUCCESS } from "@/constant/constant";
import { getStorageSyncToken, setStorageSyncToken } from "../constant/token";
// 跳转登录
export const goLogin = () => uni.navigateTo({ url: "/pages/login/index" });
// 登录成功后,返回上一页
export const goBack = () => uni.navigateBack({ delta: 1 });
// 登录逻辑
export const onLogin = async (e) => {
console.info("onLogin code: ", e);
return new Promise(async (resolve, reject) => {
// 判断用户拒绝
if (e !== undefined && e && e.detail && e.detail.errno === 104) {
reject();
return;
}
await loginAuth(e).then(async () => {
// 检查手机号是否绑定
const checkRes = await checkPhone();
if (checkRes.data) {
resolve();
return;
}
if (e === undefined) {
resolve();
return;
}
const { code } = e.detail;
// 绑定手机号
const params = { wechatPhoneCode: code, clientId: clientId };
const res = await bindPhone(params);
if (res.data) {
resolve();
}
});
});
};
// 检测token
export const checkToken = () => {
const token = getStorageSyncToken();
return new Promise((resolve) => {
if (!token) {
goLogin();
return;
}
resolve();
});
};
// 刷新token
export const refreshToken = async () => {
return new Promise((resolve) => {
checkPhone().then(async (checkRes) => {
if (!checkRes.data) {
resolve(true);
return;
}
uni.login({
provider: "weixin", //使用微信登录
success: async ({ code }) => {
console.log("refreshToken", code);
const params = {
openIdCode: [code],
grant_type: "wechat",
scope: "server",
clientId: clientId,
};
console.log("获取到的微信授权params:", JSON.stringify(params));
const response = await wxLogin(params);
if (response.access_token) {
setStorageSyncToken(response.access_token);
// 登录成功后,触发登录成功事件
uni.$emit(NOTICE_EVENT_LOGIN_SUCCESS);
}
},
});
});
});
};