shop-web/src/pinia/stores/wx.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-03-17 08:30:57 +08:00
import { pinia } from "@/pinia"
import { getOpenIdApi } from "@/common/apis/shop"
export const useWxStore = defineStore("wx", () => {
// 微信授权 code
const code = ref<string>("")
// 防止 CSRF 攻击的 state 参数
const state = ref<string>("")
// 用户 openid
const openid = ref<string>("")
// 模拟微信授权获取 code需对接实际微信接口
const getWxAuth = async () => {
// 这里应替换为实际微信授权逻辑
return new Promise<void>((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)
}