51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
/**
|
||
* 主播绑定 - 前端工具(参考 Soul 创业实验:ref 捕获 + 登录后绑定)
|
||
*/
|
||
|
||
const STORAGE_KEY = "wanzhi_pending_streamer_ref"
|
||
|
||
export function getPendingStreamerRef(): string | null {
|
||
if (typeof window === "undefined") return null
|
||
try {
|
||
const v = localStorage.getItem(STORAGE_KEY)
|
||
return v && v.trim() ? v.trim() : null
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
export function setPendingStreamerRef(ref: string): void {
|
||
if (typeof window === "undefined") return
|
||
try {
|
||
if (ref && ref.trim()) localStorage.setItem(STORAGE_KEY, ref.trim())
|
||
else localStorage.removeItem(STORAGE_KEY)
|
||
} catch {}
|
||
}
|
||
|
||
export function clearPendingStreamerRef(): void {
|
||
if (typeof window === "undefined") return
|
||
try {
|
||
localStorage.removeItem(STORAGE_KEY)
|
||
} catch {}
|
||
}
|
||
|
||
/**
|
||
* 调用绑定接口;成功后清除待绑定
|
||
*/
|
||
export async function bindStreamer(userId: string, ref: string): Promise<{ success: boolean; message?: string }> {
|
||
if (!userId || !ref) return { success: false, message: "缺少 userId 或 ref" }
|
||
try {
|
||
const res = await fetch("/api/streamer/bind", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ userId, ref }),
|
||
})
|
||
const json = await res.json().catch(() => ({}))
|
||
if (json.success) clearPendingStreamerRef()
|
||
return { success: !!json.success, message: json.message }
|
||
} catch (e) {
|
||
console.error("[streamer-bind] bindStreamer error:", e)
|
||
return { success: false, message: "请求失败" }
|
||
}
|
||
}
|