'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

View File

@@ -4,18 +4,7 @@ import { useState, useEffect } from "react";
import { VideoCard } from "./VideoCard";
import { useVideoProgress } from "./useVideoProgress";
import AuthModal from "../../components/AuthModal";
function getStoredUser(): string | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem("pb_user");
if (!raw) return null;
const user = JSON.parse(raw);
return user?.email ?? null;
} catch {
return null;
}
}
import { getStoredUserEmail, pbLogout } from "@/app/lib/pocketbase";
/* ─── data ─── */
@@ -166,12 +155,11 @@ export default function CoursePage() {
const { markCompleted, isCompleted, isPartCompleted } = useVideoProgress();
useEffect(() => {
setUserEmail(getStoredUser());
setUserEmail(getStoredUserEmail());
}, []);
const handleLogout = () => {
localStorage.removeItem("pb_token");
localStorage.removeItem("pb_user");
pbLogout();
setUserEmail(null);
};

View File

@@ -2,7 +2,7 @@
import { useEffect, useState, useRef, useCallback } from "react";
import { Link } from "@/i18n/navigation";
import type { EbookData } from "../lib/ebook";
import type { EbookData } from "@/app/lib/ebook";
import "github-markdown-css/github-markdown.css";
import styles from "./ebook.module.css";

View File

@@ -2,7 +2,15 @@
import { useState, useRef, useEffect, type FormEvent, type ChangeEvent } from "react";
import { Link } from "@/i18n/navigation";
import { getPayEnv, getRecommendedChannel, mustUseWxPay, type PayChannel, type PayEnv } from "../../lib/payEnv";
import {
getPayEnv,
getRecommendedChannel,
mustUseWxPay,
redirectToPay,
getDeviceFromEnv,
} from "@/app/lib/payment";
import { usePayStatusPoll } from "@/app/lib/payment/usePayStatusPoll";
import type { PayChannel, PayEnv } from "@/app/lib/payment";
const genderOptions = ["男", "女"];
const singleOptions = ["单身", "恋爱中", "已婚"];
@@ -55,6 +63,9 @@ export default function JoinPage() {
}
}, []);
// 微信 H5 支付完成后可能不跳转,后台静默轮询,检测到已支付则显示成功页
usePayStatusPoll(() => setSubmitted(true));
useEffect(() => {
if (typeof window === "undefined") return;
const env = getPayEnv();
@@ -86,33 +97,18 @@ export default function JoinPage() {
}
setSubmitting(false);
setPayRedirecting(true);
const returnUrl = `${window.location.origin}${window.location.pathname}?paid=1`;
const payForm = document.createElement("form");
payForm.method = "POST";
payForm.action = "/api/pay";
payForm.target = "_self";
payForm.style.display = "none";
// Z-Pay return_url 不支持带参数,使用 /join/paid 专用路径
const returnUrl = `${window.location.origin}${window.location.pathname}/paid`;
const env = getPayEnv();
const channel = mustUseWxPay(env) ? "wxpay" : payChannel;
const device = env === "pc" ? "pc" : "h5"; // PC 跳转 payurlH5/微信 用 payurl/payurl2
const fields: [string, string][] = [
["user_id", userId],
["total_fee", "80"],
["type", "meetup"],
["channel", channel],
["device", device],
["return_url", returnUrl],
["html", "1"],
];
fields.forEach(([k, v]) => {
const input = document.createElement("input");
input.type = "hidden";
input.name = k;
input.value = v;
payForm.appendChild(input);
const device = getDeviceFromEnv(env);
redirectToPay({
user_id: userId,
return_url: returnUrl,
channel,
device,
useJoinConfig: true,
});
document.body.appendChild(payForm);
payForm.submit();
return;
} catch (err) {
setError(err instanceof Error ? err.message : "网络错误,请重试");

View File

@@ -0,0 +1,31 @@
"use client";
import { Link } from "@/i18n/navigation";
/**
* 支付完成回跳页
* Z-Pay 的 return_url 不支持带查询参数,故使用 /join/paid 作为专用成功页
*/
export default function JoinPaidPage() {
return (
<div className="flex min-h-screen items-center justify-center bg-[#f0f4f8] px-4">
<div className="w-full max-w-md animate-fade-in rounded-2xl bg-white p-10 text-center shadow-lg">
<div className="mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-full bg-emerald-50 text-5xl">
</div>
<h2 className="text-2xl font-bold text-slate-800"></h2>
<p className="mt-3 text-slate-500">
<br />
</p>
<Link
href="/"
className="mt-8 inline-flex items-center gap-2 rounded-full bg-sky-500 px-8 py-3 font-semibold text-white transition-colors hover:bg-sky-600"
>
</Link>
</div>
</div>
);
}

View File

@@ -2,14 +2,18 @@ import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { LocaleProvider } from "../context/LocaleContext";
import type { Locale } from "../context/LocaleContext";
import { getThemeConfig } from "@/config";
import { getThemeMessages } from "@/app/lib/theme-data";
const LOCALES: Locale[] = ["zh", "en"];
export const metadata: Metadata = {
title: "数字游民指南 | Digital Nomad Guide",
description:
"从零开始7天开启你的数字游民生活。远程工作、地点自由、技能变现 —— 一站式数字游民资源平台。",
};
export const metadata: Metadata = (() => {
const theme = getThemeConfig();
return {
title: theme.meta.title,
description: theme.meta.description,
};
})();
export function generateStaticParams() {
return LOCALES.map((locale) => ({ locale }));
@@ -27,7 +31,7 @@ export default async function LocaleLayout({
notFound();
}
const messages = (await import(`../../messages/${locale}.json`)).default;
const messages = await getThemeMessages(locale as Locale);
return (
<LocaleProvider locale={locale as Locale} messages={messages}>

View File

@@ -5,8 +5,11 @@ import Roadmap from "../components/Roadmap";
import Tools from "../components/Tools";
import Community from "../components/Community";
import Footer from "../components/Footer";
import { getThemeToolsData } from "../lib/theme-data";
export default async function HomePage() {
const toolsData = await getThemeToolsData();
export default function HomePage() {
return (
<>
<Header />
@@ -14,7 +17,7 @@ export default function HomePage() {
<Hero />
<Features />
<Roadmap />
<Tools />
<Tools data={toolsData} />
<Community />
</main>
<Footer />

View File

@@ -1,7 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
const PB_URL = process.env.POCKETBASE_URL || "https://pocketbase.hackrobot.cn";
const COLLECTION = "solan";
import { getPocketBaseConfig } from "@/config/services.config";
import { getThemeConfig } from "@/config";
function getOrCreateUserId(): string {
return `user${Date.now()}`;
@@ -62,13 +61,19 @@ export async function POST(request: NextRequest) {
(record as Record<string, string>)["media"] = mediaUrl;
}
const theme = getThemeConfig();
const pb = getPocketBaseConfig({
joinCollection: theme.services?.pocketbaseJoinCollection,
});
const collection = pb.joinCollection;
const doCreate = async (authToken?: string) => {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (authToken) headers["Authorization"] = authToken;
return fetch(`${PB_URL}/api/collections/${COLLECTION}/records`, {
return fetch(`${pb.url}/api/collections/${collection}/records`, {
method: "POST",
headers,
body: JSON.stringify(record),

View File

@@ -1,21 +1,24 @@
import { NextRequest, NextResponse } from "next/server";
import { PAYMENT_API_URL, SITE_URL } from "../../lib/env";
const ZPAY_SUBMIT = "https://zpayz.cn/submit.php";
import { getPaymentConfig, getJoinPaymentConfig } from "@/config/services.config";
import { SITE_URL } from "../../lib/env";
async function createPayOrder(
user_id: string,
return_url: string,
total_fee = 80,
type = "meetup",
total_fee?: number,
type?: string,
channel = "alipay"
) {
if (!PAYMENT_API_URL) throw new Error("未配置 PAYMENT_API_URL");
const joinConfig = getJoinPaymentConfig();
const fee = total_fee ?? joinConfig.amount;
const orderType = type ?? joinConfig.type;
const config = getPaymentConfig();
if (!config.apiUrl) throw new Error("未配置 PAYMENT_API_URL");
const payload = {
user_id,
total_fee: Number(total_fee) || 80,
type,
total_fee: Number(fee) || joinConfig.amount,
type: orderType,
channel,
return_url,
};
@@ -23,7 +26,7 @@ async function createPayOrder(
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
const res = await fetch(`${PAYMENT_API_URL}/payh5`, {
const res = await fetch(`${config.apiUrl}/payh5`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
@@ -36,7 +39,7 @@ async function createPayOrder(
}
let params = data.params || data.xorpay_params || {};
const payUrl = data.pay_url || data.xorpay_url || ZPAY_SUBMIT;
const payUrl = data.pay_url || data.xorpay_url || config.zpaySubmitUrl;
if (!params || typeof params !== "object") {
throw new Error("payjsapi 未返回支付参数");
}
@@ -103,12 +106,14 @@ export async function POST(request: NextRequest) {
body = Object.fromEntries(form.entries()) as Record<string, string>;
}
const joinConfig = getJoinPaymentConfig();
const payConfig = getPaymentConfig();
const user_id = String(body?.user_id || "").trim();
const return_url = String(body?.return_url || "").trim();
const total_fee = Number(body?.total_fee) || 80;
const type = String(body?.type || "meetup");
const total_fee = Number(body?.total_fee) || joinConfig.amount;
const type = String(body?.type || joinConfig.type);
const channel = String(body?.channel || "alipay");
const device = String(body?.device || "pc"); // pc | h5,前端根据 UA 传入
const device = String(body?.device || "pc"); // pc | h5 | wechat微信内传 wechat
if (!user_id) {
return NextResponse.json({ ok: false, error: "缺少 user_id" }, { status: 400 });
@@ -118,7 +123,8 @@ export async function POST(request: NextRequest) {
request.headers.get("x-forwarded-host")
? `${request.headers.get("x-forwarded-proto") || "https"}://${request.headers.get("x-forwarded-host")}`
: request.headers.get("origin") || SITE_URL;
const finalReturnUrl = return_url || `${origin}/join?paid=1`;
// Z-Pay return_url 不支持带参数,使用 /join/paid 专用路径
const finalReturnUrl = return_url || `${origin}/zh/join/paid`;
const { params, payUrl } = await createPayOrder(
user_id,
@@ -151,7 +157,7 @@ export async function POST(request: NextRequest) {
};
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000);
const redirectRes = await fetch(`${PAYMENT_API_URL}/payh5/redirect`, {
const redirectRes = await fetch(`${payConfig.apiUrl}/payh5/redirect`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(redirectPayload),
@@ -160,9 +166,38 @@ export async function POST(request: NextRequest) {
}).finally(() => clearTimeout(timeout));
if (redirectRes.status >= 301 && redirectRes.status <= 308) {
const location = redirectRes.headers.get("location");
if (location) return NextResponse.redirect(location);
if (location) {
const res = NextResponse.redirect(location);
// payh5/redirect 创建的是新订单,必须用其返回的 order_id非 createPayOrder 的 params
const orderId =
redirectRes.headers.get("x-pay-order-id")?.trim() ||
String(params?.out_trade_no || "").trim();
if (orderId) {
// 附带时间戳,前端只对 15 分钟内设置的 cookie 轮询,避免陈旧 cookie 误触发
const payload = `${orderId}|${Date.now()}`;
res.cookies.set("join_pay_order", payload, { path: "/", maxAge: 900 });
}
return res;
}
}
const resData = await redirectRes.json().catch(() => ({}));
// 微信内payurl2 会提示「请外微信外打开」,改用收银台表单由 Z-Pay 识别 UA
if (redirectRes.status === 200 && resData?.use_form) {
const html = buildPayHtml(payConfig.zpaySubmitUrl, params as Record<string, unknown>);
const res = new NextResponse(html, {
status: 200,
headers: { "Content-Type": "text/html; charset=utf-8" },
});
const orderId =
resData?.order_id?.trim() || String(params?.out_trade_no || "").trim();
if (orderId) {
res.cookies.set("join_pay_order", `${orderId}|${Date.now()}`, {
path: "/",
maxAge: 900,
});
}
return res;
}
if (redirectRes.status === 200 && resData?.qrcode_mode && resData?.img) {
const returnUrl = String(resData.return_url || finalReturnUrl).replace(/[&<>"']/g, (c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] || c
@@ -247,7 +282,7 @@ export async function POST(request: NextRequest) {
{ status: 500 }
);
}
const zpayRes = await fetch(ZPAY_SUBMIT, {
const zpayRes = await fetch(payConfig.zpaySubmitUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: formParams.toString(),
@@ -255,7 +290,13 @@ export async function POST(request: NextRequest) {
});
const location = zpayRes.headers.get("location");
if ((zpayRes.status === 301 || zpayRes.status === 302) && location) {
return NextResponse.redirect(location);
const res = NextResponse.redirect(location);
const outTradeNo = String(params?.out_trade_no || "").trim();
if (outTradeNo) {
const payload = `${outTradeNo}|${Date.now()}`;
res.cookies.set("join_pay_order", payload, { path: "/", maxAge: 900 });
}
return res;
}
const text = await zpayRes.text();
try {

View File

@@ -1,17 +1,18 @@
import { NextRequest, NextResponse } from "next/server";
import { PAYMENT_API_URL } from "../../../lib/env";
import { getPaymentConfig } from "@/config/services.config";
export async function GET(request: NextRequest) {
const orderId = request.nextUrl.searchParams.get("order_id");
if (!orderId) {
return NextResponse.json({ ok: false, error: "缺少 order_id" }, { status: 400 });
}
if (!PAYMENT_API_URL) {
const config = getPaymentConfig();
if (!config.apiUrl) {
return NextResponse.json({ ok: false, error: "未配置 PAYMENT_API_URL" }, { status: 500 });
}
try {
const res = await fetch(
`${PAYMENT_API_URL}/zpay_order_status?out_trade_no=${encodeURIComponent(orderId)}`,
`${config.apiUrl}/zpay_order_status?out_trade_no=${encodeURIComponent(orderId)}`,
{ cache: "no-store" }
);
const data = await res.json().catch(() => ({}));

View File

@@ -1,17 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import * as Minio from "minio";
import { uploadBuffer, generateObjectKey } from "@/app/lib/minio";
// mc alias list myminio: http://minioweb.hackrobot.cn:9035
const MINIO_ENDPOINT = process.env.MINIO_ENDPOINT || "minioweb.hackrobot.cn";
const MINIO_PORT = parseInt(process.env.MINIO_PORT || "9035", 10);
const MINIO_USE_SSL = process.env.MINIO_USE_SSL === "true";
const MINIO_BUCKET = process.env.MINIO_BUCKET || "hackrobot";
const MINIO_ACCESS_KEY = process.env.MINIO_ACCESS_KEY || "6i56HHfg4zPfYItCZtnp";
const MINIO_SECRET_KEY = process.env.MINIO_SECRET_KEY || "vDJCqEit3ejH5UmWKAZnvqhziNfbVsoOlBW12G8Q";
// 公开访问 URLhttps 无端口API 上传用 9035
const MINIO_PUBLIC_URL =
process.env.MINIO_PUBLIC_URL ||
`https://${MINIO_ENDPOINT}/${MINIO_BUCKET}`;
const MAX_SIZE = 20 * 1024 * 1024; // 20MB
export async function POST(request: NextRequest) {
try {
@@ -27,38 +17,23 @@ export async function POST(request: NextRequest) {
);
}
if (fileObj.size > 20 * 1024 * 1024) {
if (fileObj.size > MAX_SIZE) {
return NextResponse.json(
{ ok: false, error: "文件大小不能超过 20MB" },
{ status: 400 }
);
}
const client = new Minio.Client({
endPoint: MINIO_ENDPOINT,
port: MINIO_PORT,
useSSL: MINIO_USE_SSL,
accessKey: MINIO_ACCESS_KEY,
secretKey: MINIO_SECRET_KEY,
pathStyle: true,
region: process.env.MINIO_REGION || "china",
});
const ext =
(fileObj instanceof File ? fileObj.name : "").split(".").pop() ||
(fileObj.type?.startsWith("video/") ? "mp4" : "jpg");
const objectKey = `joins/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
const objectKey = generateObjectKey(ext);
const buffer = Buffer.from(await fileObj.arrayBuffer());
const contentType =
(fileObj as File).type || "application/octet-stream";
await client.putObject(MINIO_BUCKET, objectKey, buffer, buffer.length, {
"Content-Type": contentType,
});
const base = MINIO_PUBLIC_URL.replace(/\/$/, "");
const url = `${base}/${objectKey}`;
const { url } = await uploadBuffer(buffer, objectKey, contentType);
return NextResponse.json({ ok: true, url });
} catch (e) {

View File

@@ -1,8 +1,11 @@
"use client";
import { useState, type FormEvent } from "react";
const PB_URL = process.env.NEXT_PUBLIC_POCKETBASE_URL || "https://pocketbase.hackrobot.cn";
import {
pbLogin,
pbRegister,
pbSaveAuth,
} from "@/app/lib/pocketbase";
interface AuthModalProps {
isOpen: boolean;
@@ -24,6 +27,7 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
setLoading(true);
try {
let result;
if (mode === "register") {
if (password !== passwordConfirm) {
setError("两次密码不一致");
@@ -35,49 +39,11 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
setLoading(false);
return;
}
const res = await fetch(`${PB_URL}/api/collections/users/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 || "注册失败");
}
// 注册成功后自动登录
const authRes = await fetch(`${PB_URL}/api/collections/users/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity: email, password }),
});
if (!authRes.ok) {
throw new Error("注册成功,请手动登录");
}
const authData = await authRes.json();
if (authData?.token) {
localStorage.setItem("pb_token", authData.token);
localStorage.setItem("pb_user", JSON.stringify(authData.record));
}
result = await pbRegister(email, password, passwordConfirm);
} else {
const res = await fetch(`${PB_URL}/api/collections/users/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity: email, password }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err?.message || "登录失败");
}
const data = await res.json();
if (data?.token) {
localStorage.setItem("pb_token", data.token);
localStorage.setItem("pb_user", JSON.stringify(data.record));
}
result = await pbLogin(email, password);
}
pbSaveAuth(result.token, result.record);
onSuccess(email);
onClose();
setEmail("");

View File

@@ -2,6 +2,7 @@
import { useState, useEffect } from "react";
import { Link, useLocale, usePathname, useRouter, useTranslation } from "@/i18n/navigation";
import { getStoredUserEmail, pbLogout } from "@/app/lib/pocketbase";
import AuthModal from "./AuthModal";
import ThemeToggle from "./ThemeToggle";
@@ -11,18 +12,6 @@ const navLinks = [
{ labelKey: "community" as const, href: "#community" },
];
function getStoredUser(): string | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem("pb_user");
if (!raw) return null;
const user = JSON.parse(raw);
return user?.email ?? null;
} catch {
return null;
}
}
export default function Header() {
const { t } = useTranslation("common");
const { t: tNav } = useTranslation("nav");
@@ -35,12 +24,11 @@ export default function Header() {
const [userEmail, setUserEmail] = useState<string | null>(null);
useEffect(() => {
setUserEmail(getStoredUser());
setUserEmail(getStoredUserEmail());
}, []);
const handleLogout = () => {
localStorage.removeItem("pb_token");
localStorage.removeItem("pb_user");
pbLogout();
setUserEmail(null);
};

View File

@@ -1,23 +1,19 @@
"use client";
import { useTranslation } from "@/i18n/navigation";
import toolsData from "../data/tools.json";
import type { ToolsCategory } from "@/app/lib/theme-data";
const categories = toolsData.categories as Array<{
icon: string;
title: string;
color: string;
bg: string;
text: string;
tools: Array<{ name: string; desc: string; href: string }>;
}>;
type ToolsProps = {
data: { categories: ToolsCategory[] };
};
function truncateDesc(desc: string, maxLen = 5) {
if (!desc || desc.length <= maxLen) return desc;
return desc.slice(0, maxLen) + "...";
}
export default function Tools() {
export default function Tools({ data }: ToolsProps) {
const categories = data.categories;
const { t } = useTranslation("tools");
const total = categories.reduce((s, c) => s + c.tools.length, 0);
const toolStats = [

View File

@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "./context/ThemeContext";
import { getThemeConfig } from "@/config";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -13,11 +14,13 @@ const geistMono = Geist_Mono({
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "数字游民指南 | Digital Nomad Guide",
description:
"从零开始7天开启你的数字游民生活。远程工作、地点自由、技能变现 —— 一站式数字游民资源平台。",
};
export const metadata: Metadata = (() => {
const theme = getThemeConfig();
return {
title: theme.meta.title,
description: theme.meta.description,
};
})();
function ThemeScript() {
return (
@@ -46,7 +49,7 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN" suppressHydrationError>
<html lang="zh-CN" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>

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 };