;'s'
This commit is contained in:
@@ -1,12 +1,11 @@
|
|||||||
/**
|
/**
|
||||||
* 支付状态轮询:点击支付后轮询,支付成功刷新,超时重置
|
* 支付状态轮询
|
||||||
* 优先使用 sessionStorage(pay_pending_order),其次 cookie
|
* - 手机 H5:传入 orderId(点击支付后由 state 传入),直接轮询,不依赖 sessionStorage/cookie
|
||||||
|
* - PC/微信:不传 orderId,使用 cookie 轮询(兼容旧逻辑)
|
||||||
*/
|
*/
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
const COOKIE_NAME = "nomadvip_pay_order";
|
const COOKIE_NAME = "nomadvip_pay_order";
|
||||||
const SESSION_KEY_ORDER = "pay_pending_order";
|
|
||||||
const SESSION_KEY_TS = "pay_pending_ts";
|
|
||||||
const POLL_INTERVAL = 2000;
|
const POLL_INTERVAL = 2000;
|
||||||
const MAX_POLLS = 160; // ~5 分钟
|
const MAX_POLLS = 160; // ~5 分钟
|
||||||
const MAX_AGE_MS = 15 * 60 * 1000;
|
const MAX_AGE_MS = 15 * 60 * 1000;
|
||||||
@@ -22,29 +21,6 @@ function clearCookie(name: string): void {
|
|||||||
document.cookie = `${name}=; path=/; max-age=0`;
|
document.cookie = `${name}=; path=/; max-age=0`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getSessionOrder(): [string | null, boolean] {
|
|
||||||
if (typeof window === "undefined") return [null, false];
|
|
||||||
const orderId = sessionStorage.getItem(SESSION_KEY_ORDER)?.trim() || null;
|
|
||||||
const ts = sessionStorage.getItem(SESSION_KEY_TS);
|
|
||||||
const timestamp = ts ? parseInt(ts, 10) : NaN;
|
|
||||||
if (!orderId) return [null, false];
|
|
||||||
if (Number.isNaN(timestamp)) return [orderId, true];
|
|
||||||
if (Date.now() - timestamp > MAX_AGE_MS) return [orderId, false];
|
|
||||||
return [orderId, true];
|
|
||||||
}
|
|
||||||
|
|
||||||
function setSessionOrder(orderId: string): void {
|
|
||||||
if (typeof window === "undefined") return;
|
|
||||||
sessionStorage.setItem(SESSION_KEY_ORDER, orderId);
|
|
||||||
sessionStorage.setItem(SESSION_KEY_TS, String(Date.now()));
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearSessionOrder(): void {
|
|
||||||
if (typeof window === "undefined") return;
|
|
||||||
sessionStorage.removeItem(SESSION_KEY_ORDER);
|
|
||||||
sessionStorage.removeItem(SESSION_KEY_TS);
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePayOrderCookie(raw: string | null): [string | null, boolean] {
|
function parsePayOrderCookie(raw: string | null): [string | null, boolean] {
|
||||||
if (!raw?.trim()) return [null, false];
|
if (!raw?.trim()) return [null, false];
|
||||||
const parts = raw.split("|");
|
const parts = raw.split("|");
|
||||||
@@ -56,20 +32,12 @@ function parsePayOrderCookie(raw: string | null): [string | null, boolean] {
|
|||||||
return [orderId, true];
|
return [orderId, true];
|
||||||
}
|
}
|
||||||
|
|
||||||
function getOrderIdToPoll(): [string | null, "session" | "cookie" | null] {
|
export function usePayStatusPoll(
|
||||||
const [sessionOrder, sessionValid] = getSessionOrder();
|
onPaid: (orderId?: string) => void,
|
||||||
if (sessionOrder && sessionValid) return [sessionOrder, "session"];
|
onTimeout?: () => void,
|
||||||
const raw = getCookie(COOKIE_NAME);
|
/** 手机 H5:点击支付后传入的 orderId,直接轮询,不依赖 sessionStorage/cookie */
|
||||||
const [cookieOrder, cookieValid] = parsePayOrderCookie(raw);
|
orderIdFromState?: string | null
|
||||||
if (cookieOrder && cookieValid) return [cookieOrder, "cookie"];
|
): boolean {
|
||||||
return [null, null];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setPayPendingOrder(orderId: string): void {
|
|
||||||
setSessionOrder(orderId);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function usePayStatusPoll(onPaid: (orderId?: string) => void, onTimeout?: () => void): boolean {
|
|
||||||
const [polling, setPolling] = useState(false);
|
const [polling, setPolling] = useState(false);
|
||||||
const onPaidRef = useRef(onPaid);
|
const onPaidRef = useRef(onPaid);
|
||||||
const onTimeoutRef = useRef(onTimeout);
|
const onTimeoutRef = useRef(onTimeout);
|
||||||
@@ -77,10 +45,16 @@ export function usePayStatusPoll(onPaid: (orderId?: string) => void, onTimeout?:
|
|||||||
onTimeoutRef.current = onTimeout;
|
onTimeoutRef.current = onTimeout;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const [orderId] = getOrderIdToPoll();
|
const orderId =
|
||||||
|
orderIdFromState !== undefined
|
||||||
|
? (orderIdFromState?.trim() || null)
|
||||||
|
: (() => {
|
||||||
|
const raw = getCookie(COOKIE_NAME);
|
||||||
|
const [oid, valid] = parsePayOrderCookie(raw);
|
||||||
|
return valid ? oid : null;
|
||||||
|
})();
|
||||||
if (!orderId) {
|
if (!orderId) {
|
||||||
const raw = getCookie(COOKIE_NAME);
|
if (orderIdFromState === undefined && getCookie(COOKIE_NAME)) clearCookie(COOKIE_NAME);
|
||||||
if (raw) clearCookie(COOKIE_NAME);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +64,6 @@ export function usePayStatusPoll(onPaid: (orderId?: string) => void, onTimeout?:
|
|||||||
count++;
|
count++;
|
||||||
if (count > MAX_POLLS) {
|
if (count > MAX_POLLS) {
|
||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
clearSessionOrder();
|
|
||||||
clearCookie(COOKIE_NAME);
|
clearCookie(COOKIE_NAME);
|
||||||
setPolling(false);
|
setPolling(false);
|
||||||
onTimeoutRef.current?.();
|
onTimeoutRef.current?.();
|
||||||
@@ -101,7 +74,6 @@ export function usePayStatusPoll(onPaid: (orderId?: string) => void, onTimeout?:
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data?.ok && data?.paid) {
|
if (data?.ok && data?.paid) {
|
||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
clearSessionOrder();
|
|
||||||
clearCookie(COOKIE_NAME);
|
clearCookie(COOKIE_NAME);
|
||||||
setPolling(false);
|
setPolling(false);
|
||||||
onPaidRef.current(orderId);
|
onPaidRef.current(orderId);
|
||||||
@@ -112,7 +84,7 @@ export function usePayStatusPoll(onPaid: (orderId?: string) => void, onTimeout?:
|
|||||||
}, POLL_INTERVAL);
|
}, POLL_INTERVAL);
|
||||||
|
|
||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, []);
|
}, [orderIdFromState]);
|
||||||
|
|
||||||
return polling;
|
return polling;
|
||||||
}
|
}
|
||||||
|
|||||||
62
app/page.tsx
62
app/page.tsx
@@ -8,7 +8,7 @@ import { indexMd } from "./index-content";
|
|||||||
import styles from "./index.module.css";
|
import styles from "./index.module.css";
|
||||||
import { getPayEnv, getDeviceFromEnv } from "@/app/lib/payEnv";
|
import { getPayEnv, getDeviceFromEnv } from "@/app/lib/payEnv";
|
||||||
import { getPaymentConfig } from "@/config/services.config";
|
import { getPaymentConfig } from "@/config/services.config";
|
||||||
import { usePayStatusPoll, setPayPendingOrder } from "@/app/lib/usePayStatusPoll";
|
import { usePayStatusPoll } from "@/app/lib/usePayStatusPoll";
|
||||||
|
|
||||||
const PB_URL =
|
const PB_URL =
|
||||||
process.env.NEXT_PUBLIC_POCKETBASE_URL || "https://pocketbase.hackrobot.cn";
|
process.env.NEXT_PUBLIC_POCKETBASE_URL || "https://pocketbase.hackrobot.cn";
|
||||||
@@ -51,14 +51,14 @@ function redirectToPayZpay(params: {
|
|||||||
form.submit();
|
form.submit();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** H5 手机:fetch 获取 order_id + 支付参数,写入 sessionStorage 后提交表单,支持轮询 */
|
/** H5 手机:fetch 获取 order_id,新标签页打开支付,当前页保持可轮询 */
|
||||||
async function redirectToPayZpayH5(params: {
|
async function redirectToPayZpayH5(params: {
|
||||||
user_id: string;
|
user_id: string;
|
||||||
return_url: string;
|
return_url: string;
|
||||||
total_fee: number;
|
total_fee: number;
|
||||||
type: string;
|
type: string;
|
||||||
channel: "alipay" | "wxpay";
|
channel: "alipay" | "wxpay";
|
||||||
}) {
|
}): Promise<string | null> {
|
||||||
const res = await fetch("/api/pay", {
|
const res = await fetch("/api/pay", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -72,18 +72,17 @@ async function redirectToPayZpayH5(params: {
|
|||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
if (!data?.ok || !data?.params || !data?.payUrl) {
|
if (!data?.ok || !data?.params || !data?.payUrl) {
|
||||||
alert(data?.error || "支付发起失败");
|
alert(data?.error || "支付发起失败");
|
||||||
return;
|
return null;
|
||||||
}
|
}
|
||||||
const orderId = data?.order_id?.trim();
|
const orderId = data?.order_id?.trim() || null;
|
||||||
if (orderId) setPayPendingOrder(orderId);
|
|
||||||
if (data?.redirect_url) {
|
if (data?.redirect_url) {
|
||||||
window.location.href = data.redirect_url;
|
window.open(data.redirect_url, "_blank");
|
||||||
return;
|
return orderId;
|
||||||
}
|
}
|
||||||
const form = document.createElement("form");
|
const form = document.createElement("form");
|
||||||
form.method = "POST";
|
form.method = "POST";
|
||||||
form.action = data.payUrl;
|
form.action = data.payUrl;
|
||||||
form.target = "_self";
|
form.target = "_blank";
|
||||||
form.style.display = "none";
|
form.style.display = "none";
|
||||||
for (const [k, v] of Object.entries(data.params as Record<string, string>)) {
|
for (const [k, v] of Object.entries(data.params as Record<string, string>)) {
|
||||||
if (v == null) continue;
|
if (v == null) continue;
|
||||||
@@ -95,9 +94,11 @@ async function redirectToPayZpayH5(params: {
|
|||||||
}
|
}
|
||||||
document.body.appendChild(form);
|
document.body.appendChild(form);
|
||||||
form.submit();
|
form.submit();
|
||||||
|
document.body.removeChild(form);
|
||||||
|
return orderId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 微信内:fetch 获取 xorpay 参数,写入 order_id 后提交表单到收银台,无中转页 */
|
/** 微信内:fetch 获取 xorpay 参数,直接提交表单到收银台,无中转页 */
|
||||||
async function payWechatXorpay(params: {
|
async function payWechatXorpay(params: {
|
||||||
user_id: string;
|
user_id: string;
|
||||||
return_url: string;
|
return_url: string;
|
||||||
@@ -121,8 +122,6 @@ async function payWechatXorpay(params: {
|
|||||||
alert(data?.error || "支付发起失败");
|
alert(data?.error || "支付发起失败");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const orderId = data?.order_id?.trim();
|
|
||||||
if (orderId) setPayPendingOrder(orderId);
|
|
||||||
const form = document.createElement("form");
|
const form = document.createElement("form");
|
||||||
form.method = "POST";
|
form.method = "POST";
|
||||||
form.action = data.payUrl;
|
form.action = data.payUrl;
|
||||||
@@ -159,6 +158,7 @@ export default function Home() {
|
|||||||
const [paidType, setPaidType] = useState<string | null>(null);
|
const [paidType, setPaidType] = useState<string | null>(null);
|
||||||
const [userName, setUserName] = useState<string | null>(null);
|
const [userName, setUserName] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [payPendingOrderId, setPayPendingOrderId] = useState<string | null>(null);
|
||||||
const contentRef = useRef<HTMLDivElement>(null);
|
const contentRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
const savePaidType = useCallback((type: string | null) => {
|
const savePaidType = useCallback((type: string | null) => {
|
||||||
@@ -250,7 +250,7 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handlePay = useCallback(() => {
|
const handlePay = useCallback(async () => {
|
||||||
const userId = getOrCreateUserId();
|
const userId = getOrCreateUserId();
|
||||||
const returnUrl = `${window.location.origin}/paid`;
|
const returnUrl = `${window.location.origin}/paid`;
|
||||||
const env = getPayEnv();
|
const env = getPayEnv();
|
||||||
@@ -260,7 +260,8 @@ export default function Home() {
|
|||||||
if (device === "wechat" && WECHAT_PAY_PROVIDER === "xorpay") {
|
if (device === "wechat" && WECHAT_PAY_PROVIDER === "xorpay") {
|
||||||
payWechatXorpay(base);
|
payWechatXorpay(base);
|
||||||
} else if (device === "h5") {
|
} else if (device === "h5") {
|
||||||
redirectToPayZpayH5(base);
|
const orderId = await redirectToPayZpayH5(base);
|
||||||
|
if (orderId) setPayPendingOrderId(orderId);
|
||||||
} else {
|
} else {
|
||||||
redirectToPayZpay({ ...base, device });
|
redirectToPayZpay({ ...base, device });
|
||||||
}
|
}
|
||||||
@@ -274,18 +275,27 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
}, [userName]);
|
}, [userName]);
|
||||||
|
|
||||||
// 微信/手机 H5 支付完成后可能不跳转,轮询检测到已支付则刷新
|
const env = getPayEnv();
|
||||||
usePayStatusPoll((orderId) => {
|
const device = getDeviceFromEnv(env);
|
||||||
let uid = getStorage("userId");
|
const isH5 = device === "h5";
|
||||||
if (!uid && orderId?.includes("_order_")) {
|
usePayStatusPoll(
|
||||||
const prefix = orderId.split("_order_")[0];
|
(orderId) => {
|
||||||
const parts = prefix.split("_");
|
let uid = getStorage("userId");
|
||||||
if (parts.length >= 2) uid = parts.slice(0, -1).join("_");
|
if (!uid && orderId?.includes("_order_")) {
|
||||||
}
|
const prefix = orderId.split("_order_")[0];
|
||||||
if (uid) saveUserName(uid);
|
const parts = prefix.split("_");
|
||||||
savePaidType("vip");
|
if (parts.length >= 2) uid = parts.slice(0, -1).join("_");
|
||||||
window.location.reload();
|
}
|
||||||
});
|
if (uid) saveUserName(uid);
|
||||||
|
savePaidType("vip");
|
||||||
|
if (isH5) setPayPendingOrderId(null);
|
||||||
|
window.location.reload();
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
if (isH5) setPayPendingOrderId(null);
|
||||||
|
},
|
||||||
|
isH5 ? payPendingOrderId : undefined
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
|||||||
Reference in New Issue
Block a user