This commit is contained in:
eric
2026-03-13 04:41:51 -05:00
parent 37d0883ce9
commit a193fe4d45
22 changed files with 1119 additions and 468 deletions

View File

@@ -36,15 +36,11 @@ export function getPayEnv(): PayEnv {
}
/**
* 根据环境推荐/强制支付通道
* - 微信浏览器:只能用 wxpay支付宝在微信内无法唤起
* - 支付宝浏览器:优先 alipay
* - PC/H5用户可选
* 根据环境推荐支付通道
* 所有支付默认微信支付,支付宝暂不提供
*/
export function getRecommendedChannel(env: PayEnv): PayChannel {
if (env === "wechat") return "wxpay";
if (env === "pc" || env === "h5") return "alipay"; // 默认支付宝
return "alipay";
export function getRecommendedChannel(_env: PayEnv): PayChannel {
return "wxpay";
}
/** 微信内是否只能选微信支付 */

View File

@@ -1,13 +1,10 @@
/**
* 微信 H5 支付完成后可能不跳转,通过 cookie 中的订单号轮询检测支付状态
* cookie 格式order_id|timestamp仅对 15 分钟内设置的 cookie 轮询,避免陈旧 cookie 误触发
*/
import { useEffect, useRef, useState } from "react";
const COOKIE_NAME = "join_pay_order";
const POLL_INTERVAL = 2000;
const MAX_POLLS = 150; // 约 5 分钟
const MAX_AGE_MS = 15 * 60 * 1000; // 15 分钟
const STORAGE_NAME = "join_pay_order";
const POLL_INTERVAL_MS = 1200;
const MAX_POLLS = 60;
const MAX_AGE_MS = 15 * 60 * 1000;
function getCookie(name: string): string | null {
if (typeof document === "undefined") return null;
@@ -20,15 +17,40 @@ function clearCookie(name: string): void {
document.cookie = `${name}=; path=/; max-age=0`;
}
/** 解析 cookieorder_id|timestamp返回 [orderId, isValid]。无时间戳视为过期并清除 */
function parsePayOrderCookie(raw: string | null): [string | null, boolean] {
function getStorage(name: string): string | null {
if (typeof window === "undefined") return null;
return window.localStorage.getItem(name);
}
function removeStorage(name: string): void {
if (typeof window === "undefined") return;
window.localStorage.removeItem(name);
}
function clearPendingOrder(): void {
clearCookie(COOKIE_NAME);
removeStorage(STORAGE_NAME);
}
function persistPendingOrder(raw: string): void {
if (typeof document !== "undefined") {
document.cookie = `${COOKIE_NAME}=${encodeURIComponent(raw)}; path=/; max-age=900`;
}
if (typeof window !== "undefined") {
try {
window.localStorage.setItem(STORAGE_NAME, raw);
} catch {}
}
}
function parsePendingOrder(raw: string | null): [string | null, boolean] {
if (!raw?.trim()) return [null, false];
const parts = raw.split("|");
const orderId = parts[0]?.trim() || raw.trim();
const ts = parts[1] ? parseInt(parts[1], 10) : NaN;
if (!orderId) return [null, false];
if (Number.isNaN(ts)) return [orderId, false]; // 旧格式无时间戳,视为过期
if (Date.now() - ts > MAX_AGE_MS) return [orderId, false]; // 超过 15 分钟
if (Number.isNaN(ts)) return [orderId, false];
if (Date.now() - ts > MAX_AGE_MS) return [orderId, false];
return [orderId, true];
}
@@ -38,38 +60,110 @@ export function usePayStatusPoll(onPaid: () => void): boolean {
onPaidRef.current = onPaid;
useEffect(() => {
const raw = getCookie(COOKIE_NAME);
const [orderId, isValid] = parsePayOrderCookie(raw);
if (!orderId || !isValid) {
if (raw) clearCookie(COOKIE_NAME);
const cookieRaw = getCookie(COOKIE_NAME);
const [cookieOrderId, cookieValid] = parsePendingOrder(cookieRaw);
const storageRaw = getStorage(STORAGE_NAME);
const [storageOrderId, storageValid] = parsePendingOrder(storageRaw);
const orderId = cookieValid ? cookieOrderId : storageValid ? storageOrderId : null;
const activeRaw = cookieValid ? cookieRaw : storageValid ? storageRaw : null;
if (!orderId) {
if (cookieRaw || storageRaw) {
clearPendingOrder();
}
return;
}
if (activeRaw) {
persistPendingOrder(activeRaw);
}
setPolling(true);
let count = 0;
const timer = setInterval(async () => {
count++;
if (count > MAX_POLLS) {
clearInterval(timer);
clearCookie(COOKIE_NAME);
let attempts = 0;
let stopped = false;
let timer: number | undefined;
let inFlight = false;
const stop = () => {
stopped = true;
if (timer) window.clearTimeout(timer);
};
const scheduleNext = () => {
if (stopped) return;
timer = window.setTimeout(tick, POLL_INTERVAL_MS);
};
const tick = async () => {
if (stopped) return;
if (inFlight) {
scheduleNext();
return;
}
attempts += 1;
if (attempts > MAX_POLLS) {
stop();
clearPendingOrder();
setPolling(false);
return;
}
inFlight = true;
try {
const res = await fetch(`/api/pay/status?order_id=${encodeURIComponent(orderId)}`);
const data = await res.json();
const res = await fetch(
`/api/pay/status?order_id=${encodeURIComponent(orderId)}`,
{ cache: "no-store" }
);
const data = await res.json().catch(() => ({}));
if (data?.ok && data?.paid) {
clearInterval(timer);
clearCookie(COOKIE_NAME);
stop();
clearPendingOrder();
setPolling(false);
// 对齐 nomadvip调用 confirm 写入 PocketBase site_vip不依赖 payjsapi 异步 notify
try {
const confirmRes = await fetch("/api/pay/confirm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ order_id: orderId }),
cache: "no-store",
});
if (confirmRes.ok && typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("vip:updated"));
}
} catch {
/* 忽略,不影响跳转 */
}
onPaidRef.current();
return;
}
} catch {
// 继续轮询
// keep polling
} finally {
inFlight = false;
}
}, POLL_INTERVAL);
return () => clearInterval(timer);
scheduleNext();
};
const handleResume = () => {
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
return;
}
void tick();
};
document.addEventListener("visibilitychange", handleResume);
window.addEventListener("pageshow", handleResume);
window.addEventListener("focus", handleResume);
void tick();
return () => {
document.removeEventListener("visibilitychange", handleResume);
window.removeEventListener("pageshow", handleResume);
window.removeEventListener("focus", handleResume);
stop();
};
}, []);
return polling;

View File

@@ -0,0 +1,49 @@
import { createHash } from "crypto";
const XORPAY_AID = process.env.XORPAY_AID || "8220";
const XORPAY_SECRET =
process.env.XORPAY_SECRET || "afcacd99570945f88de62624aaa3578e";
const XORPAY_QUERY_URL =
process.env.XORPAY_QUERY_URL || "https://xorpay.com/api/query2";
export async function queryXorPayOrderStatus(
orderId: string,
timeoutMs = 5000
): Promise<{ paid: boolean; status?: string; error?: string; url: string } | null> {
const normalizedOrderId = orderId.trim();
if (!normalizedOrderId || !XORPAY_AID || !XORPAY_SECRET) {
return null;
}
const sign = createHash("md5")
.update(`${normalizedOrderId}${XORPAY_SECRET}`, "utf8")
.digest("hex")
.toLowerCase();
const url = new URL(
`${XORPAY_QUERY_URL.replace(/\/$/, "")}/${encodeURIComponent(XORPAY_AID)}`
);
url.searchParams.set("order_id", normalizedOrderId);
url.searchParams.set("sign", sign);
try {
const res = await fetch(url.toString(), {
cache: "no-store",
signal: AbortSignal.timeout(timeoutMs),
});
const data = await res.json().catch(() => ({}));
const status = String(data?.status || "").trim().toLowerCase();
return {
paid: res.ok && (status === "payed" || status === "success"),
status,
url: url.toString(),
error: res.ok ? undefined : `status=${res.status}`,
};
} catch (error) {
return {
paid: false,
url: url.toString(),
error: error instanceof Error ? error.message : String(error),
};
}
}

View File

@@ -0,0 +1,45 @@
const ZPAY_PID = process.env.ZPAY_PID || "2025121809351743";
const ZPAY_KEY = process.env.ZPAY_KEY || "tpEi7wWIWI2kXiYVTpIG6j7it0mjVW89";
const ZPAY_QUERY_URL =
process.env.ZPAY_QUERY_URL || "https://zpayz.cn/api.php";
export async function queryZPayOrderStatus(
orderId: string,
timeoutMs = 5000
): Promise<{ paid: boolean; status?: string; error?: string; url: string } | null> {
const normalizedOrderId = orderId.trim();
if (!normalizedOrderId || !ZPAY_PID || !ZPAY_KEY) {
return null;
}
const url = new URL(ZPAY_QUERY_URL);
url.searchParams.set("act", "order");
url.searchParams.set("pid", ZPAY_PID);
url.searchParams.set("key", ZPAY_KEY);
url.searchParams.set("out_trade_no", normalizedOrderId);
try {
const res = await fetch(url.toString(), {
cache: "no-store",
signal: AbortSignal.timeout(timeoutMs),
});
const data = await res.json().catch(() => ({}));
const code = String(data?.code || "").trim();
const status = String(data?.status || "").trim();
return {
paid: res.ok && code === "1" && status === "1",
status,
url: url.toString(),
error:
res.ok && code === "1"
? undefined
: String(data?.msg || `status=${res.status}`),
};
} catch (error) {
return {
paid: false,
url: url.toString(),
error: error instanceof Error ? error.message : String(error),
};
}
}

View File

@@ -67,11 +67,17 @@ export function pbSaveAuth(token: string, record: AuthUser): void {
localStorage.setItem(PB_STORAGE_KEYS.user, JSON.stringify(record));
}
/** 登出 - 清除本地存储和根域 Cookie */
/** 登出 - 清除本地存储、支付订单 cookie 和根域 Cookie */
export async function pbLogout(): Promise<void> {
if (typeof window === "undefined") return;
localStorage.removeItem(PB_STORAGE_KEYS.token);
localStorage.removeItem(PB_STORAGE_KEYS.user);
localStorage.removeItem("join_pay_order");
try {
document.cookie = "join_pay_order=; path=/; max-age=0";
} catch {
/* ignore */
}
try {
await fetch("/api/auth/logout", { method: "POST" });
} catch {

View File

@@ -18,14 +18,9 @@ export function useAuthAndVip(): AuthAndVipState {
const refetch = useCallback(async (): Promise<{ user: { id: string; email: string } | null; vip: boolean }> => {
setLoading(true);
try {
const [meRes, vipRes] = await Promise.all([
fetch("/api/auth/me", { credentials: "include" }),
fetch("/api/vip/check", { credentials: "include" }),
]);
const meRes = await fetch("/api/auth/me", { credentials: "include" });
const meData = await meRes.json();
const vipData = await vipRes.json();
let newUser = meData?.user ?? null;
let newVip = vipData?.vip === true;
if (!newUser) {
const storedUser = getStoredUser();
@@ -45,6 +40,13 @@ export function useAuthAndVip(): AuthAndVipState {
}
}
let newVip = false;
if (newUser?.email) {
const vipRes = await fetch(`/api/vip/check?email=${encodeURIComponent(newUser.email)}`, { credentials: "include" });
const vipData = await vipRes.json();
newVip = vipData?.vip === true;
}
setUser(newUser);
setVip(newVip);
return { user: newUser, vip: newVip };