import { pinia } from "@/pinia" import { getOpenIdApi } from "@/common/apis/shop" export const useWxStore = defineStore("wx", () => { // 微信授权 code const code = ref("") // 防止 CSRF 攻击的 state 参数 const state = ref("") // 用户 openid const openid = ref("") // 模拟微信授权获取 code(需对接实际微信接口) const getWxAuth = async () => { // 这里应替换为实际微信授权逻辑 return new Promise((resolve) => { setTimeout(() => { code.value = "模拟的微信code" state.value = Date.now().toString() resolve() }, 1000) }) } // 设置 openid const setOpenid = (id: string) => { openid.value = id } const handleWxCallback = async (params: { code?: string; state?: string }) => { console.log('handleWxCallback:', params) if (params.code) { code.value = params.code state.value = params.state || state.value try { // 调用获取 openid 的接口 const res = await getOpenIdApi({ code: params.code }) console.log('获取 openid 成功:', res) if (res) { openid.value = res } } catch (err) { console.error('获取 openid 失败:', err) } } } (window as any).testWxSetOpenid = setOpenid return { code, state, openid, getWxAuth, setOpenid, handleWxCallback } }) /** * @description 用于在 setup 外使用 store */ export function useWxStoreOutside() { return useWxStore(pinia) }