ykt-wxapp/store/account.js
2026-01-20 13:21:50 +08:00

72 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ref } from "vue";
import { defineStore } from "pinia";
import api from '@/utils/api';
import { toast } from '@/utils/widget';
import { getInitIMPromise, clearInitIMPromise } from "@/utils/tim-chat.js";
const env = __VITE_ENV__;
export default defineStore("accountStore", () => {
const appid = env.MP_WX_APP_ID;
const account = ref(null);
const loading = ref(false)
// IM 相关
const openid = ref("");
const isIMInitialized = ref(false);
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;
// 兼容不同字段名
openid.value = res.data.openid || res.data.openId || res.data.userId || "";
isIMInitialized.value = false;
clearInitIMPromise();
return res.data
}
}
toast('登录失败,请重新登录');
} catch (e) {
toast('登录失败,请重新登录');
}
loading.value = false
}
/**
* 登录后初始化 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;
}
}
return { account, openid, isIMInitialized, login, initIMAfterLogin }
})