's'
This commit is contained in:
@@ -1,13 +1,9 @@
|
||||
/**
|
||||
* 支付状态轮询
|
||||
* - 手机 H5:传入 orderId(点击支付后由 state 传入),直接轮询,不依赖 sessionStorage/cookie
|
||||
* - PC/微信:不传 orderId,使用 cookie 轮询(兼容旧逻辑)
|
||||
*/
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
const COOKIE_NAME = "nomadvip_pay_order";
|
||||
const POLL_INTERVAL = 1000;
|
||||
const MAX_POLLS = 160; // ~5 分钟
|
||||
const STORAGE_NAME = "nomadvip_pay_order";
|
||||
const POLL_INTERVAL_MS = 1200;
|
||||
const MAX_POLLS = 30;
|
||||
const MAX_AGE_MS = 15 * 60 * 1000;
|
||||
|
||||
function getCookie(name: string): string | null {
|
||||
@@ -21,6 +17,21 @@ function clearCookie(name: string): void {
|
||||
document.cookie = `${name}=; path=/; max-age=0`;
|
||||
}
|
||||
|
||||
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 parsePayOrderCookie(raw: string | null): [string | null, boolean] {
|
||||
if (!raw?.trim()) return [null, false];
|
||||
const parts = raw.split("|");
|
||||
@@ -35,7 +46,6 @@ function parsePayOrderCookie(raw: string | null): [string | null, boolean] {
|
||||
export function usePayStatusPoll(
|
||||
onPaid: (orderId?: string) => void,
|
||||
onTimeout?: () => void,
|
||||
/** 手机 H5:点击支付后传入的 orderId,直接轮询,不依赖 sessionStorage/cookie */
|
||||
orderIdFromState?: string | null
|
||||
): boolean {
|
||||
const [polling, setPolling] = useState(false);
|
||||
@@ -47,43 +57,101 @@ export function usePayStatusPoll(
|
||||
useEffect(() => {
|
||||
const orderId =
|
||||
orderIdFromState !== undefined
|
||||
? (orderIdFromState?.trim() || null)
|
||||
? orderIdFromState?.trim() || null
|
||||
: (() => {
|
||||
const raw = getCookie(COOKIE_NAME);
|
||||
const [oid, valid] = parsePayOrderCookie(raw);
|
||||
return valid ? oid : null;
|
||||
const cookieRaw = getCookie(COOKIE_NAME);
|
||||
const [cookieOrderId, cookieValid] = parsePayOrderCookie(cookieRaw);
|
||||
if (cookieValid) {
|
||||
return cookieOrderId;
|
||||
}
|
||||
|
||||
const storageRaw = getStorage(STORAGE_NAME);
|
||||
const [storageOrderId, storageValid] = parsePayOrderCookie(storageRaw);
|
||||
return storageValid ? storageOrderId : null;
|
||||
})();
|
||||
|
||||
if (!orderId) {
|
||||
if (orderIdFromState === undefined && getCookie(COOKIE_NAME)) clearCookie(COOKIE_NAME);
|
||||
if (
|
||||
orderIdFromState === undefined &&
|
||||
(getCookie(COOKIE_NAME) || getStorage(STORAGE_NAME))
|
||||
) {
|
||||
clearPendingOrder();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
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 tick = async () => {
|
||||
if (stopped) return;
|
||||
if (inFlight) {
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
|
||||
attempts += 1;
|
||||
if (attempts > MAX_POLLS) {
|
||||
stop();
|
||||
clearPendingOrder();
|
||||
setPolling(false);
|
||||
onTimeoutRef.current?.();
|
||||
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);
|
||||
onPaidRef.current(orderId);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 继续轮询
|
||||
// ignore and continue polling
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
}, POLL_INTERVAL);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
scheduleNext();
|
||||
};
|
||||
|
||||
const scheduleNext = () => {
|
||||
if (stopped) return;
|
||||
timer = window.setTimeout(tick, POLL_INTERVAL_MS);
|
||||
};
|
||||
|
||||
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();
|
||||
};
|
||||
}, [orderIdFromState]);
|
||||
|
||||
return polling;
|
||||
|
||||
67
app/lib/xorpayStatus.ts
Normal file
67
app/lib/xorpayStatus.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
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";
|
||||
const XORPAY_QUERY_TIMEOUT_MS = Number(
|
||||
process.env.XORPAY_QUERY_TIMEOUT_MS || 5000
|
||||
);
|
||||
|
||||
export type XorPayStatusResult = {
|
||||
ok: boolean;
|
||||
paid: boolean;
|
||||
status?: string;
|
||||
error?: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
function buildXorPaySign(orderId: string): string {
|
||||
return createHash("md5")
|
||||
.update(`${orderId}${XORPAY_SECRET}`, "utf8")
|
||||
.digest("hex")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export async function queryXorPayOrderStatus(
|
||||
orderId: string,
|
||||
timeoutMs = XORPAY_QUERY_TIMEOUT_MS
|
||||
): Promise<XorPayStatusResult | null> {
|
||||
const normalizedOrderId = orderId.trim();
|
||||
if (!normalizedOrderId || !XORPAY_AID || !XORPAY_SECRET) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(
|
||||
`${XORPAY_QUERY_URL.replace(/\/$/, "")}/${encodeURIComponent(XORPAY_AID)}`
|
||||
);
|
||||
url.searchParams.set("order_id", normalizedOrderId);
|
||||
url.searchParams.set("sign", buildXorPaySign(normalizedOrderId));
|
||||
|
||||
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 {
|
||||
ok: res.ok,
|
||||
paid: res.ok && (status === "payed" || status === "success"),
|
||||
status,
|
||||
url: url.toString(),
|
||||
error: res.ok ? undefined : `status=${res.status}`,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
paid: false,
|
||||
url: url.toString(),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
59
app/lib/zpayStatus.ts
Normal file
59
app/lib/zpayStatus.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
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";
|
||||
const ZPAY_QUERY_TIMEOUT_MS = Number(
|
||||
process.env.ZPAY_QUERY_TIMEOUT_MS || 5000
|
||||
);
|
||||
|
||||
export type ZPayStatusResult = {
|
||||
ok: boolean;
|
||||
paid: boolean;
|
||||
status?: string;
|
||||
error?: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export async function queryZPayOrderStatus(
|
||||
orderId: string,
|
||||
timeoutMs = ZPAY_QUERY_TIMEOUT_MS
|
||||
): Promise<ZPayStatusResult | 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 {
|
||||
ok: res.ok,
|
||||
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 {
|
||||
ok: false,
|
||||
paid: false,
|
||||
url: url.toString(),
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user