's'调试支付

This commit is contained in:
eric
2026-03-08 06:43:48 -05:00
parent b99fba1c5a
commit 1f4473cb04
35 changed files with 1794 additions and 178 deletions

67
app/lib/minio/client.ts Normal file
View File

@@ -0,0 +1,67 @@
/**
* MinIO 客户端封装 - 上传、下载等操作
* 通过 getMinioConfig() 获取配置,支持主题覆盖
*/
import * as Minio from "minio";
import { getMinioConfig } from "./config";
import { getThemeConfig } from "@/config/site.config";
/** 获取 MinIO 客户端实例(使用主题配置) */
export function getMinioClient(): Minio.Client {
const theme = getThemeConfig();
const cfg = getMinioConfig(theme.services?.minio);
return new Minio.Client({
endPoint: cfg.endPoint,
port: cfg.port,
useSSL: cfg.useSSL,
accessKey: cfg.accessKey,
secretKey: cfg.secretKey,
pathStyle: true,
region: cfg.region,
});
}
export interface UploadResult {
url: string;
objectKey: string;
}
/**
* 上传文件到 MinIO
* @param buffer 文件内容
* @param objectKey 对象键(含路径,如 joins/xxx.jpg
* @param contentType MIME 类型
*/
export async function uploadBuffer(
buffer: Buffer,
objectKey: string,
contentType: string = "application/octet-stream"
): Promise<UploadResult> {
const theme = getThemeConfig();
const cfg = getMinioConfig(theme.services?.minio);
if (!cfg.enabled) {
throw new Error("MinIO 存储未启用");
}
const client = getMinioClient();
await client.putObject(cfg.bucket, objectKey, buffer, buffer.length, {
"Content-Type": contentType,
});
const url = `${cfg.publicUrl}/${objectKey}`;
return { url, objectKey };
}
/**
* 生成上传用的对象键
* @param ext 文件扩展名
*/
export function generateObjectKey(ext: string): string {
const theme = getThemeConfig();
const cfg = getMinioConfig(theme.services?.minio);
const prefix = cfg.uploadPrefix.replace(/\/$/, "");
return `${prefix}/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
}

2
app/lib/minio/config.ts Normal file
View File

@@ -0,0 +1,2 @@
export { getMinioConfig } from "@/config/services.config";
export type { MinioConfig } from "@/config/services.config";

13
app/lib/minio/index.ts Normal file
View File

@@ -0,0 +1,13 @@
/**
* MinIO 存储组件化封装
* 通过 config/services.config 和主题配置,支持多环境、多主题
*/
export { getMinioConfig } from "./config";
export type { MinioConfig } from "./config";
export {
getMinioClient,
uploadBuffer,
generateObjectKey,
} from "./client";
export type { UploadResult } from "./client";

57
app/lib/payment/client.ts Normal file
View File

@@ -0,0 +1,57 @@
/**
* 支付客户端 - 封装支付 API 调用
* 用于前端发起支付、跳转支付页
*/
import { getPaymentConfig, getJoinPaymentConfig } from "@/config/services.config";
import type { PayChannel, PayEnv } from "./types";
/** 发起支付并跳转(表单 POST 到 /api/pay */
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();
}
/** 根据 PayEnv 确定 device微信内用 wechat 走收银台表单payurl2 仅支持微信外 */
export function getDeviceFromEnv(env: PayEnv): "pc" | "h5" | "wechat" {
if (env === "wechat") return "wechat";
return env === "pc" ? "pc" : "h5";
}

View File

@@ -0,0 +1,2 @@
export { getPaymentConfig, getServicesConfig } from "@/config/services.config";
export type { PaymentConfig } from "@/config/services.config";

4
app/lib/payment/index.ts Normal file
View File

@@ -0,0 +1,4 @@
export { redirectToPay, getDeviceFromEnv } from "./client";
export { getPayEnv, getRecommendedChannel, mustUseWxPay } from "../payEnv";
export type { PayChannel, PayEnv, CreatePayParams, PayRedirectParams } from "./types";
export { getPaymentConfig } from "./config";

21
app/lib/payment/types.ts Normal file
View File

@@ -0,0 +1,21 @@
export type PayChannel = "alipay" | "wxpay";
export type PayEnv = "pc" | "h5" | "wechat";
export interface CreatePayParams {
user_id: string;
return_url: string;
total_fee?: number;
type?: string;
channel?: PayChannel;
device?: "pc" | "h5" | "wechat";
}
export interface PayRedirectParams {
user_id: string;
total_fee: number;
type: string;
channel: PayChannel;
return_url: string;
device: "pc" | "h5" | "wechat";
html?: "1";
}

View File

@@ -0,0 +1,76 @@
/**
* 微信 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 分钟
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`;
}
/** 解析 cookieorder_id|timestamp返回 [orderId, isValid]。无时间戳视为过期并清除 */
function parsePayOrderCookie(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 分钟
return [orderId, true];
}
export function usePayStatusPoll(onPaid: () => void): boolean {
const [polling, setPolling] = useState(false);
const onPaidRef = useRef(onPaid);
onPaidRef.current = onPaid;
useEffect(() => {
const raw = getCookie(COOKIE_NAME);
const [orderId, isValid] = parsePayOrderCookie(raw);
if (!orderId || !isValid) {
if (raw) clearCookie(COOKIE_NAME);
return;
}
setPolling(true);
let count = 0;
const timer = setInterval(async () => {
count++;
if (count > MAX_POLLS) {
clearInterval(timer);
clearCookie(COOKIE_NAME);
setPolling(false);
return;
}
try {
const res = await fetch(`/api/pay/status?order_id=${encodeURIComponent(orderId)}`);
const data = await res.json();
if (data?.ok && data?.paid) {
clearInterval(timer);
clearCookie(COOKIE_NAME);
setPolling(false);
onPaidRef.current();
}
} catch {
// 继续轮询
}
}, POLL_INTERVAL);
return () => clearInterval(timer);
}, []);
return polling;
}

View File

@@ -0,0 +1,94 @@
/**
* PocketBase 认证服务 - 客户端使用
* 登录、注册、登出、获取当前用户
*/
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;
}
/** 获取 PocketBase 基础 URL客户端用 NEXT_PUBLIC_ 前缀) */
function getPBUrl(): string {
return getPocketBaseConfig().url;
}
/** 登录 */
export async function pbLogin(identity: string, password: string): Promise<AuthResult> {
const url = getPBUrl();
const res = await fetch(`${url}/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 url = getPBUrl();
const config = getPocketBaseConfig();
const res = await fetch(`${url}/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);
}
/** 保存认证信息到 localStorage */
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 function pbLogout(): void {
if (typeof window === "undefined") return;
localStorage.removeItem(PB_STORAGE_KEYS.token);
localStorage.removeItem(PB_STORAGE_KEYS.user);
}
/** 获取当前存储的用户邮箱 */
export function getStoredUserEmail(): string | 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);
return user?.email ?? null;
} catch {
return null;
}
}
/** 获取存储的 token用于 API 请求) */
export function getStoredToken(): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem(PB_STORAGE_KEYS.token);
}

View File

@@ -0,0 +1,2 @@
export { getPocketBaseConfig, getServicesConfig } from "@/config/services.config";
export type { PocketBaseConfig } from "@/config/services.config";

View File

@@ -0,0 +1,5 @@
/** localStorage 存储 key */
export const PB_STORAGE_KEYS = {
token: "pb_token",
user: "pb_user",
} as const;

View File

@@ -0,0 +1,11 @@
export {
pbLogin,
pbRegister,
pbSaveAuth,
pbLogout,
getStoredUserEmail,
getStoredToken,
} from "./auth";
export type { AuthUser, AuthResult } from "./auth";
export { PB_STORAGE_KEYS } from "./constants";
export { getPocketBaseConfig } from "./config";

86
app/lib/theme-data.ts Normal file
View File

@@ -0,0 +1,86 @@
/**
* 主题数据加载器 - 根据 CURRENT_THEME 加载对应主题的内容
* 新增主题1. 在 config/site.config.ts 添加 THEME_CONFIGS
* 2. 在 content/themes/[theme-id]/ 下添加 messages 和 data
* 3. 在本文件 switch 中添加 case
*/
import { CURRENT_THEME, THEME_IDS, type ThemeId } from "@/config";
export type Locale = "zh" | "en";
export type ToolsCategory = {
id: string;
icon: string;
title: string;
color: string;
bg: string;
text: string;
tools: Array<{ name: string; desc: string; href: string }>;
};
/** 加载当前主题的 messages */
export async function getThemeMessages(
locale: Locale
): Promise<Record<string, unknown>> {
const theme = CURRENT_THEME;
switch (theme) {
case "digital-nomad": {
const mod =
locale === "zh"
? await import("@/content/themes/digital-nomad/messages/zh.json")
: await import("@/content/themes/digital-nomad/messages/en.json");
return mod.default;
}
case "solo-company":
case "tiktok-ops":
case "indie-dev":
// 新主题暂无内容时回退到 digital-nomad
return getThemeMessagesFallback(locale);
default:
return getThemeMessagesFallback(locale);
}
}
async function getThemeMessagesFallback(
locale: Locale
): Promise<Record<string, unknown>> {
const mod =
locale === "zh"
? await import("@/content/themes/digital-nomad/messages/zh.json")
: await import("@/content/themes/digital-nomad/messages/en.json");
return mod.default;
}
/** 加载当前主题的 tools 数据 */
export async function getThemeToolsData(): Promise<{
categories: ToolsCategory[];
}> {
const theme = CURRENT_THEME;
switch (theme) {
case "digital-nomad": {
const mod = await import(
"@/content/themes/digital-nomad/data/tools.json"
);
return mod.default;
}
case "solo-company":
case "tiktok-ops":
case "indie-dev":
return getThemeToolsDataFallback();
default:
return getThemeToolsDataFallback();
}
}
async function getThemeToolsDataFallback(): Promise<{
categories: ToolsCategory[];
}> {
const mod = await import(
"@/content/themes/digital-nomad/data/tools.json"
);
return mod.default;
}
export { CURRENT_THEME, THEME_IDS };
export type { ThemeId };