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

47 lines
1.2 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>("")
// 设置 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)
2025-03-21 17:00:06 +08:00
if (res && res.code == 0) {
openid.value = res.data
2025-03-17 08:30:57 +08:00
}
} catch (err) {
console.error('获取 openid 失败:', err)
}
}
}
(window as any).testWxSetOpenid = setOpenid
2025-03-31 09:42:26 +08:00
return { code, state, openid, setOpenid, handleWxCallback }
2025-03-17 08:30:57 +08:00
})
/**
* @description setup 使 store
*/
export function useWxStoreOutside() {
return useWxStore(pinia)
}