'init'
This commit is contained in:
27
app/lib/auth-cookie.ts
Normal file
27
app/lib/auth-cookie.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
const COOKIE_NAME = "pb_session";
|
||||
export const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
|
||||
|
||||
export { COOKIE_NAME };
|
||||
|
||||
export function getHostFromRequest(request: { headers: { get: (k: string) => string | null } }): string {
|
||||
const host = request.headers.get("host") || request.headers.get("x-forwarded-host") || "";
|
||||
return host.split(",")[0].trim().replace(/:\d+$/, "");
|
||||
}
|
||||
|
||||
export function getCookieOptions(clear = false, requestHost?: string) {
|
||||
const isProd = process.env.NODE_ENV === "production";
|
||||
const domain = process.env.AUTH_COOKIE_DOMAIN?.trim();
|
||||
const opts: Record<string, unknown> = {
|
||||
path: "/",
|
||||
maxAge: clear ? 0 : COOKIE_MAX_AGE,
|
||||
secure: isProd,
|
||||
sameSite: "lax" as const,
|
||||
httpOnly: true,
|
||||
};
|
||||
if (domain && isProd) {
|
||||
opts.domain = domain;
|
||||
} else if (!isProd && requestHost && /^(\d{1,3}\.){3}\d{1,3}$/.test(requestHost)) {
|
||||
opts.domain = requestHost;
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
5
app/lib/env.ts
Normal file
5
app/lib/env.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
const isDev = process.env.NODE_ENV === "development";
|
||||
|
||||
export const SITE_URL =
|
||||
process.env.NEXT_PUBLIC_SITE_URL ||
|
||||
(isDev ? "http://localhost:3002" : "http://localhost:3002");
|
||||
19
app/lib/payEnv.ts
Normal file
19
app/lib/payEnv.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export type PayEnv = "pc" | "h5" | "wechat";
|
||||
|
||||
export function isWeChat(): boolean {
|
||||
if (typeof navigator === "undefined") return false;
|
||||
return /MicroMessenger/i.test(navigator.userAgent);
|
||||
}
|
||||
|
||||
export function isMobile(): boolean {
|
||||
if (typeof navigator === "undefined") return false;
|
||||
return /AppleWebKit.*Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
||||
navigator.userAgent
|
||||
);
|
||||
}
|
||||
|
||||
export function getPayEnv(): PayEnv {
|
||||
if (isWeChat()) return "wechat";
|
||||
if (isMobile()) return "h5";
|
||||
return "pc";
|
||||
}
|
||||
50
app/lib/payment/client.ts
Normal file
50
app/lib/payment/client.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { getPaymentConfig, getJoinPaymentConfig } from "@/config/services.config";
|
||||
|
||||
export type PayChannel = "wxpay" | "alipay";
|
||||
|
||||
export function redirectToPay(params: {
|
||||
user_id: string;
|
||||
return_url: string;
|
||||
total_fee?: number;
|
||||
type?: string;
|
||||
channel: PayChannel;
|
||||
device: "pc" | "h5" | "wechat";
|
||||
useJoinConfig?: boolean;
|
||||
}): void {
|
||||
const baseConfig = getPaymentConfig();
|
||||
const joinConfig = params.useJoinConfig ? getJoinPaymentConfig() : null;
|
||||
const total_fee = params.total_fee ?? joinConfig?.amount ?? baseConfig.defaultAmount;
|
||||
const type = params.type ?? joinConfig?.type ?? baseConfig.defaultType;
|
||||
|
||||
const payForm = document.createElement("form");
|
||||
payForm.method = "POST";
|
||||
payForm.action = "/api/pay";
|
||||
payForm.target = "_self";
|
||||
payForm.style.display = "none";
|
||||
|
||||
const fields: [string, string][] = [
|
||||
["user_id", params.user_id],
|
||||
["return_url", params.return_url],
|
||||
["total_fee", String(total_fee)],
|
||||
["type", type],
|
||||
["channel", params.channel],
|
||||
["device", params.device],
|
||||
["html", "1"],
|
||||
];
|
||||
|
||||
fields.forEach(([k, v]) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "hidden";
|
||||
input.name = k;
|
||||
input.value = v;
|
||||
payForm.appendChild(input);
|
||||
});
|
||||
|
||||
document.body.appendChild(payForm);
|
||||
payForm.submit();
|
||||
}
|
||||
|
||||
export function getDeviceFromEnv(env: "pc" | "h5" | "wechat"): "pc" | "h5" | "wechat" {
|
||||
if (env === "wechat") return "wechat";
|
||||
return env === "pc" ? "pc" : "h5";
|
||||
}
|
||||
4
app/lib/payment/index.ts
Normal file
4
app/lib/payment/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export { redirectToPay, getDeviceFromEnv } from "./client";
|
||||
export { getPayEnv } from "../payEnv";
|
||||
export { usePayStatusPoll } from "./usePayStatusPoll";
|
||||
export type { PayChannel } from "./client";
|
||||
165
app/lib/payment/usePayStatusPoll.ts
Normal file
165
app/lib/payment/usePayStatusPoll.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
const COOKIE_NAME = "join_pay_order";
|
||||
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;
|
||||
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
|
||||
function clearCookie(name: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
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 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];
|
||||
return [orderId, true];
|
||||
}
|
||||
|
||||
export function usePayStatusPoll(onPaid: (orderId: string) => void): boolean {
|
||||
const [polling, setPolling] = useState(false);
|
||||
const onPaidRef = useRef(onPaid);
|
||||
onPaidRef.current = onPaid;
|
||||
|
||||
useEffect(() => {
|
||||
const urlOrderId =
|
||||
typeof window !== "undefined"
|
||||
? new URLSearchParams(window.location.search).get("order_id") || ""
|
||||
: "";
|
||||
const cookieRaw = getCookie(COOKIE_NAME);
|
||||
const [cookieOrderId, cookieValid] = parsePendingOrder(cookieRaw);
|
||||
const storageRaw = getStorage(STORAGE_NAME);
|
||||
const [storageOrderId, storageValid] = parsePendingOrder(storageRaw);
|
||||
let orderId = cookieValid ? cookieOrderId : storageValid ? storageOrderId : null;
|
||||
let activeRaw = cookieValid ? cookieRaw : storageValid ? storageRaw : null;
|
||||
if (!orderId && urlOrderId.trim()) {
|
||||
orderId = urlOrderId.trim();
|
||||
activeRaw = `${orderId}|${Date.now()}`;
|
||||
persistPendingOrder(activeRaw);
|
||||
}
|
||||
|
||||
if (!orderId) {
|
||||
if (cookieRaw || storageRaw) {
|
||||
clearPendingOrder();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeRaw) {
|
||||
persistPendingOrder(activeRaw);
|
||||
}
|
||||
|
||||
setPolling(true);
|
||||
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!)}`,
|
||||
{ cache: "no-store" }
|
||||
);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (data?.ok && data?.paid) {
|
||||
stop();
|
||||
clearPendingOrder();
|
||||
setPolling(false);
|
||||
onPaidRef.current(orderId!);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// keep polling
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
40
app/lib/pocketbase/admin.ts
Normal file
40
app/lib/pocketbase/admin.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
|
||||
let cachedToken: { token: string; expiresAt: number } | null = null;
|
||||
const TOKEN_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export async function getAdminToken(): Promise<string | null> {
|
||||
if (cachedToken && Date.now() < cachedToken.expiresAt) {
|
||||
return cachedToken.token;
|
||||
}
|
||||
|
||||
const email = process.env.POCKETBASE_EMAIL;
|
||||
const password = process.env.POCKETBASE_PASSWORD;
|
||||
if (!email || !password) return null;
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const base = pb.url.replace(/\/$/, "");
|
||||
const body = JSON.stringify({ identity: email, password });
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
|
||||
const endpoints = [
|
||||
`${base}/api/collections/_superusers/auth-with-password`,
|
||||
`${base}/api/admins/auth-with-password`,
|
||||
];
|
||||
|
||||
for (const url of endpoints) {
|
||||
try {
|
||||
const res = await fetch(url, { method: "POST", headers, body });
|
||||
if (!res.ok) continue;
|
||||
const data = await res.json();
|
||||
const token = data?.token;
|
||||
if (token) {
|
||||
cachedToken = { token, expiresAt: Date.now() + TOKEN_TTL_MS };
|
||||
return token;
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
95
app/lib/pocketbase/auth.ts
Normal file
95
app/lib/pocketbase/auth.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
import { PB_STORAGE_KEYS } from "./constants";
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface AuthResult {
|
||||
token: string;
|
||||
record: AuthUser;
|
||||
}
|
||||
|
||||
function getPBUrl(): string {
|
||||
return getPocketBaseConfig().url;
|
||||
}
|
||||
|
||||
export async function pbLogin(identity: string, password: string): Promise<AuthResult> {
|
||||
const res = await fetch(`${getPBUrl()}/api/collections/users/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ identity, password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(err?.message || "登录失败");
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!data?.token) throw new Error("登录响应异常");
|
||||
return { token: data.token, record: data.record };
|
||||
}
|
||||
|
||||
export async function pbRegister(
|
||||
email: string,
|
||||
password: string,
|
||||
passwordConfirm: string
|
||||
): Promise<AuthResult> {
|
||||
const config = getPocketBaseConfig();
|
||||
const res = await fetch(
|
||||
`${getPBUrl()}/api/collections/${config.usersCollection}/records`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password, passwordConfirm }),
|
||||
}
|
||||
);
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(err?.message || "注册失败");
|
||||
}
|
||||
return pbLogin(email, password);
|
||||
}
|
||||
|
||||
export function pbSaveAuth(token: string, record: AuthUser): void {
|
||||
if (typeof window === "undefined") return;
|
||||
localStorage.setItem(PB_STORAGE_KEYS.token, token);
|
||||
localStorage.setItem(PB_STORAGE_KEYS.user, JSON.stringify(record));
|
||||
}
|
||||
|
||||
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", credentials: "include" });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent("auth:updated"));
|
||||
}
|
||||
|
||||
export function getStoredUser(): AuthUser | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const raw = localStorage.getItem(PB_STORAGE_KEYS.user);
|
||||
if (!raw) return null;
|
||||
const user = JSON.parse(raw);
|
||||
if (!user?.id || !user?.email) return null;
|
||||
return user;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getStoredToken(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return localStorage.getItem(PB_STORAGE_KEYS.token);
|
||||
}
|
||||
2
app/lib/pocketbase/config.ts
Normal file
2
app/lib/pocketbase/config.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { getPocketBaseConfig } from "@/config/services.config";
|
||||
export type { PocketBaseConfig } from "@/config/services.config";
|
||||
4
app/lib/pocketbase/constants.ts
Normal file
4
app/lib/pocketbase/constants.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export const PB_STORAGE_KEYS = {
|
||||
token: "pb_token",
|
||||
user: "pb_user",
|
||||
} as const;
|
||||
11
app/lib/pocketbase/index.ts
Normal file
11
app/lib/pocketbase/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export {
|
||||
pbLogin,
|
||||
pbRegister,
|
||||
pbSaveAuth,
|
||||
pbLogout,
|
||||
getStoredUser,
|
||||
getStoredToken,
|
||||
} from "./auth";
|
||||
export type { AuthUser, AuthResult } from "./auth";
|
||||
export { PB_STORAGE_KEYS } from "./constants";
|
||||
export { getPocketBaseConfig } from "./config";
|
||||
92
app/lib/salonApi.ts
Normal file
92
app/lib/salonApi.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { getPaymentConfig } from "@/config/services.config";
|
||||
|
||||
function isPrivateHost(hostname: string): boolean {
|
||||
if (!hostname) return false;
|
||||
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") return true;
|
||||
if (/^10\./.test(hostname) || /^192\.168\./.test(hostname)) return true;
|
||||
const match = hostname.match(/^172\.(\d{1,2})\./);
|
||||
if (!match) return false;
|
||||
return Number(match[1]) >= 16 && Number(match[1]) <= 31;
|
||||
}
|
||||
|
||||
function getRequestHostname(request: NextRequest): string {
|
||||
const host = request.headers.get("x-forwarded-host") || request.headers.get("host") || "";
|
||||
return host.split(",")[0].trim().split(":")[0];
|
||||
}
|
||||
|
||||
/** 与 cnomadcna 一致:多 URL 回退,开发/内网优先本地 */
|
||||
function getApiCandidates(request: NextRequest): string[] {
|
||||
const config = getPaymentConfig();
|
||||
const hostname = getRequestHostname(request);
|
||||
const port = process.env.PAYJSAPI_PORT || "8007";
|
||||
const localUrl = `http://${hostname || "127.0.0.1"}:${port}`;
|
||||
const configuredUrl = config.apiUrl.replace(/\/$/, "");
|
||||
|
||||
const preferLocal = process.env.NODE_ENV === "development" || isPrivateHost(hostname);
|
||||
const urls = preferLocal ? [localUrl, configuredUrl] : [configuredUrl, localUrl];
|
||||
return urls.filter((u, i) => u && urls.indexOf(u) === i);
|
||||
}
|
||||
|
||||
const TIMEOUT_MS = 20000;
|
||||
|
||||
export async function postSalonApi(
|
||||
request: NextRequest,
|
||||
path: string,
|
||||
body: unknown
|
||||
): Promise<{ status: number; data: unknown }> {
|
||||
const candidates = getApiCandidates(request);
|
||||
if (!candidates.length) throw new Error("PAYMENT_API_URL 未配置");
|
||||
|
||||
let lastError: unknown = null;
|
||||
for (const apiUrl of candidates) {
|
||||
const url = `${apiUrl}${path}`;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timeoutId);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok || (res.status !== 404 && res.status < 500)) {
|
||||
return { status: res.status, data };
|
||||
}
|
||||
lastError = data?.detail || data?.error || `HTTP ${res.status}`;
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error ? lastError : new Error("payjsapi 请求失败");
|
||||
}
|
||||
|
||||
export async function getSalonApi(
|
||||
request: NextRequest,
|
||||
path: string
|
||||
): Promise<{ status: number; data: unknown }> {
|
||||
const candidates = getApiCandidates(request);
|
||||
if (!candidates.length) throw new Error("PAYMENT_API_URL 未配置");
|
||||
|
||||
let lastError: unknown = null;
|
||||
for (const apiUrl of candidates) {
|
||||
const url = `${apiUrl}${path}`;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(url, { cache: "no-store", signal: controller.signal });
|
||||
clearTimeout(timeoutId);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok) return { status: res.status, data };
|
||||
lastError = data?.detail || data?.error || `HTTP ${res.status}`;
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error ? lastError : new Error("payjsapi 请求失败");
|
||||
}
|
||||
Reference in New Issue
Block a user