39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
"use client"
|
||
|
||
import { useEffect } from "react"
|
||
import { usePathname, useSearchParams } from "next/navigation"
|
||
|
||
/**
|
||
* 捕获分享链接上的 ?ref=xxx 并写入本地存储
|
||
* - 目的:分销/推荐码在后续注册登录时可读取
|
||
* - 对齐小程序:pendingReferralCode
|
||
*/
|
||
export function ReferralCapture() {
|
||
const pathname = usePathname()
|
||
const searchParams = useSearchParams()
|
||
|
||
useEffect(() => {
|
||
// admin 不参与分销 ref 逻辑
|
||
if (pathname?.startsWith("/admin")) return
|
||
|
||
const ref = searchParams?.get("ref")?.trim()
|
||
if (!ref) return
|
||
|
||
try {
|
||
// 双写:对齐小程序 key,并留一份更直观的 key
|
||
localStorage.setItem("pendingReferralCode", ref)
|
||
localStorage.setItem("referral_code", ref)
|
||
|
||
// 兜底:写 cookie,方便服务端/客户端读取(30天)
|
||
const maxAge = 60 * 60 * 24 * 30
|
||
document.cookie = `pendingReferralCode=${encodeURIComponent(ref)}; Path=/; Max-Age=${maxAge}; SameSite=Lax`
|
||
document.cookie = `ref=${encodeURIComponent(ref)}; Path=/; Max-Age=${maxAge}; SameSite=Lax`
|
||
} catch {
|
||
// 忽略写入失败(隐私模式/禁用存储等),不影响页面访问
|
||
}
|
||
}, [pathname, searchParams])
|
||
|
||
return null
|
||
}
|
||
|