Files
soul-yongping/next-project/components/view/layout/referral-capture.tsx
2026-02-09 14:43:35 +08:00

39 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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
}