ykt-wxapp/store/account.js

78 lines
2.2 KiB
JavaScript
Raw Normal View History

2026-01-19 18:52:18 +08:00
import { ref } from "vue";
import { defineStore } from "pinia";
import api from '@/utils/api';
import { toast } from '@/utils/widget';
2026-01-20 13:21:50 +08:00
import { getInitIMPromise, clearInitIMPromise } from "@/utils/tim-chat.js";
2026-01-19 18:52:18 +08:00
const env = __VITE_ENV__;
export default defineStore("accountStore", () => {
const appid = env.MP_WX_APP_ID;
const account = ref(null);
const loading = ref(false)
2026-01-20 13:21:50 +08:00
// IM 相关
const openid = ref("");
const isIMInitialized = ref(false);
2026-01-20 16:30:03 +08:00
// 手机号(从授权登录获取)
const mobile = ref(uni.getStorageSync('user_mobile') || '');
2026-01-19 18:52:18 +08:00
async function login(phoneCode = '') {
if (loading.value) return;
loading.value = true;
try {
const { code } = await uni.login({
appid,
provider: "weixin",
scope: "snsapi_base",
});
console.log('logincode: ', code)
if (code) {
const res = await api('wxAppLogin', {
phoneCode,
code,
});
loading.value = false
console.log(res)
if (res.success && res.data && res.data.mobile) {
account.value = res.data;
2026-01-20 13:21:50 +08:00
openid.value = res.data.openid || res.data.openId || res.data.userId || "";
isIMInitialized.value = false;
clearInitIMPromise();
2026-01-20 16:30:03 +08:00
// 存储手机号
if (res.data.mobile) {
mobile.value = res.data.mobile;
uni.setStorageSync('user_mobile', res.data.mobile);
}
2026-01-19 18:52:18 +08:00
return res.data
}
}
toast('登录失败,请重新登录');
} catch (e) {
toast('登录失败,请重新登录');
}
loading.value = false
}
2026-01-20 13:21:50 +08:00
/**
* 登录后初始化 IM供聊天页调用
* @param {string} userID - IM userID通常用 openid/openId
*/
async function initIMAfterLogin(userID) {
const uid = userID || openid.value;
if (!uid) {
toast("缺少 openid无法初始化IM");
return false;
}
try {
await getInitIMPromise(uid, true);
isIMInitialized.value = true;
return true;
} catch (e) {
isIMInitialized.value = false;
return false;
}
}
2026-01-20 16:30:03 +08:00
return { account, openid, isIMInitialized, mobile, login, initIMAfterLogin }
2026-01-19 18:52:18 +08:00
})