Merge branch 'dev' into test
This commit is contained in:
@@ -29,22 +29,3 @@ AUTH_FACEBOOK_SECRET=004b1a9384b3433e153992e5edcef4ad
|
|||||||
# Cloudflare CDN(test / production 部署后刷缓存用)
|
# Cloudflare CDN(test / production 部署后刷缓存用)
|
||||||
CF_ZONE_ID=b1b6bfb7795667609c8e7f418af0156b
|
CF_ZONE_ID=b1b6bfb7795667609c8e7f418af0156b
|
||||||
CF_API_TOKEN=cfut_xyHb70XCw0j8f5Wz5fg5PemUQ2ZHnSpWvmrBvVeK94d3b00f
|
CF_API_TOKEN=cfut_xyHb70XCw0j8f5Wz5fg5PemUQ2ZHnSpWvmrBvVeK94d3b00f
|
||||||
|
|
||||||
# ─────────────────────────────
|
|
||||||
# Stripe 支付(dev 环境 test keys —— **查** https://dashboard.stripe.com/test/apikeys 拿**到**)
|
|
||||||
# ─────────────────────────────
|
|
||||||
# 服务**端** secret key(**仅** Next.js API route **用**,**不**要**曝**露**给**前**端**)
|
|
||||||
STRIPE_SECRET_KEY=sk_test_replace_with_your_dev_secret_key
|
|
||||||
# 前**端** publishable key(NEXT_PUBLIC_ 前**缀**才**能**在**前**端**用**)
|
|
||||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_51Te8ybEJDtUGxQHo0UMySJ2hW0vVryynzllmIUI3UQdQCFgxNLci0Jmm2lQkRsTaIP7C7IQlFzfFyBJ5rOhr1ML800G8P8DF5R
|
|
||||||
# webhook 签**名**密**钥**(**从** `stripe listen` 输**出**拿**到**,**本**地**开**发**用**)
|
|
||||||
STRIPE_WEBHOOK_SECRET=whsec_replace_with_your_stripe_cli_output
|
|
||||||
|
|
||||||
# 3 **个**订**阅**套餐**的** Product / Price ID(**从** Stripe dashboard **创**建** 3 **个** Product + 3 **个** Price **后**填**)
|
|
||||||
STRIPE_PRODUCT_MONTHLY=prod_replace_monthly
|
|
||||||
STRIPE_PRICE_MONTHLY=price_replace_monthly
|
|
||||||
STRIPE_PRODUCT_QUARTERLY=prod_replace_quarterly
|
|
||||||
STRIPE_PRICE_QUARTERLY=price_replace_quarterly
|
|
||||||
STRIPE_PRODUCT_ANNUAL=prod_replace_annual
|
|
||||||
STRIPE_PRICE_ANNUAL=price_replace_annual
|
|
||||||
|
|
||||||
|
|||||||
@@ -23,18 +23,3 @@ AUTH_FACEBOOK_SECRET=004b1a9384b3433e153992e5edcef4ad
|
|||||||
# Cloudflare CDN(test / production 部署后刷缓存用)
|
# Cloudflare CDN(test / production 部署后刷缓存用)
|
||||||
CF_ZONE_ID=b1b6bfb7795667609c8e7f418af0156b
|
CF_ZONE_ID=b1b6bfb7795667609c8e7f418af0156b
|
||||||
CF_API_TOKEN=cfut_xyHb70XCw0j8f5Wz5fg5PemUQ2ZHnSpWvmrBvVeK94d3b00f
|
CF_API_TOKEN=cfut_xyHb70XCw0j8f5Wz5fg5PemUQ2ZHnSpWvmrBvVeK94d3b00f
|
||||||
|
|
||||||
# ─────────────────────────────
|
|
||||||
# Stripe 支付(test 环境 test keys)
|
|
||||||
# ─────────────────────────────
|
|
||||||
STRIPE_SECRET_KEY=sk_test_replace_with_your_test_secret_key
|
|
||||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_51Te8ybEJDtUGxQHo0UMySJ2hW0vVryynzllmIUI3UQdQCFgxNLci0Jmm2lQkRsTaIP7C7IQlFzfFyBJ5rOhr1ML800G8P8DF5R
|
|
||||||
STRIPE_WEBHOOK_SECRET=whsec_replace_with_your_stripe_cli_output
|
|
||||||
|
|
||||||
STRIPE_PRODUCT_MONTHLY=prod_replace_monthly
|
|
||||||
STRIPE_PRICE_MONTHLY=price_replace_monthly
|
|
||||||
STRIPE_PRODUCT_QUARTERLY=prod_replace_quarterly
|
|
||||||
STRIPE_PRICE_QUARTERLY=price_replace_quarterly
|
|
||||||
STRIPE_PRODUCT_ANNUAL=prod_replace_annual
|
|
||||||
STRIPE_PRICE_ANNUAL=price_replace_annual
|
|
||||||
|
|
||||||
|
|||||||
@@ -30,20 +30,3 @@ AUTH_FACEBOOK_SECRET=004b1a9384b3433e153992e5edcef4ad
|
|||||||
# Cloudflare CDN(test / production 部署后刷缓存用)
|
# Cloudflare CDN(test / production 部署后刷缓存用)
|
||||||
CF_ZONE_ID=b1b6bfb7795667609c8e7f418af0156b
|
CF_ZONE_ID=b1b6bfb7795667609c8e7f418af0156b
|
||||||
CF_API_TOKEN=cfut_xyHb70XCw0j8f5Wz5fg5PemUQ2ZHnSpWvmrBvVeK94d3b00f
|
CF_API_TOKEN=cfut_xyHb70XCw0j8f5Wz5fg5PemUQ2ZHnSpWvmrBvVeK94d3b00f
|
||||||
|
|
||||||
# ─────────────────────────────
|
|
||||||
# Stripe 支付(**生**产**环**境** live keys —— **从** https://dashboard.stripe.com/apikeys 拿**到**)
|
|
||||||
# **不**要** commit 真**实** key 到**版**本**控**制**
|
|
||||||
# ─────────────────────────────
|
|
||||||
STRIPE_SECRET_KEY=sk_live_replace_with_your_live_secret_key
|
|
||||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_replace_with_your_dev_publishable_key
|
|
||||||
# webhook 签**名**密**钥**(**从** Stripe dashboard / Webhooks **端**点**的** "Signing secret" **拿**到**)
|
|
||||||
STRIPE_WEBHOOK_SECRET=whsec_replace_with_your_live_webhook_signing_secret
|
|
||||||
|
|
||||||
STRIPE_PRODUCT_MONTHLY=prod_replace_monthly
|
|
||||||
STRIPE_PRICE_MONTHLY=price_replace_monthly
|
|
||||||
STRIPE_PRODUCT_QUARTERLY=prod_replace_quarterly
|
|
||||||
STRIPE_PRICE_QUARTERLY=price_replace_quarterly
|
|
||||||
STRIPE_PRODUCT_ANNUAL=prod_replace_annual
|
|
||||||
STRIPE_PRICE_ANNUAL=price_replace_annual
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,6 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fingerprintjs/fingerprintjs": "^5.2.0",
|
"@fingerprintjs/fingerprintjs": "^5.2.0",
|
||||||
"@stripe/stripe-js": "^9.8.0",
|
|
||||||
"@xstate/react": "^5",
|
"@xstate/react": "^5",
|
||||||
"classnames": "^2.5.1",
|
"classnames": "^2.5.1",
|
||||||
"dexie": "^4.4.3",
|
"dexie": "^4.4.3",
|
||||||
@@ -32,7 +31,6 @@
|
|||||||
"react": "19.2.4",
|
"react": "19.2.4",
|
||||||
"react-dom": "19.2.4",
|
"react-dom": "19.2.4",
|
||||||
"react-icons": "^5.6.0",
|
"react-icons": "^5.6.0",
|
||||||
"stripe": "^22.2.1",
|
|
||||||
"ua-parser-js": "^2.0.10",
|
"ua-parser-js": "^2.0.10",
|
||||||
"unstorage": "^1.17.5",
|
"unstorage": "^1.17.5",
|
||||||
"xstate": "^5",
|
"xstate": "^5",
|
||||||
|
|||||||
Generated
-25
@@ -11,9 +11,6 @@ importers:
|
|||||||
'@fingerprintjs/fingerprintjs':
|
'@fingerprintjs/fingerprintjs':
|
||||||
specifier: ^5.2.0
|
specifier: ^5.2.0
|
||||||
version: 5.2.0
|
version: 5.2.0
|
||||||
'@stripe/stripe-js':
|
|
||||||
specifier: ^9.8.0
|
|
||||||
version: 9.8.0
|
|
||||||
'@xstate/react':
|
'@xstate/react':
|
||||||
specifier: ^5
|
specifier: ^5
|
||||||
version: 5.0.5(@types/react@19.2.16)(react@19.2.4)(xstate@5.32.0)
|
version: 5.0.5(@types/react@19.2.16)(react@19.2.4)(xstate@5.32.0)
|
||||||
@@ -50,9 +47,6 @@ importers:
|
|||||||
react-icons:
|
react-icons:
|
||||||
specifier: ^5.6.0
|
specifier: ^5.6.0
|
||||||
version: 5.6.0(react@19.2.4)
|
version: 5.6.0(react@19.2.4)
|
||||||
stripe:
|
|
||||||
specifier: ^22.2.1
|
|
||||||
version: 22.2.1(@types/node@20.19.41)
|
|
||||||
ua-parser-js:
|
ua-parser-js:
|
||||||
specifier: ^2.0.10
|
specifier: ^2.0.10
|
||||||
version: 2.0.10
|
version: 2.0.10
|
||||||
@@ -896,10 +890,6 @@ packages:
|
|||||||
'@standard-schema/spec@1.1.0':
|
'@standard-schema/spec@1.1.0':
|
||||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||||
|
|
||||||
'@stripe/stripe-js@9.8.0':
|
|
||||||
resolution: {integrity: sha512-DHJpol/98VKyojNSYmpkB5vOMnlf87hPe0wPxyaYTNiTMk5QjKMXDfSZLwGctYIXAgAWDFeRABc8lFAj0BELyw==}
|
|
||||||
engines: {node: '>=12.16'}
|
|
||||||
|
|
||||||
'@swc/core-darwin-arm64@1.15.32':
|
'@swc/core-darwin-arm64@1.15.32':
|
||||||
resolution: {integrity: sha512-/YWMvJDPu+AAwuUsM2G+DNQ/7zhodURGzdQyewEqcvgklAdDHs3LwQmLLnyn6SJl8DT8UOxkbzK+D1PmPeelRg==}
|
resolution: {integrity: sha512-/YWMvJDPu+AAwuUsM2G+DNQ/7zhodURGzdQyewEqcvgklAdDHs3LwQmLLnyn6SJl8DT8UOxkbzK+D1PmPeelRg==}
|
||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
@@ -2944,15 +2934,6 @@ packages:
|
|||||||
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
|
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
stripe@22.2.1:
|
|
||||||
resolution: {integrity: sha512-ULAtq25USBEx3yeN5zimEkfYVFETVMP5om25Ryr8ol11P62imaCZLBIEW78T7zm7Wg3wnZi+80S72yf3LCpNhw==}
|
|
||||||
engines: {node: '>=18'}
|
|
||||||
peerDependencies:
|
|
||||||
'@types/node': '>=18'
|
|
||||||
peerDependenciesMeta:
|
|
||||||
'@types/node':
|
|
||||||
optional: true
|
|
||||||
|
|
||||||
styled-jsx@5.1.6:
|
styled-jsx@5.1.6:
|
||||||
resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==}
|
resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==}
|
||||||
engines: {node: '>= 12.0.0'}
|
engines: {node: '>= 12.0.0'}
|
||||||
@@ -3989,8 +3970,6 @@ snapshots:
|
|||||||
|
|
||||||
'@standard-schema/spec@1.1.0': {}
|
'@standard-schema/spec@1.1.0': {}
|
||||||
|
|
||||||
'@stripe/stripe-js@9.8.0': {}
|
|
||||||
|
|
||||||
'@swc/core-darwin-arm64@1.15.32':
|
'@swc/core-darwin-arm64@1.15.32':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
@@ -6236,10 +6215,6 @@ snapshots:
|
|||||||
|
|
||||||
strip-json-comments@3.1.1: {}
|
strip-json-comments@3.1.1: {}
|
||||||
|
|
||||||
stripe@22.2.1(@types/node@20.19.41):
|
|
||||||
optionalDependencies:
|
|
||||||
'@types/node': 20.19.41
|
|
||||||
|
|
||||||
styled-jsx@5.1.6(@babel/core@7.29.7)(react@19.2.4):
|
styled-jsx@5.1.6(@babel/core@7.29.7)(react@19.2.4):
|
||||||
dependencies:
|
dependencies:
|
||||||
client-only: 0.0.1
|
client-only: 0.0.1
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
/**
|
|
||||||
* POST /api/payment/create-checkout-session
|
|
||||||
*
|
|
||||||
* 创建 Stripe Checkout Session(订阅模式)→ 返回 URL 给前端
|
|
||||||
* 前端接到后 `window.location.href = url` 跳转到 Stripe 托管页
|
|
||||||
*
|
|
||||||
* 业务流程:
|
|
||||||
* 1. 前端用户点 "Confirm the agreement and Activate"
|
|
||||||
* 2. 前端 POST `{ planId, successUrl, cancelUrl }` 到本端点
|
|
||||||
* 3. 本端调 `stripe.checkout.sessions.create({...})` 创建 session
|
|
||||||
* 4. 返回 `{ url: session.url }` 给前端
|
|
||||||
* 5. 前端 `window.location.href = url` 跳转
|
|
||||||
* 6. Stripe 收银台结束后回跳到 success_url / cancel_url
|
|
||||||
* 7. 同时 Stripe 发送 `checkout.session.completed` webhook → 后端设置 user.isVip + voiceMinutes
|
|
||||||
*/
|
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
|
||||||
|
|
||||||
import { SUBSCRIPTION_PLANS } from "@/data/constants/subscription-plans";
|
|
||||||
import type { SubscriptionPlanId } from "@/data/constants/subscription-plans";
|
|
||||||
import { getPlanPriceId } from "@/lib/stripe/stripe-products";
|
|
||||||
import { getStripeClient } from "@/lib/stripe/stripe-client";
|
|
||||||
import { Logger } from "@/utils";
|
|
||||||
|
|
||||||
const log = new Logger("AppApiPaymentCreateCheckoutSessionRoute");
|
|
||||||
|
|
||||||
interface CreateCheckoutRequestBody {
|
|
||||||
planId: SubscriptionPlanId;
|
|
||||||
successUrl: string;
|
|
||||||
cancelUrl: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
|
||||||
let body: CreateCheckoutRequestBody;
|
|
||||||
try {
|
|
||||||
body = (await req.json()) as CreateCheckoutRequestBody;
|
|
||||||
} catch {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Invalid JSON body" },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 入参验证
|
|
||||||
if (!body.planId || !body.successUrl || !body.cancelUrl) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Missing required fields: planId, successUrl, cancelUrl" },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!SUBSCRIPTION_PLANS.find((p) => p.id === body.planId)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: `Unknown planId: ${body.planId}` },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证 successUrl / cancelUrl 来自同源(防 open redirect)
|
|
||||||
// 注:本轮先不做验证(前端和后端同源)—— 未来如果要开放给第三方请加 `same-origin` 检查
|
|
||||||
|
|
||||||
// 拿到 Stripe Price ID(从 env)
|
|
||||||
let priceId: string;
|
|
||||||
try {
|
|
||||||
priceId = getPlanPriceId(body.planId);
|
|
||||||
} catch (e) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (e as Error).message },
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 调 Stripe API 创建 Checkout Session
|
|
||||||
const stripe = getStripeClient();
|
|
||||||
try {
|
|
||||||
const session = await stripe.checkout.sessions.create({
|
|
||||||
mode: "subscription",
|
|
||||||
line_items: [{ price: priceId, quantity: 1 }],
|
|
||||||
success_url: body.successUrl,
|
|
||||||
cancel_url: body.cancelUrl,
|
|
||||||
// 让 webhook 能识别用户 + 套餐(后端接收 webhook 时从 metadata 取)
|
|
||||||
metadata: {
|
|
||||||
planId: body.planId,
|
|
||||||
// TODO: 加 userId(如果已知)—— 前端可在 body 传 userId
|
|
||||||
},
|
|
||||||
// 允许 promo codes(如果 Stripe dashboard 开了)
|
|
||||||
allow_promotion_codes: true,
|
|
||||||
// billing_address_collection: "auto" —— 根据 Stripe dashboard 配置
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({ url: session.url });
|
|
||||||
} catch (e) {
|
|
||||||
const err = e as { message?: string; type?: string; code?: string };
|
|
||||||
log.error("[api/create-checkout-session] Stripe error", {
|
|
||||||
message: err.message,
|
|
||||||
type: err.type,
|
|
||||||
code: err.code,
|
|
||||||
});
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error: err.message ?? "Failed to create checkout session",
|
|
||||||
type: err.type,
|
|
||||||
},
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
/**
|
|
||||||
* POST /api/payment/customer-portal
|
|
||||||
*
|
|
||||||
* 创建 Stripe Customer Portal Session → 返回 URL 给前端
|
|
||||||
*
|
|
||||||
* 为什么需要 Customer Portal:
|
|
||||||
* - Stripe 托管的"用户自助管理"页(取消 / 换 plan / 查看账单 / 更新卡)
|
|
||||||
* - 不需要我们自己写 UI
|
|
||||||
* - 最常用的就是 "取消订阅"(避免客服)
|
|
||||||
*
|
|
||||||
* 需要的参数:`customerId`(从 User.stripeCustomerId 取)—— webhook 会设置
|
|
||||||
* - 如果为 null:返错("先购买")
|
|
||||||
*/
|
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
|
||||||
|
|
||||||
import { getStripeClient } from "@/lib/stripe/stripe-client";
|
|
||||||
import { Logger } from "@/utils";
|
|
||||||
|
|
||||||
const log = new Logger("AppApiPaymentCustomerPortalRoute");
|
|
||||||
|
|
||||||
interface CreatePortalRequestBody {
|
|
||||||
customerId: string | null;
|
|
||||||
returnUrl: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
|
||||||
let body: CreatePortalRequestBody;
|
|
||||||
try {
|
|
||||||
body = (await req.json()) as CreatePortalRequestBody;
|
|
||||||
} catch {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Invalid JSON body" },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 入参验证
|
|
||||||
if (!body.customerId) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Missing customerId. Please subscribe first before managing subscription." },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!body.returnUrl) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Missing returnUrl" },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 调 Stripe API 创建 Customer Portal Session
|
|
||||||
const stripe = getStripeClient();
|
|
||||||
try {
|
|
||||||
const session = await stripe.billingPortal.sessions.create({
|
|
||||||
customer: body.customerId,
|
|
||||||
return_url: body.returnUrl,
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({ url: session.url });
|
|
||||||
} catch (e) {
|
|
||||||
const err = e as { message?: string; type?: string; code?: string };
|
|
||||||
log.error("[api/customer-portal] Stripe error", {
|
|
||||||
customerId: body.customerId,
|
|
||||||
message: err.message,
|
|
||||||
type: err.type,
|
|
||||||
code: err.code,
|
|
||||||
});
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error: err.message ?? "Failed to create customer portal session",
|
|
||||||
type: err.type,
|
|
||||||
},
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
/**
|
|
||||||
* POST /api/payment/webhook
|
|
||||||
*
|
|
||||||
* 接收 Stripe webhook → 验签 → 分发到 handler
|
|
||||||
*
|
|
||||||
* 关键设计:
|
|
||||||
* - 必须用 raw body 验签(不能让 Next.js 解析 JSON,所以用 `request.text()` 取原文)
|
|
||||||
* - 校验 `stripe-signature` 头(用 `STRIPE_WEBHOOK_SECRET`)
|
|
||||||
* - `stripe.webhooks.constructEvent(rawBody, sigHeader, secret)` 会抛错(如果签名不匹配)
|
|
||||||
* - 分发到 `dispatchStripeEvent()` → 4 个 handler 之一
|
|
||||||
*
|
|
||||||
* 配置 Stripe webhook 端点:
|
|
||||||
* - URL:https://cozsweet.com/api/payment/webhook
|
|
||||||
* - 监听的事件:
|
|
||||||
* - checkout.session.completed
|
|
||||||
* - customer.subscription.created
|
|
||||||
* - customer.subscription.updated
|
|
||||||
* - customer.subscription.deleted
|
|
||||||
* - invoice.payment_succeeded
|
|
||||||
*
|
|
||||||
* 本地开发用 Stripe CLI 转发:
|
|
||||||
* stripe listen --forward-to localhost:3000/api/payment/webhook
|
|
||||||
* 输出的 `whsec_xxx` → 写到 .env.local 的 `STRIPE_WEBHOOK_SECRET`
|
|
||||||
*/
|
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
|
||||||
import type Stripe from "stripe";
|
|
||||||
|
|
||||||
import { dispatchStripeEvent } from "@/lib/stripe/stripe-events";
|
|
||||||
import { getStripeClient } from "@/lib/stripe/stripe-client";
|
|
||||||
import { Logger } from "@/utils";
|
|
||||||
|
|
||||||
const log = new Logger("AppApiPaymentWebhookRoute");
|
|
||||||
|
|
||||||
export async function POST(req: NextRequest) {
|
|
||||||
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
|
||||||
if (!webhookSecret) {
|
|
||||||
log.error("[api/webhook] STRIPE_WEBHOOK_SECRET is not set");
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Webhook secret not configured" },
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 取 raw body(验签用 raw bytes,不能 JSON.parse 后再 stringify —— 会丢空格、字节顺序等)
|
|
||||||
const rawBody = await req.text();
|
|
||||||
const sigHeader = req.headers.get("stripe-signature");
|
|
||||||
if (!sigHeader) {
|
|
||||||
log.error("[api/webhook] Missing stripe-signature header");
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Missing stripe-signature header" },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 校验签名(不匹配会抛错)
|
|
||||||
const stripe = getStripeClient();
|
|
||||||
let event: Stripe.Event;
|
|
||||||
try {
|
|
||||||
event = stripe.webhooks.constructEvent(rawBody, sigHeader, webhookSecret);
|
|
||||||
} catch (e) {
|
|
||||||
const err = e as Error;
|
|
||||||
log.error("[api/webhook] Signature verification failed", {
|
|
||||||
message: err.message,
|
|
||||||
});
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: `Webhook signature verification failed: ${err.message}` },
|
|
||||||
{ status: 400 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 分发到 handler
|
|
||||||
log.debug("[api/webhook] Received event", {
|
|
||||||
eventId: event.id,
|
|
||||||
type: event.type,
|
|
||||||
created: new Date(event.created * 1000).toISOString(),
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const handled = await dispatchStripeEvent(event);
|
|
||||||
if (!handled) {
|
|
||||||
log.debug(`[api/webhook] Ignored event type: ${event.type}`);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
const err = e as Error;
|
|
||||||
log.error("[api/webhook] Handler error", {
|
|
||||||
eventId: event.id,
|
|
||||||
type: event.type,
|
|
||||||
message: err.message,
|
|
||||||
stack: err.stack,
|
|
||||||
});
|
|
||||||
// 返 500 让 Stripe 重试(幂等保护:handler 自己用 event.id 去重)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Handler error" },
|
|
||||||
{ status: 500 },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 返 200 让 Stripe 标记为已接收(即使 handler 没做什么也返 200 —— 避免无谓重试)
|
|
||||||
return NextResponse.json({ received: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 关闭 body parser 验签 raw body 需要 raw text(不能被 Next.js 的 bodyParser 解析)*/
|
|
||||||
export const dynamic = "force-dynamic"; // 关闭静态优化(避免 body 被缓存)
|
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
* 订阅取消回跳页
|
* 订阅取消回跳页
|
||||||
*
|
*
|
||||||
* 流程:
|
* 流程:
|
||||||
* 1. 用户在 Stripe 托管页点 "Cancel" / 关闭页面
|
* 1. 用户在支付服务托管页点 "Cancel" / 关闭页面
|
||||||
* 2. Stripe 重定向到 `/subscription/cancel`
|
* 2. 支付服务重定向到 `/subscription/cancel`
|
||||||
* 3. 这个页面显示 "已取消" + 跳回 `/subscription`
|
* 3. 这个页面显示 "已取消" + 跳回 `/subscription`
|
||||||
*
|
*
|
||||||
* 不需要任何后端逻辑(没付款发生)
|
* 不需要任何后端逻辑(没付款发生)
|
||||||
|
|||||||
@@ -7,6 +7,5 @@ export * from "./subscription-banner";
|
|||||||
export * from "./subscription-benefits-card";
|
export * from "./subscription-benefits-card";
|
||||||
export * from "./subscription-checkout-button";
|
export * from "./subscription-checkout-button";
|
||||||
export * from "./subscription-cta-button";
|
export * from "./subscription-cta-button";
|
||||||
export * from "./subscription-manage-button";
|
|
||||||
export * from "./subscription-plan-card";
|
export * from "./subscription-plan-card";
|
||||||
export * from "./subscription-user-row";
|
export * from "./subscription-user-row";
|
||||||
|
|||||||
@@ -2,75 +2,63 @@
|
|||||||
/**
|
/**
|
||||||
* 订阅 checkout 触发按钮
|
* 订阅 checkout 触发按钮
|
||||||
*
|
*
|
||||||
* 包装 `SubscriptionCtaButton` —— 加上调 `/api/payment/create-checkout-session` 的逻辑
|
* 包装 `SubscriptionCtaButton` —— 通过 payment 状态机创建后端订单并拉起支付。
|
||||||
*
|
|
||||||
* 流程:
|
|
||||||
* 1. 用户点 "Confirm the agreement and Activate"
|
|
||||||
* 2. fetch POST /api/payment/create-checkout-session { planId, successUrl, cancelUrl }
|
|
||||||
* 3. 拿到 `{ url }` → `window.location.href = url` 跳转到 Stripe 托管页
|
|
||||||
* 4. 用户结账 → Stripe 回跳到 successUrl / cancelUrl
|
|
||||||
* 5. 同时发 webhook → 后端设置 user.isVip + voiceMinutes
|
|
||||||
*/
|
*/
|
||||||
import { useState } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
import type { SubscriptionPlanId } from "@/data/constants/subscription-plans";
|
import {
|
||||||
import { ROUTES } from "@/router/routes";
|
usePaymentDispatch,
|
||||||
|
usePaymentState,
|
||||||
|
} from "@/stores/payment/payment-context";
|
||||||
|
|
||||||
import { SubscriptionCtaButton } from "./subscription-cta-button";
|
import { SubscriptionCtaButton } from "./subscription-cta-button";
|
||||||
import styles from "./subscription-cta-button.module.css";
|
import styles from "./subscription-cta-button.module.css";
|
||||||
import { Logger } from "@/utils";
|
|
||||||
|
|
||||||
const log = new Logger("AppSubscriptionComponentsSubscriptionCheckoutButton");
|
|
||||||
|
|
||||||
export interface SubscriptionCheckoutButtonProps {
|
export interface SubscriptionCheckoutButtonProps {
|
||||||
planId: SubscriptionPlanId;
|
|
||||||
/** 是否可用(未选套餐 / 未勾选协议 → false) */
|
/** 是否可用(未选套餐 / 未勾选协议 → false) */
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SubscriptionCheckoutButton({
|
export function SubscriptionCheckoutButton({
|
||||||
planId,
|
|
||||||
disabled = false,
|
disabled = false,
|
||||||
}: SubscriptionCheckoutButtonProps) {
|
}: SubscriptionCheckoutButtonProps) {
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const payment = usePaymentState();
|
||||||
const [error, setError] = useState<string | null>(null);
|
const paymentDispatch = usePaymentDispatch();
|
||||||
|
const launchedNonceRef = useRef(0);
|
||||||
|
|
||||||
const handleClick = async () => {
|
useEffect(() => {
|
||||||
if (disabled || isLoading) return;
|
if (!payment.payParams || payment.launchNonce <= launchedNonceRef.current) {
|
||||||
setIsLoading(true);
|
return;
|
||||||
setError(null);
|
}
|
||||||
|
|
||||||
try {
|
launchedNonceRef.current = payment.launchNonce;
|
||||||
// success / cancel URL —— 走当前 origin 的绝对路径
|
const paymentUrl = getPaymentUrl(payment.payParams);
|
||||||
const origin = window.location.origin;
|
if (!paymentUrl) {
|
||||||
const res = await fetch("/api/payment/create-checkout-session", {
|
paymentDispatch({
|
||||||
method: "POST",
|
type: "PaymentLaunchFailed",
|
||||||
headers: { "Content-Type": "application/json" },
|
errorMessage: "Payment parameters did not include a supported URL.",
|
||||||
body: JSON.stringify({
|
|
||||||
planId,
|
|
||||||
successUrl: `${origin}${ROUTES.subscription}/success?session_id={CHECKOUT_SESSION_ID}`,
|
|
||||||
cancelUrl: `${origin}${ROUTES.subscription}/cancel`,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
return;
|
||||||
if (!res.ok) {
|
|
||||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
|
||||||
throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const { url } = (await res.json()) as { url: string };
|
window.location.href = paymentUrl;
|
||||||
if (!url) {
|
}, [payment.launchNonce, payment.payParams, paymentDispatch]);
|
||||||
throw new Error("No checkout URL returned");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 跳转到 Stripe 托管页
|
const isLoading =
|
||||||
window.location.href = url;
|
payment.isCreatingOrder ||
|
||||||
} catch (e) {
|
payment.isPollingOrder ||
|
||||||
const err = e as Error;
|
payment.isCheckingVipStatus;
|
||||||
log.error("[subscription-checkout-button] error", err);
|
const label = payment.isPaid
|
||||||
setError(err.message);
|
? "Activated"
|
||||||
setIsLoading(false);
|
: payment.isPollingOrder
|
||||||
}
|
? "Processing payment..."
|
||||||
|
: payment.isCreatingOrder
|
||||||
|
? "Creating order..."
|
||||||
|
: "Confirm the agreement and Activate";
|
||||||
|
|
||||||
|
const handleClick = () => {
|
||||||
|
if (disabled || isLoading) return;
|
||||||
|
paymentDispatch({ type: "PaymentCreateOrderSubmitted" });
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -82,9 +70,9 @@ export function SubscriptionCheckoutButton({
|
|||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
className={styles.button}
|
className={styles.button}
|
||||||
>
|
>
|
||||||
Confirm the agreement and Activate
|
{label}
|
||||||
</SubscriptionCtaButton>
|
</SubscriptionCtaButton>
|
||||||
{error ? (
|
{payment.errorMessage ? (
|
||||||
<p
|
<p
|
||||||
role="alert"
|
role="alert"
|
||||||
style={{
|
style={{
|
||||||
@@ -94,9 +82,28 @@ export function SubscriptionCheckoutButton({
|
|||||||
textAlign: "center",
|
textAlign: "center",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{error}
|
{payment.errorMessage}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getPaymentUrl(payParams: Record<string, unknown>): string | null {
|
||||||
|
const keys = [
|
||||||
|
"url",
|
||||||
|
"checkoutUrl",
|
||||||
|
"checkout_url",
|
||||||
|
"paymentUrl",
|
||||||
|
"payment_url",
|
||||||
|
"redirectUrl",
|
||||||
|
"redirect_url",
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = payParams[key];
|
||||||
|
if (typeof value === "string" && value.length > 0) return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
"use client";
|
|
||||||
/**
|
|
||||||
* "Manage VIP" 按钮组件(取消订阅 / 换 plan / 查看账单)
|
|
||||||
*
|
|
||||||
* 点击后调 `/api/payment/customer-portal` 拿到 Stripe Customer Portal 页面的 URL
|
|
||||||
*
|
|
||||||
* 业务事实:
|
|
||||||
* - 不自己写 "取消订阅" UI —— 跳到 Stripe 自己的 Customer Portal
|
|
||||||
* - 要 `customerId` —— webhook 会设置到 User.stripeCustomerId
|
|
||||||
* - 如果为 null(用户从未购买)→ 提示 "先购买"("Get VIP" 路径走过来就是这个)
|
|
||||||
*/
|
|
||||||
import { useState } from "react";
|
|
||||||
|
|
||||||
import { ROUTES } from "@/router/routes";
|
|
||||||
|
|
||||||
import { SubscriptionCtaButton } from "./subscription-cta-button";
|
|
||||||
import styles from "./subscription-cta-button.module.css";
|
|
||||||
import { Logger } from "@/utils";
|
|
||||||
|
|
||||||
const log = new Logger("AppSubscriptionComponentsSubscriptionManageButton");
|
|
||||||
|
|
||||||
export interface SubscriptionManageButtonProps {
|
|
||||||
/** 从 User.stripeCustomerId 取(webhook 设置) */
|
|
||||||
customerId: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SubscriptionManageButton({ customerId }: SubscriptionManageButtonProps) {
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const handleClick = async () => {
|
|
||||||
if (isLoading) return;
|
|
||||||
|
|
||||||
// 没有 customerId → 不该出现这个按钮(sidebar 根据 isVip + stripeCustomerId 控制展示)
|
|
||||||
// 防御性检查:如果走到这里没有 customerId,提示用户联系客服
|
|
||||||
if (!customerId) {
|
|
||||||
setError("Please subscribe first before managing your subscription.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const origin = window.location.origin;
|
|
||||||
const res = await fetch("/api/payment/customer-portal", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
customerId,
|
|
||||||
returnUrl: `${origin}${ROUTES.subscription}`,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
|
||||||
throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const { url } = (await res.json()) as { url: string };
|
|
||||||
if (!url) {
|
|
||||||
throw new Error("No portal URL returned");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 跳转到 Stripe Customer Portal
|
|
||||||
window.location.href = url;
|
|
||||||
} catch (e) {
|
|
||||||
const err = e as Error;
|
|
||||||
log.error("[subscription-manage-button] error", err);
|
|
||||||
setError(err.message);
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<SubscriptionCtaButton
|
|
||||||
type="button"
|
|
||||||
disabled={!customerId}
|
|
||||||
isLoading={isLoading}
|
|
||||||
onClick={handleClick}
|
|
||||||
className={styles.button}
|
|
||||||
>
|
|
||||||
Manage VIP
|
|
||||||
</SubscriptionCtaButton>
|
|
||||||
{error ? (
|
|
||||||
<p
|
|
||||||
role="alert"
|
|
||||||
style={{
|
|
||||||
color: "#c0392b",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
marginTop: "0.5rem",
|
|
||||||
textAlign: "center",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -9,20 +9,31 @@
|
|||||||
* - 选中/高亮:2px 粉色边框 + 浅粉阴影
|
* - 选中/高亮:2px 粉色边框 + 浅粉阴影
|
||||||
* - 三个卡片底部渐变不同:粉 → 紫红 → 紫
|
* - 三个卡片底部渐变不同:粉 → 紫红 → 紫
|
||||||
*/
|
*/
|
||||||
import type { SubscriptionPlan, SubscriptionPlanId } from "@/data/constants/subscription-plans";
|
|
||||||
|
|
||||||
import styles from "./subscription-plan-card.module.css";
|
import styles from "./subscription-plan-card.module.css";
|
||||||
|
|
||||||
const PER_DAY_GRADIENTS: Record<SubscriptionPlanId, string> = {
|
const PER_DAY_GRADIENTS = [
|
||||||
monthly: "linear-gradient(90deg, #ff7ab8 0%, #ff5d9c 100%)",
|
"linear-gradient(90deg, #ff7ab8 0%, #ff5d9c 100%)",
|
||||||
quarterly: "linear-gradient(90deg, #d16bff 0%, #ff5da3 100%)",
|
"linear-gradient(90deg, #d16bff 0%, #ff5da3 100%)",
|
||||||
annual: "linear-gradient(90deg, #9a4dff 0%, #c44dff 100%)",
|
"linear-gradient(90deg, #9a4dff 0%, #c44dff 100%)",
|
||||||
};
|
"linear-gradient(90deg, #32c7b5 0%, #2f8fd8 100%)",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export interface SubscriptionPlanView {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
price: string;
|
||||||
|
originalPrice: string | null;
|
||||||
|
perDay: string;
|
||||||
|
highlight: boolean;
|
||||||
|
currencySymbol: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface SubscriptionPlanCardProps {
|
export interface SubscriptionPlanCardProps {
|
||||||
plan: SubscriptionPlan;
|
plan: SubscriptionPlanView;
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
|
gradientIndex?: number;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,6 +41,7 @@ export function SubscriptionPlanCard({
|
|||||||
plan,
|
plan,
|
||||||
selected,
|
selected,
|
||||||
onClick,
|
onClick,
|
||||||
|
gradientIndex = 0,
|
||||||
className,
|
className,
|
||||||
}: SubscriptionPlanCardProps) {
|
}: SubscriptionPlanCardProps) {
|
||||||
const classes = [
|
const classes = [
|
||||||
@@ -41,22 +53,26 @@ export function SubscriptionPlanCard({
|
|||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" ");
|
.join(" ");
|
||||||
|
|
||||||
const perDayStyle = { background: PER_DAY_GRADIENTS[plan.id] };
|
const perDayStyle = {
|
||||||
|
background: PER_DAY_GRADIENTS[gradientIndex % PER_DAY_GRADIENTS.length],
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
aria-pressed={selected}
|
aria-pressed={selected}
|
||||||
aria-label={`${plan.name} plan, $${plan.price}`}
|
aria-label={`${plan.name} plan, ${plan.currencySymbol}${plan.price}`}
|
||||||
className={classes}
|
className={classes}
|
||||||
>
|
>
|
||||||
<p className={styles.name}>{plan.name}</p>
|
<p className={styles.name}>{plan.name}</p>
|
||||||
<div className={styles.priceBlock}>
|
<div className={styles.priceBlock}>
|
||||||
<span className={styles.currency}>$</span>
|
<span className={styles.currency}>{plan.currencySymbol}</span>
|
||||||
<span className={styles.price}>{plan.price}</span>
|
<span className={styles.price}>{plan.price}</span>
|
||||||
</div>
|
</div>
|
||||||
<p className={styles.originalPrice}>${plan.originalPrice}</p>
|
<p className={styles.originalPrice}>
|
||||||
|
{plan.originalPrice ? `${plan.currencySymbol}${plan.originalPrice}` : "\u00a0"}
|
||||||
|
</p>
|
||||||
<div className={styles.perDayBar} style={perDayStyle}>
|
<div className={styles.perDayBar} style={perDayStyle}>
|
||||||
{plan.perDay}
|
{plan.perDay}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -28,11 +28,21 @@
|
|||||||
|
|
||||||
.plansRow {
|
.plansRow {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(3, 1fr);
|
grid-template-columns: repeat(auto-fit, minmax(92px, 1fr));
|
||||||
gap: var(--spacing-sm);
|
gap: var(--spacing-sm);
|
||||||
margin-top: var(--spacing-xl);
|
margin-top: var(--spacing-xl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.plansStatus {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
margin: 0;
|
||||||
|
padding: var(--spacing-md) var(--spacing-xs);
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: var(--font-size-sm);
|
||||||
|
text-align: center;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
.autoRenewCaption {
|
.autoRenewCaption {
|
||||||
margin: var(--spacing-md) 0 0;
|
margin: var(--spacing-md) 0 0;
|
||||||
padding: 0 var(--spacing-xs);
|
padding: 0 var(--spacing-xs);
|
||||||
|
|||||||
@@ -14,48 +14,110 @@
|
|||||||
* 7. 主操作按钮
|
* 7. 主操作按钮
|
||||||
* 8. 协议复选框
|
* 8. 协议复选框
|
||||||
*/
|
*/
|
||||||
import { useState } from "react";
|
import { useEffect, useMemo, useRef } from "react";
|
||||||
|
|
||||||
import { Checkbox, MobileShell } from "@/app/_components/core";
|
import { Checkbox, MobileShell } from "@/app/_components/core";
|
||||||
import { AppConstants } from "@/core/app_constants";
|
import { AppConstants } from "@/core/app_constants";
|
||||||
import {
|
import type { PaymentPlan } from "@/data/dto/payment";
|
||||||
SUBSCRIPTION_PLANS,
|
|
||||||
type SubscriptionPlanId,
|
|
||||||
} from "@/data/constants/subscription-plans";
|
|
||||||
import { VIP_BENEFITS } from "@/data/constants/vip-benefits";
|
import { VIP_BENEFITS } from "@/data/constants/vip-benefits";
|
||||||
import { useUserState } from "@/stores/user/user-context";
|
import {
|
||||||
|
usePaymentDispatch,
|
||||||
|
usePaymentState,
|
||||||
|
} from "@/stores/payment/payment-context";
|
||||||
|
import { useUserDispatch, useUserState } from "@/stores/user/user-context";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
SubscriptionBackLink,
|
SubscriptionBackLink,
|
||||||
SubscriptionBanner,
|
SubscriptionBanner,
|
||||||
SubscriptionBenefitsCard,
|
SubscriptionBenefitsCard,
|
||||||
SubscriptionCheckoutButton,
|
SubscriptionCheckoutButton,
|
||||||
SubscriptionManageButton,
|
SubscriptionCtaButton,
|
||||||
SubscriptionPlanCard,
|
SubscriptionPlanCard,
|
||||||
SubscriptionUserRow,
|
SubscriptionUserRow,
|
||||||
} from "./components";
|
} from "./components";
|
||||||
import styles from "./components/subscription-screen.module.css";
|
import styles from "./components/subscription-screen.module.css";
|
||||||
|
import type { SubscriptionPlanView } from "./components/subscription-plan-card";
|
||||||
|
|
||||||
const FALLBACK_USERNAME = "User name";
|
const FALLBACK_USERNAME = "User name";
|
||||||
|
|
||||||
|
function isVipPlan(plan: PaymentPlan): boolean {
|
||||||
|
return plan.orderType.startsWith("vip_") || plan.planId.startsWith("vip_");
|
||||||
|
}
|
||||||
|
|
||||||
|
function currencySymbol(currency: string): string {
|
||||||
|
if (currency === "CNY") return "¥";
|
||||||
|
if (currency === "USD") return "$";
|
||||||
|
return `${currency} `;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAmount(amountCents: number): string {
|
||||||
|
return (amountCents / 100).toFixed(2).replace(/\.00$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function planCaption(plan: PaymentPlan): string {
|
||||||
|
if (plan.vipDays === null) return "Lifetime";
|
||||||
|
const perDay = plan.amountCents / 100 / Math.max(plan.vipDays, 1);
|
||||||
|
return `${currencySymbol(plan.currency)}${perDay.toFixed(2)}/day`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toPlanView(plan: PaymentPlan, index: number): SubscriptionPlanView {
|
||||||
|
return {
|
||||||
|
id: plan.planId,
|
||||||
|
name: plan.planName,
|
||||||
|
price: formatAmount(plan.amountCents),
|
||||||
|
originalPrice: null,
|
||||||
|
perDay: planCaption(plan),
|
||||||
|
highlight: plan.planId === "vip_monthly" || index === 0,
|
||||||
|
currencySymbol: currencySymbol(plan.currency),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function SubscriptionScreen() {
|
export function SubscriptionScreen() {
|
||||||
const user = useUserState();
|
const user = useUserState();
|
||||||
|
const userDispatch = useUserDispatch();
|
||||||
|
const payment = usePaymentState();
|
||||||
|
const paymentDispatch = usePaymentDispatch();
|
||||||
|
const refreshedPaidOrderRef = useRef<string | null>(null);
|
||||||
|
|
||||||
const initialPlanId =
|
useEffect(() => {
|
||||||
SUBSCRIPTION_PLANS.find((p) => p.highlight)?.id ?? null;
|
if (payment.status === "idle") {
|
||||||
|
paymentDispatch({ type: "PaymentInit" });
|
||||||
|
}
|
||||||
|
}, [payment.status, paymentDispatch]);
|
||||||
|
|
||||||
// 强制类型为 `SubscriptionPlanId` —— 套餐表只有 3 个 id,不会越界
|
useEffect(() => {
|
||||||
const [selectedPlanId, setSelectedPlanId] = useState<SubscriptionPlanId | null>(
|
if (!payment.isPaid || !payment.currentOrderId) return;
|
||||||
initialPlanId as SubscriptionPlanId | null,
|
if (refreshedPaidOrderRef.current === payment.currentOrderId) return;
|
||||||
|
refreshedPaidOrderRef.current = payment.currentOrderId;
|
||||||
|
userDispatch({ type: "UserFetch" });
|
||||||
|
}, [payment.currentOrderId, payment.isPaid, userDispatch]);
|
||||||
|
|
||||||
|
const vipPlans = useMemo(
|
||||||
|
() =>
|
||||||
|
payment.plans
|
||||||
|
.filter(isVipPlan)
|
||||||
|
.map((plan, index) => toPlanView(plan, index)),
|
||||||
|
[payment.plans],
|
||||||
);
|
);
|
||||||
const [agreed, setAgreed] = useState(false);
|
|
||||||
|
|
||||||
const canActivate = selectedPlanId !== null && agreed;
|
const selectedPlan =
|
||||||
const isVip = user.currentUser?.isVip ?? false;
|
vipPlans.find((plan) => plan.id === payment.selectedPlanId) ?? null;
|
||||||
const stripeCustomerId = user.currentUser?.stripeCustomerId ?? null;
|
const isPaymentBusy =
|
||||||
|
payment.isCreatingOrder ||
|
||||||
|
payment.isPollingOrder ||
|
||||||
|
payment.isCheckingVipStatus;
|
||||||
|
const canActivate =
|
||||||
|
selectedPlan !== null && payment.agreed && !isPaymentBusy;
|
||||||
|
const isVip =
|
||||||
|
user.currentUser?.isVip === true ||
|
||||||
|
payment.vipStatus?.isVip === true ||
|
||||||
|
payment.isPaid;
|
||||||
|
|
||||||
const name = user.currentUser?.username ?? FALLBACK_USERNAME;
|
const name = user.currentUser?.username ?? FALLBACK_USERNAME;
|
||||||
const avatarUrl = user.currentUser?.avatarUrl ?? null;
|
const avatarUrl = user.currentUser?.avatarUrl ?? null;
|
||||||
|
const autoRenewCaption = payment.autoRenew
|
||||||
|
? "It will automatically renew upon expiration, and can be canceled at any time"
|
||||||
|
: "This plan is a one-time purchase and will not automatically renew";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MobileShell>
|
<MobileShell>
|
||||||
@@ -76,20 +138,31 @@ export function SubscriptionScreen() {
|
|||||||
className={styles.plansRow}
|
className={styles.plansRow}
|
||||||
aria-label="Choose a subscription plan"
|
aria-label="Choose a subscription plan"
|
||||||
>
|
>
|
||||||
{SUBSCRIPTION_PLANS.map((plan) => (
|
{vipPlans.length > 0 ? (
|
||||||
|
vipPlans.map((plan, index) => (
|
||||||
<SubscriptionPlanCard
|
<SubscriptionPlanCard
|
||||||
key={plan.id}
|
key={plan.id}
|
||||||
plan={plan}
|
plan={plan}
|
||||||
selected={selectedPlanId === plan.id}
|
gradientIndex={index}
|
||||||
onClick={() => setSelectedPlanId(plan.id)}
|
selected={payment.selectedPlanId === plan.id}
|
||||||
|
onClick={() =>
|
||||||
|
paymentDispatch({
|
||||||
|
type: "PaymentPlanSelected",
|
||||||
|
planId: plan.id,
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
))}
|
))
|
||||||
|
) : (
|
||||||
|
<p className={styles.plansStatus}>
|
||||||
|
{payment.isLoadingPlans
|
||||||
|
? "Loading membership plans..."
|
||||||
|
: payment.errorMessage ?? "Membership plans are unavailable."}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<p className={styles.autoRenewCaption}>
|
<p className={styles.autoRenewCaption}>{autoRenewCaption}</p>
|
||||||
It will automatically renew upon expiration, and can be canceled at
|
|
||||||
any time
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<section className={styles.benefitsSlot}>
|
<section className={styles.benefitsSlot}>
|
||||||
<SubscriptionBenefitsCard
|
<SubscriptionBenefitsCard
|
||||||
@@ -99,15 +172,12 @@ export function SubscriptionScreen() {
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div className={styles.ctaSlot}>
|
<div className={styles.ctaSlot}>
|
||||||
{/*
|
|
||||||
* 已为 VIP 的用户 → 显示 Manage VIP 按钮(跳转到 Stripe Customer Portal)
|
|
||||||
* VIP 状态从 `user.isVip` 取(webhook 会设置)
|
|
||||||
*/}
|
|
||||||
{isVip ? (
|
{isVip ? (
|
||||||
<SubscriptionManageButton customerId={stripeCustomerId} />
|
<SubscriptionCtaButton type="button" disabled>
|
||||||
|
VIP Activated
|
||||||
|
</SubscriptionCtaButton>
|
||||||
) : (
|
) : (
|
||||||
<SubscriptionCheckoutButton
|
<SubscriptionCheckoutButton
|
||||||
planId={selectedPlanId ?? "monthly"}
|
|
||||||
disabled={!canActivate}
|
disabled={!canActivate}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -115,8 +185,13 @@ export function SubscriptionScreen() {
|
|||||||
|
|
||||||
<div className={styles.agreementSlot}>
|
<div className={styles.agreementSlot}>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={agreed}
|
checked={payment.agreed}
|
||||||
onChange={setAgreed}
|
onChange={(agreed) =>
|
||||||
|
paymentDispatch({
|
||||||
|
type: "PaymentAgreementChanged",
|
||||||
|
agreed,
|
||||||
|
})
|
||||||
|
}
|
||||||
label={
|
label={
|
||||||
<>
|
<>
|
||||||
I agree to the{" "}
|
I agree to the{" "}
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* 订阅成功回跳页
|
* 订阅成功回跳页
|
||||||
*
|
*
|
||||||
* 流程:
|
* 流程:
|
||||||
* 1. 用户在 Stripe 托管页完成结账
|
* 1. 用户在支付服务托管页完成结账
|
||||||
* 2. Stripe 重定向到 `/subscription/success?session_id=xxx`
|
* 2. 支付服务重定向到 `/subscription/success`
|
||||||
* 3. 这个页面显示 "购买成功" + 调 `getCurrentUser` 刷新 user
|
* 3. 这个页面显示 "购买成功" + 调 `getCurrentUser` 刷新 user
|
||||||
* 4. 点 "返回订阅页" 跳回 `/subscription`
|
* 4. 点 "返回订阅页" 跳回 `/subscription`
|
||||||
*
|
*
|
||||||
* 注意:webhook 会异步触发 + 更新 user.isVip + voiceMinutes
|
* 注意:权益发放由后端支付服务链路异步完成。
|
||||||
* 此页面拿到 session_id 后 轮询几次 getCurrentUser 等待 webhook 完成(避免 webhook 还没到 user 就还没更新的情况)
|
* 此页面轮询几次 getCurrentUser 等待 user 状态完成更新。
|
||||||
*/
|
*/
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
@@ -25,7 +25,7 @@ export default function SubscriptionSuccessPage() {
|
|||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
const hasRefreshed = useRef(false);
|
const hasRefreshed = useRef(false);
|
||||||
|
|
||||||
// 轮询 getCurrentUser 等待 webhook 完成
|
// 轮询 getCurrentUser 等待后端权益发放完成
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hasRefreshed.current) return;
|
if (hasRefreshed.current) return;
|
||||||
hasRefreshed.current = true;
|
hasRefreshed.current = true;
|
||||||
|
|||||||
@@ -5,12 +5,8 @@
|
|||||||
*
|
*
|
||||||
* 原始 Dart: lib/ui/subscription/...
|
* 原始 Dart: lib/ui/subscription/...
|
||||||
*
|
*
|
||||||
* Stripe 接入新增字段:
|
* 当前订阅页优先使用后端 `/api/payment/plans` 返回的套餐。
|
||||||
* - `stripeProductId` / `stripePriceId`:Stripe 后台创建 Product + Price 后拿到的 id
|
* 本常量仅保留给旧 UI / fallback 代码参考。
|
||||||
* - `voiceMinutesPerDay`:该套餐每天给用户的语音分钟数(订阅后每天补充)
|
|
||||||
*
|
|
||||||
* 注:stripeProductId / stripePriceId 没有默认值 —— 为避免硬编码真实 id,由 env 动态注入(见 `src/lib/stripe/stripe-products.ts`)
|
|
||||||
* 本常量表只是 UI 形状 + 业务字段的单一真相源
|
|
||||||
*/
|
*/
|
||||||
export type SubscriptionPlanId = "monthly" | "quarterly" | "annual";
|
export type SubscriptionPlanId = "monthly" | "quarterly" | "annual";
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,10 @@ export class ChatHistoryResponse {
|
|||||||
declare readonly total: number;
|
declare readonly total: number;
|
||||||
declare readonly limit: number;
|
declare readonly limit: number;
|
||||||
declare readonly offset: number;
|
declare readonly offset: number;
|
||||||
|
declare readonly isVip: boolean;
|
||||||
|
declare readonly privateFreeLimit: number;
|
||||||
|
declare readonly privateUsedToday: number;
|
||||||
|
declare readonly privateCanViewFree: boolean;
|
||||||
|
|
||||||
private constructor(input: ChatHistoryResponseInput) {
|
private constructor(input: ChatHistoryResponseInput) {
|
||||||
const data = ChatHistoryResponseSchema.parse(input);
|
const data = ChatHistoryResponseSchema.parse(input);
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ export class ChatMessage {
|
|||||||
declare readonly content: string;
|
declare readonly content: string;
|
||||||
declare readonly id: string;
|
declare readonly id: string;
|
||||||
declare readonly createdAt: string;
|
declare readonly createdAt: string;
|
||||||
|
declare readonly isPrivate: boolean | null;
|
||||||
|
declare readonly privateLocked: boolean | null;
|
||||||
|
declare readonly privateHint: string | null;
|
||||||
|
|
||||||
private constructor(input: ChatMessageInput) {
|
private constructor(input: ChatMessageInput) {
|
||||||
const data = ChatMessageSchema.parse(input);
|
const data = ChatMessageSchema.parse(input);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
ChatSendResponseSchema,
|
ChatSendResponseSchema,
|
||||||
type ChatSendResponseInput,
|
type ChatSendResponseInput,
|
||||||
type ChatSendResponseData,
|
type ChatSendResponseData,
|
||||||
|
type ChatBlockDetailData,
|
||||||
} from "@/data/schemas/chat/chat_send_response";
|
} from "@/data/schemas/chat/chat_send_response";
|
||||||
|
|
||||||
export class ChatSendResponse {
|
export class ChatSendResponse {
|
||||||
@@ -12,13 +13,20 @@ export class ChatSendResponse {
|
|||||||
declare readonly reply: string;
|
declare readonly reply: string;
|
||||||
declare readonly voiceUrl: string;
|
declare readonly voiceUrl: string;
|
||||||
declare readonly audioUrl: string;
|
declare readonly audioUrl: string;
|
||||||
declare readonly intimidadChange: number;
|
declare readonly intimacyChange: number;
|
||||||
declare readonly newIntimacy: number;
|
declare readonly newIntimacy: number;
|
||||||
declare readonly relationshipStage: string;
|
declare readonly relationshipStage: string;
|
||||||
declare readonly currentMood: string;
|
declare readonly currentMood: string;
|
||||||
declare readonly messageId: string;
|
declare readonly messageId: string;
|
||||||
declare readonly isGuest: boolean;
|
declare readonly isGuest: boolean;
|
||||||
declare readonly timestamp: number;
|
declare readonly timestamp: number;
|
||||||
|
declare readonly blocked: boolean | null;
|
||||||
|
declare readonly blockReason: string | null;
|
||||||
|
declare readonly blockDetail: ChatBlockDetailData | null;
|
||||||
|
declare readonly paywallTriggered: boolean;
|
||||||
|
declare readonly showUpgrade: boolean;
|
||||||
|
declare readonly imageType: string | null;
|
||||||
|
declare readonly imageUrl: string | null;
|
||||||
|
|
||||||
private constructor(input: ChatSendResponseInput) {
|
private constructor(input: ChatSendResponseInput) {
|
||||||
const data = ChatSendResponseSchema.parse(input);
|
const data = ChatSendResponseSchema.parse(input);
|
||||||
|
|||||||
@@ -14,3 +14,5 @@ export * from "./send_message_request";
|
|||||||
export * from "./stt_data";
|
export * from "./stt_data";
|
||||||
export * from "./sync_message";
|
export * from "./sync_message";
|
||||||
export * from "./ui_message";
|
export * from "./ui_message";
|
||||||
|
export * from "./unlock_private_request";
|
||||||
|
export * from "./unlock_private_response";
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/**
|
||||||
|
* 私密消息解锁请求 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
UnlockPrivateRequestSchema,
|
||||||
|
type UnlockPrivateRequestData,
|
||||||
|
type UnlockPrivateRequestInput,
|
||||||
|
} from "@/data/schemas/chat/unlock_private_request";
|
||||||
|
|
||||||
|
export class UnlockPrivateRequest {
|
||||||
|
declare readonly messageId: string;
|
||||||
|
|
||||||
|
private constructor(input: UnlockPrivateRequestInput) {
|
||||||
|
const data = UnlockPrivateRequestSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(input: UnlockPrivateRequestInput): UnlockPrivateRequest {
|
||||||
|
return new UnlockPrivateRequest(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): UnlockPrivateRequest {
|
||||||
|
return UnlockPrivateRequest.from(json as UnlockPrivateRequestInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): UnlockPrivateRequestData {
|
||||||
|
return UnlockPrivateRequestSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/**
|
||||||
|
* 私密消息解锁响应 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
UnlockPrivateResponseSchema,
|
||||||
|
type UnlockPrivateReason,
|
||||||
|
type UnlockPrivateResponseData,
|
||||||
|
type UnlockPrivateResponseInput,
|
||||||
|
} from "@/data/schemas/chat/unlock_private_response";
|
||||||
|
|
||||||
|
export class UnlockPrivateResponse {
|
||||||
|
declare readonly unlocked: boolean;
|
||||||
|
declare readonly content: string | null;
|
||||||
|
declare readonly showUpgrade: boolean;
|
||||||
|
declare readonly paywallTriggered: boolean;
|
||||||
|
declare readonly privateFreeLimit: number;
|
||||||
|
declare readonly privateUsedToday: number;
|
||||||
|
declare readonly reason: UnlockPrivateReason;
|
||||||
|
|
||||||
|
private constructor(input: UnlockPrivateResponseInput) {
|
||||||
|
const data = UnlockPrivateResponseSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(input: UnlockPrivateResponseInput): UnlockPrivateResponse {
|
||||||
|
return new UnlockPrivateResponse(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): UnlockPrivateResponse {
|
||||||
|
return UnlockPrivateResponse.from(json as UnlockPrivateResponseInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): UnlockPrivateResponseData {
|
||||||
|
return UnlockPrivateResponseSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/**
|
||||||
|
* 创建支付订单请求 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
CreatePaymentOrderRequestSchema,
|
||||||
|
type CreatePaymentOrderRequestData,
|
||||||
|
type CreatePaymentOrderRequestInput,
|
||||||
|
type PayChannel,
|
||||||
|
} from "@/data/schemas/payment/create_payment_order_request";
|
||||||
|
|
||||||
|
export type { PayChannel };
|
||||||
|
|
||||||
|
export class CreatePaymentOrderRequest {
|
||||||
|
declare readonly planId: string;
|
||||||
|
declare readonly payChannel: PayChannel;
|
||||||
|
declare readonly autoRenew: boolean;
|
||||||
|
|
||||||
|
private constructor(input: CreatePaymentOrderRequestInput) {
|
||||||
|
const data = CreatePaymentOrderRequestSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(
|
||||||
|
input: CreatePaymentOrderRequestInput,
|
||||||
|
): CreatePaymentOrderRequest {
|
||||||
|
return new CreatePaymentOrderRequest(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): CreatePaymentOrderRequest {
|
||||||
|
return CreatePaymentOrderRequest.from(
|
||||||
|
json as CreatePaymentOrderRequestInput,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): CreatePaymentOrderRequestData {
|
||||||
|
return CreatePaymentOrderRequestSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/**
|
||||||
|
* 创建支付订单响应 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
CreatePaymentOrderResponseSchema,
|
||||||
|
type CreatePaymentOrderResponseData,
|
||||||
|
type CreatePaymentOrderResponseInput,
|
||||||
|
} from "@/data/schemas/payment/create_payment_order_response";
|
||||||
|
|
||||||
|
export class CreatePaymentOrderResponse {
|
||||||
|
declare readonly orderId: string;
|
||||||
|
declare readonly payParams: Record<string, unknown>;
|
||||||
|
|
||||||
|
private constructor(input: CreatePaymentOrderResponseInput) {
|
||||||
|
const data = CreatePaymentOrderResponseSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(
|
||||||
|
input: CreatePaymentOrderResponseInput,
|
||||||
|
): CreatePaymentOrderResponse {
|
||||||
|
return new CreatePaymentOrderResponse(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): CreatePaymentOrderResponse {
|
||||||
|
return CreatePaymentOrderResponse.from(
|
||||||
|
json as CreatePaymentOrderResponseInput,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): CreatePaymentOrderResponseData {
|
||||||
|
return CreatePaymentOrderResponseSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
/**
|
||||||
|
* @file Payment DTO barrel.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export * from "./create_payment_order_request";
|
||||||
|
export * from "./create_payment_order_response";
|
||||||
|
export * from "./payment_order_status_response";
|
||||||
|
export * from "./payment_plan";
|
||||||
|
export * from "./payment_plans_response";
|
||||||
|
export * from "./payment_vip_status_response";
|
||||||
|
export * from "./payment_websocket_event";
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/**
|
||||||
|
* 支付订单状态响应 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
PaymentOrderStatusResponseSchema,
|
||||||
|
type PaymentOrderStatus,
|
||||||
|
type PaymentOrderStatusResponseData,
|
||||||
|
type PaymentOrderStatusResponseInput,
|
||||||
|
} from "@/data/schemas/payment/payment_order_status_response";
|
||||||
|
|
||||||
|
export type { PaymentOrderStatus };
|
||||||
|
|
||||||
|
export class PaymentOrderStatusResponse {
|
||||||
|
declare readonly orderId: string;
|
||||||
|
declare readonly status: PaymentOrderStatus;
|
||||||
|
declare readonly orderType: string;
|
||||||
|
declare readonly planId: string;
|
||||||
|
|
||||||
|
private constructor(input: PaymentOrderStatusResponseInput) {
|
||||||
|
const data = PaymentOrderStatusResponseSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(
|
||||||
|
input: PaymentOrderStatusResponseInput,
|
||||||
|
): PaymentOrderStatusResponse {
|
||||||
|
return new PaymentOrderStatusResponse(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): PaymentOrderStatusResponse {
|
||||||
|
return PaymentOrderStatusResponse.from(
|
||||||
|
json as PaymentOrderStatusResponseInput,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): PaymentOrderStatusResponseData {
|
||||||
|
return PaymentOrderStatusResponseSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/**
|
||||||
|
* 支付套餐 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
PaymentPlanSchema,
|
||||||
|
type PaymentPlanData,
|
||||||
|
type PaymentPlanInput,
|
||||||
|
} from "@/data/schemas/payment/payment_plan";
|
||||||
|
|
||||||
|
export class PaymentPlan {
|
||||||
|
declare readonly planId: string;
|
||||||
|
declare readonly planName: string;
|
||||||
|
declare readonly orderType: string;
|
||||||
|
declare readonly amountCents: number;
|
||||||
|
declare readonly currency: string;
|
||||||
|
declare readonly vipDays: number | null;
|
||||||
|
declare readonly dolAmount: number | null;
|
||||||
|
|
||||||
|
private constructor(input: PaymentPlanInput) {
|
||||||
|
const data = PaymentPlanSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(input: PaymentPlanInput): PaymentPlan {
|
||||||
|
return new PaymentPlan(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): PaymentPlan {
|
||||||
|
return PaymentPlan.from(json as PaymentPlanInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): PaymentPlanData {
|
||||||
|
return PaymentPlanSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/**
|
||||||
|
* 支付套餐列表响应 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
PaymentPlansResponseSchema,
|
||||||
|
type PaymentPlansResponseData,
|
||||||
|
type PaymentPlansResponseInput,
|
||||||
|
} from "@/data/schemas/payment/payment_plans_response";
|
||||||
|
|
||||||
|
import { PaymentPlan } from "./payment_plan";
|
||||||
|
|
||||||
|
export class PaymentPlansResponse {
|
||||||
|
declare readonly plans: PaymentPlan[];
|
||||||
|
|
||||||
|
private constructor(input: PaymentPlansResponseInput) {
|
||||||
|
const data = PaymentPlansResponseSchema.parse(input);
|
||||||
|
Object.assign(this, {
|
||||||
|
plans: data.plans.map((plan) => PaymentPlan.from(plan)),
|
||||||
|
});
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(input: PaymentPlansResponseInput): PaymentPlansResponse {
|
||||||
|
return new PaymentPlansResponse(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): PaymentPlansResponse {
|
||||||
|
return PaymentPlansResponse.from(json as PaymentPlansResponseInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): PaymentPlansResponseData {
|
||||||
|
return {
|
||||||
|
plans: this.plans.map((plan) => plan.toJson()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* VIP 状态响应 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
PaymentVipStatusResponseSchema,
|
||||||
|
type PaymentVipStatusResponseData,
|
||||||
|
type PaymentVipStatusResponseInput,
|
||||||
|
} from "@/data/schemas/payment/payment_vip_status_response";
|
||||||
|
|
||||||
|
export class PaymentVipStatusResponse {
|
||||||
|
declare readonly isVip: boolean;
|
||||||
|
declare readonly vipExpiresAt: string | null;
|
||||||
|
|
||||||
|
private constructor(input: PaymentVipStatusResponseInput) {
|
||||||
|
const data = PaymentVipStatusResponseSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(input: PaymentVipStatusResponseInput): PaymentVipStatusResponse {
|
||||||
|
return new PaymentVipStatusResponse(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): PaymentVipStatusResponse {
|
||||||
|
return PaymentVipStatusResponse.from(
|
||||||
|
json as PaymentVipStatusResponseInput,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): PaymentVipStatusResponseData {
|
||||||
|
return PaymentVipStatusResponseSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* 支付 WebSocket 事件 DTO
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
PaymentWebSocketEventSchema,
|
||||||
|
type PaymentWebSocketEventData,
|
||||||
|
type PaymentWebSocketEventInput,
|
||||||
|
} from "@/data/schemas/payment/payment_websocket_event";
|
||||||
|
|
||||||
|
export class PaymentWebSocketEvent {
|
||||||
|
declare readonly type: PaymentWebSocketEventData["type"];
|
||||||
|
declare readonly orderId: string;
|
||||||
|
|
||||||
|
private constructor(input: PaymentWebSocketEventInput) {
|
||||||
|
const data = PaymentWebSocketEventSchema.parse(input);
|
||||||
|
Object.assign(this, data);
|
||||||
|
Object.freeze(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(input: PaymentWebSocketEventInput): PaymentWebSocketEvent {
|
||||||
|
return new PaymentWebSocketEvent(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromJson(json: unknown): PaymentWebSocketEvent {
|
||||||
|
return PaymentWebSocketEvent.from(json as PaymentWebSocketEventInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJson(): PaymentWebSocketEventData {
|
||||||
|
return PaymentWebSocketEventSchema.parse(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type { PaymentWebSocketEventData };
|
||||||
@@ -24,14 +24,10 @@ export class User {
|
|||||||
declare readonly avatarUrl: string;
|
declare readonly avatarUrl: string;
|
||||||
declare readonly loginProvider: string;
|
declare readonly loginProvider: string;
|
||||||
declare readonly isGuest: boolean;
|
declare readonly isGuest: boolean;
|
||||||
/** 是否为 VIP 会员(Stripe webhook 更新) */
|
/** 是否为 VIP 会员 */
|
||||||
declare readonly isVip: boolean;
|
declare readonly isVip: boolean;
|
||||||
/** 语音聊天剩余分钟数(Stripe webhook 更新) */
|
/** 语音聊天剩余分钟数 */
|
||||||
declare readonly voiceMinutesRemaining: number;
|
declare readonly voiceMinutesRemaining: number;
|
||||||
/** Stripe Customer ID —— 首次 Checkout 完成后由 webhook 设置 */
|
|
||||||
declare readonly stripeCustomerId: string | null;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private constructor(input: UserInput) {
|
private constructor(input: UserInput) {
|
||||||
const data = UserSchema.parse(input);
|
const data = UserSchema.parse(input);
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ export const UserViewSchema = z.object({
|
|||||||
isGuest: z.boolean(),
|
isGuest: z.boolean(),
|
||||||
isVip: z.boolean(),
|
isVip: z.boolean(),
|
||||||
voiceMinutesRemaining: z.number(),
|
voiceMinutesRemaining: z.number(),
|
||||||
stripeCustomerId: z.string().nullable(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export type UserView = z.infer<typeof UserViewSchema>;
|
export type UserView = z.infer<typeof UserViewSchema>;
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ import {
|
|||||||
ChatMessage,
|
ChatMessage,
|
||||||
ChatSendResponse,
|
ChatSendResponse,
|
||||||
SendMessageRequest,
|
SendMessageRequest,
|
||||||
|
UnlockPrivateRequest,
|
||||||
|
UnlockPrivateResponse,
|
||||||
} from "@/data/dto/chat";
|
} from "@/data/dto/chat";
|
||||||
import { Result } from "@/utils";
|
import { Result } from "@/utils";
|
||||||
import type { IChatRepository } from "@/data/repositories/interfaces";
|
import type { IChatRepository } from "@/data/repositories/interfaces";
|
||||||
@@ -57,6 +59,15 @@ export class ChatRepository implements IChatRepository {
|
|||||||
return Result.wrap(() => this.api.getHistory(limit, offset));
|
return Result.wrap(() => this.api.getHistory(limit, offset));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 解锁私密消息。 */
|
||||||
|
async unlockPrivateMessage(
|
||||||
|
messageId: string,
|
||||||
|
): Promise<Result<UnlockPrivateResponse>> {
|
||||||
|
return Result.wrap(() =>
|
||||||
|
this.api.unlockPrivateMessage(UnlockPrivateRequest.from({ messageId })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ============ 本地(Dexie)操作 ============
|
// ============ 本地(Dexie)操作 ============
|
||||||
|
|
||||||
/** 把一条消息写入本地存储。 */
|
/** 把一条消息写入本地存储。 */
|
||||||
|
|||||||
@@ -5,8 +5,10 @@
|
|||||||
export * from "./auth_repository";
|
export * from "./auth_repository";
|
||||||
export * from "./chat_repository";
|
export * from "./chat_repository";
|
||||||
export * from "./metrics_repository";
|
export * from "./metrics_repository";
|
||||||
|
export * from "./payment_repository";
|
||||||
export * from "./user_repository";
|
export * from "./user_repository";
|
||||||
export * from "./interfaces/iauth_repository";
|
export * from "./interfaces/iauth_repository";
|
||||||
export * from "./interfaces/ichat_repository";
|
export * from "./interfaces/ichat_repository";
|
||||||
export * from "./interfaces/imetrics_repository";
|
export * from "./interfaces/imetrics_repository";
|
||||||
|
export * from "./interfaces/ipayment_repository";
|
||||||
export * from "./interfaces/iuser_repository";
|
export * from "./interfaces/iuser_repository";
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import type {
|
|||||||
ChatHistoryResponse,
|
ChatHistoryResponse,
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
ChatSendResponse,
|
ChatSendResponse,
|
||||||
|
UnlockPrivateResponse,
|
||||||
} from "@/data/dto/chat";
|
} from "@/data/dto/chat";
|
||||||
|
|
||||||
export interface IChatRepository {
|
export interface IChatRepository {
|
||||||
@@ -28,6 +29,9 @@ export interface IChatRepository {
|
|||||||
/** 获取聊天历史,分页参数默认 limit=50, offset=0。 */
|
/** 获取聊天历史,分页参数默认 limit=50, offset=0。 */
|
||||||
getHistory(limit?: number, offset?: number): Promise<Result<ChatHistoryResponse>>;
|
getHistory(limit?: number, offset?: number): Promise<Result<ChatHistoryResponse>>;
|
||||||
|
|
||||||
|
/** 解锁私密消息。 */
|
||||||
|
unlockPrivateMessage(messageId: string): Promise<Result<UnlockPrivateResponse>>;
|
||||||
|
|
||||||
/** 把一条消息写入本地存储。 */
|
/** 把一条消息写入本地存储。 */
|
||||||
saveMessageToLocal(message: ChatMessage): Promise<Result<void>>;
|
saveMessageToLocal(message: ChatMessage): Promise<Result<void>>;
|
||||||
|
|
||||||
|
|||||||
@@ -5,4 +5,5 @@
|
|||||||
export * from "./iauth_repository";
|
export * from "./iauth_repository";
|
||||||
export * from "./ichat_repository";
|
export * from "./ichat_repository";
|
||||||
export * from "./imetrics_repository";
|
export * from "./imetrics_repository";
|
||||||
|
export * from "./ipayment_repository";
|
||||||
export * from "./iuser_repository";
|
export * from "./iuser_repository";
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IPaymentRepository 接口
|
||||||
|
*/
|
||||||
|
import type {
|
||||||
|
CreatePaymentOrderResponse,
|
||||||
|
PayChannel,
|
||||||
|
PaymentOrderStatusResponse,
|
||||||
|
PaymentPlansResponse,
|
||||||
|
PaymentVipStatusResponse,
|
||||||
|
} from "@/data/dto/payment";
|
||||||
|
import type { Result } from "@/utils/result";
|
||||||
|
|
||||||
|
export interface IPaymentRepository {
|
||||||
|
/** 获取套餐列表。 */
|
||||||
|
getPlans(): Promise<Result<PaymentPlansResponse>>;
|
||||||
|
|
||||||
|
/** 创建支付订单。 */
|
||||||
|
createOrder(
|
||||||
|
planId: string,
|
||||||
|
payChannel: PayChannel,
|
||||||
|
autoRenew: boolean,
|
||||||
|
): Promise<Result<CreatePaymentOrderResponse>>;
|
||||||
|
|
||||||
|
/** 查询支付订单状态。 */
|
||||||
|
getOrderStatus(orderId: string): Promise<Result<PaymentOrderStatusResponse>>;
|
||||||
|
|
||||||
|
/** 查询当前用户 VIP 状态。 */
|
||||||
|
getVipStatus(): Promise<Result<PaymentVipStatusResponse>>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PaymentRepository
|
||||||
|
*
|
||||||
|
* 支付 / 付费墙相关远程调用。
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
CreatePaymentOrderRequest,
|
||||||
|
CreatePaymentOrderResponse,
|
||||||
|
PayChannel,
|
||||||
|
PaymentOrderStatusResponse,
|
||||||
|
PaymentPlansResponse,
|
||||||
|
PaymentVipStatusResponse,
|
||||||
|
} from "@/data/dto/payment";
|
||||||
|
import { PaymentApi, paymentApi } from "@/data/services/api";
|
||||||
|
import type { IPaymentRepository } from "@/data/repositories/interfaces";
|
||||||
|
import { Result } from "@/utils/result";
|
||||||
|
|
||||||
|
export class PaymentRepository implements IPaymentRepository {
|
||||||
|
constructor(private readonly api: PaymentApi) {}
|
||||||
|
|
||||||
|
/** 获取套餐列表。 */
|
||||||
|
async getPlans(): Promise<Result<PaymentPlansResponse>> {
|
||||||
|
return Result.wrap(() => this.api.getPlans());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 创建支付订单。 */
|
||||||
|
async createOrder(
|
||||||
|
planId: string,
|
||||||
|
payChannel: PayChannel,
|
||||||
|
autoRenew: boolean,
|
||||||
|
): Promise<Result<CreatePaymentOrderResponse>> {
|
||||||
|
const request = CreatePaymentOrderRequest.from({
|
||||||
|
planId,
|
||||||
|
payChannel,
|
||||||
|
autoRenew,
|
||||||
|
});
|
||||||
|
return Result.wrap(() => this.api.createOrder(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查询支付订单状态。 */
|
||||||
|
async getOrderStatus(
|
||||||
|
orderId: string,
|
||||||
|
): Promise<Result<PaymentOrderStatusResponse>> {
|
||||||
|
return Result.wrap(() => this.api.getOrderStatus(orderId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 查询当前用户 VIP 状态。 */
|
||||||
|
async getVipStatus(): Promise<Result<PaymentVipStatusResponse>> {
|
||||||
|
return Result.wrap(() => this.api.getVipStatus());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 全局单例。 */
|
||||||
|
export const paymentRepository = new PaymentRepository(paymentApi);
|
||||||
@@ -10,6 +10,10 @@ export const ChatHistoryResponseSchema = z.object({
|
|||||||
total: z.number().default(0),
|
total: z.number().default(0),
|
||||||
limit: z.number(),
|
limit: z.number(),
|
||||||
offset: z.number(),
|
offset: z.number(),
|
||||||
|
isVip: z.boolean().default(false),
|
||||||
|
privateFreeLimit: z.number().default(0),
|
||||||
|
privateUsedToday: z.number().default(0),
|
||||||
|
privateCanViewFree: z.boolean().default(false),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type ChatHistoryResponseInput = z.input<typeof ChatHistoryResponseSchema>;
|
export type ChatHistoryResponseInput = z.input<typeof ChatHistoryResponseSchema>;
|
||||||
|
|||||||
@@ -4,12 +4,21 @@
|
|||||||
*/
|
*/
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
export const ChatMessageSchema = z.object({
|
export const ChatMessageSchema = z
|
||||||
|
.object({
|
||||||
role: z.string(),
|
role: z.string(),
|
||||||
content: z.string(),
|
content: z.string(),
|
||||||
id: z.string().default(""),
|
id: z.string().default(""),
|
||||||
createdAt: z.string().default(""),
|
createdAt: z.string().default(""),
|
||||||
});
|
created_at: z.string().optional(),
|
||||||
|
isPrivate: z.boolean().nullable().default(null),
|
||||||
|
privateLocked: z.boolean().nullable().default(null),
|
||||||
|
privateHint: z.string().nullable().default(null),
|
||||||
|
})
|
||||||
|
.transform(({ created_at, ...data }) => ({
|
||||||
|
...data,
|
||||||
|
createdAt: data.createdAt || created_at || "",
|
||||||
|
}));
|
||||||
|
|
||||||
export type ChatMessageInput = z.input<typeof ChatMessageSchema>;
|
export type ChatMessageInput = z.input<typeof ChatMessageSchema>;
|
||||||
export type ChatMessageData = z.output<typeof ChatMessageSchema>;
|
export type ChatMessageData = z.output<typeof ChatMessageSchema>;
|
||||||
|
|||||||
@@ -4,6 +4,12 @@
|
|||||||
*/
|
*/
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const ChatBlockDetailSchema = z.object({
|
||||||
|
type: z.string(),
|
||||||
|
usedToday: z.number(),
|
||||||
|
limit: z.number(),
|
||||||
|
});
|
||||||
|
|
||||||
export const ChatSendResponseSchema = z.object({
|
export const ChatSendResponseSchema = z.object({
|
||||||
mode: z.string().default(""),
|
mode: z.string().default(""),
|
||||||
reply: z.string(),
|
reply: z.string(),
|
||||||
@@ -17,7 +23,15 @@ export const ChatSendResponseSchema = z.object({
|
|||||||
isGuest: z.boolean().default(false),
|
isGuest: z.boolean().default(false),
|
||||||
// 函数式 default —— 每次 parse 时重新调 Date.now()(后端不返回 timestamp 时用当下时间)
|
// 函数式 default —— 每次 parse 时重新调 Date.now()(后端不返回 timestamp 时用当下时间)
|
||||||
timestamp: z.number().default(() => Date.now()),
|
timestamp: z.number().default(() => Date.now()),
|
||||||
|
blocked: z.boolean().nullable().default(null),
|
||||||
|
blockReason: z.string().nullable().default(null),
|
||||||
|
blockDetail: ChatBlockDetailSchema.nullable().default(null),
|
||||||
|
paywallTriggered: z.boolean().default(false),
|
||||||
|
showUpgrade: z.boolean().default(false),
|
||||||
|
imageType: z.string().nullable().default(null),
|
||||||
|
imageUrl: z.string().nullable().default(null),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type ChatSendResponseInput = z.input<typeof ChatSendResponseSchema>;
|
export type ChatSendResponseInput = z.input<typeof ChatSendResponseSchema>;
|
||||||
export type ChatSendResponseData = z.output<typeof ChatSendResponseSchema>;
|
export type ChatSendResponseData = z.output<typeof ChatSendResponseSchema>;
|
||||||
|
export type ChatBlockDetailData = z.output<typeof ChatBlockDetailSchema>;
|
||||||
|
|||||||
@@ -12,3 +12,5 @@ export * from "./image_upload_response";
|
|||||||
export * from "./send_message_request";
|
export * from "./send_message_request";
|
||||||
export * from "./stt_data";
|
export * from "./stt_data";
|
||||||
export * from "./sync_message";
|
export * from "./sync_message";
|
||||||
|
export * from "./unlock_private_request";
|
||||||
|
export * from "./unlock_private_response";
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* 私密消息解锁请求
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const UnlockPrivateRequestSchema = z.object({
|
||||||
|
messageId: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type UnlockPrivateRequestInput = z.input<
|
||||||
|
typeof UnlockPrivateRequestSchema
|
||||||
|
>;
|
||||||
|
export type UnlockPrivateRequestData = z.output<
|
||||||
|
typeof UnlockPrivateRequestSchema
|
||||||
|
>;
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/**
|
||||||
|
* 私密消息解锁响应
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const UnlockPrivateReasonSchema = z.enum([
|
||||||
|
"ok",
|
||||||
|
"quota_exceeded",
|
||||||
|
"not_private",
|
||||||
|
"not_found",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const UnlockPrivateResponseSchema = z.object({
|
||||||
|
unlocked: z.boolean(),
|
||||||
|
content: z.string().nullable(),
|
||||||
|
showUpgrade: z.boolean(),
|
||||||
|
paywallTriggered: z.boolean(),
|
||||||
|
privateFreeLimit: z.number(),
|
||||||
|
privateUsedToday: z.number(),
|
||||||
|
reason: UnlockPrivateReasonSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type UnlockPrivateReason = z.output<typeof UnlockPrivateReasonSchema>;
|
||||||
|
export type UnlockPrivateResponseInput = z.input<
|
||||||
|
typeof UnlockPrivateResponseSchema
|
||||||
|
>;
|
||||||
|
export type UnlockPrivateResponseData = z.output<
|
||||||
|
typeof UnlockPrivateResponseSchema
|
||||||
|
>;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/**
|
||||||
|
* 创建支付订单请求
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const PayChannelSchema = z.enum(["stripe", "ezpay"]);
|
||||||
|
|
||||||
|
export const CreatePaymentOrderRequestSchema = z.object({
|
||||||
|
planId: z.string(),
|
||||||
|
payChannel: PayChannelSchema,
|
||||||
|
autoRenew: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PayChannel = z.output<typeof PayChannelSchema>;
|
||||||
|
export type CreatePaymentOrderRequestInput = z.input<
|
||||||
|
typeof CreatePaymentOrderRequestSchema
|
||||||
|
>;
|
||||||
|
export type CreatePaymentOrderRequestData = z.output<
|
||||||
|
typeof CreatePaymentOrderRequestSchema
|
||||||
|
>;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* 创建支付订单响应
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const CreatePaymentOrderResponseSchema = z.object({
|
||||||
|
orderId: z.string(),
|
||||||
|
payParams: z.record(z.string(), z.unknown()),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreatePaymentOrderResponseInput = z.input<
|
||||||
|
typeof CreatePaymentOrderResponseSchema
|
||||||
|
>;
|
||||||
|
export type CreatePaymentOrderResponseData = z.output<
|
||||||
|
typeof CreatePaymentOrderResponseSchema
|
||||||
|
>;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
/**
|
||||||
|
* @file Payment schema barrel.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export * from "./create_payment_order_request";
|
||||||
|
export * from "./create_payment_order_response";
|
||||||
|
export * from "./payment_order_status_response";
|
||||||
|
export * from "./payment_plan";
|
||||||
|
export * from "./payment_plans_response";
|
||||||
|
export * from "./payment_vip_status_response";
|
||||||
|
export * from "./payment_websocket_event";
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
* 支付订单状态响应
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const PaymentOrderStatusSchema = z.enum(["pending", "paid", "failed"]);
|
||||||
|
|
||||||
|
export const PaymentOrderStatusResponseSchema = z.object({
|
||||||
|
orderId: z.string(),
|
||||||
|
status: PaymentOrderStatusSchema,
|
||||||
|
orderType: z.string(),
|
||||||
|
planId: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PaymentOrderStatus = z.output<typeof PaymentOrderStatusSchema>;
|
||||||
|
export type PaymentOrderStatusResponseInput = z.input<
|
||||||
|
typeof PaymentOrderStatusResponseSchema
|
||||||
|
>;
|
||||||
|
export type PaymentOrderStatusResponseData = z.output<
|
||||||
|
typeof PaymentOrderStatusResponseSchema
|
||||||
|
>;
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/**
|
||||||
|
* 支付套餐
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
const PaymentPlanWireSchema = z.object({
|
||||||
|
plan_id: z.string(),
|
||||||
|
plan_name: z.string(),
|
||||||
|
order_type: z.string(),
|
||||||
|
amount_cents: z.number(),
|
||||||
|
currency: z.string(),
|
||||||
|
vip_days: z.number().nullable(),
|
||||||
|
dol_amount: z.number().nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const PaymentPlanSchema = z
|
||||||
|
.preprocess((value) => {
|
||||||
|
if (!value || typeof value !== "object") return value;
|
||||||
|
const data = value as Record<string, unknown>;
|
||||||
|
if ("planId" in data) {
|
||||||
|
return {
|
||||||
|
plan_id: data.planId,
|
||||||
|
plan_name: data.planName,
|
||||||
|
order_type: data.orderType,
|
||||||
|
amount_cents: data.amountCents,
|
||||||
|
currency: data.currency,
|
||||||
|
vip_days: data.vipDays,
|
||||||
|
dol_amount: data.dolAmount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}, PaymentPlanWireSchema)
|
||||||
|
.transform((data) => ({
|
||||||
|
planId: data.plan_id,
|
||||||
|
planName: data.plan_name,
|
||||||
|
orderType: data.order_type,
|
||||||
|
amountCents: data.amount_cents,
|
||||||
|
currency: data.currency,
|
||||||
|
vipDays: data.vip_days,
|
||||||
|
dolAmount: data.dol_amount,
|
||||||
|
}));
|
||||||
|
|
||||||
|
export type PaymentPlanInput = z.input<typeof PaymentPlanSchema>;
|
||||||
|
export type PaymentPlanData = z.output<typeof PaymentPlanSchema>;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 支付套餐列表响应
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { PaymentPlanSchema } from "./payment_plan";
|
||||||
|
|
||||||
|
export const PaymentPlansResponseSchema = z.object({
|
||||||
|
plans: z.array(PaymentPlanSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PaymentPlansResponseInput = z.input<
|
||||||
|
typeof PaymentPlansResponseSchema
|
||||||
|
>;
|
||||||
|
export type PaymentPlansResponseData = z.output<
|
||||||
|
typeof PaymentPlansResponseSchema
|
||||||
|
>;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* VIP 状态响应
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const PaymentVipStatusResponseSchema = z.object({
|
||||||
|
isVip: z.boolean(),
|
||||||
|
vipExpiresAt: z.string().nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PaymentVipStatusResponseInput = z.input<
|
||||||
|
typeof PaymentVipStatusResponseSchema
|
||||||
|
>;
|
||||||
|
export type PaymentVipStatusResponseData = z.output<
|
||||||
|
typeof PaymentVipStatusResponseSchema
|
||||||
|
>;
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
/**
|
||||||
|
* 支付 WebSocket 事件
|
||||||
|
*/
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const PaymentSuccessVipEventSchema = z.object({
|
||||||
|
type: z.literal("payment_success"),
|
||||||
|
orderId: z.string(),
|
||||||
|
payType: z.literal("vip"),
|
||||||
|
planName: z.string(),
|
||||||
|
vipExpiresAt: z.string().nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const PaymentSuccessDolEventSchema = z.object({
|
||||||
|
type: z.literal("payment_success"),
|
||||||
|
orderId: z.string(),
|
||||||
|
payType: z.literal("dol"),
|
||||||
|
planName: z.string(),
|
||||||
|
dolAmount: z.number(),
|
||||||
|
dolBalance: z.number(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const PaymentFailedEventSchema = z.object({
|
||||||
|
type: z.literal("payment_failed"),
|
||||||
|
orderId: z.string(),
|
||||||
|
info: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const PaymentSuccessEventSchema = z.discriminatedUnion("payType", [
|
||||||
|
PaymentSuccessVipEventSchema,
|
||||||
|
PaymentSuccessDolEventSchema,
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const PaymentWebSocketEventSchema = z.union([
|
||||||
|
PaymentSuccessEventSchema,
|
||||||
|
PaymentFailedEventSchema,
|
||||||
|
]);
|
||||||
|
|
||||||
|
export type PaymentSuccessVipEventData = z.output<
|
||||||
|
typeof PaymentSuccessVipEventSchema
|
||||||
|
>;
|
||||||
|
export type PaymentSuccessDolEventData = z.output<
|
||||||
|
typeof PaymentSuccessDolEventSchema
|
||||||
|
>;
|
||||||
|
export type PaymentFailedEventData = z.output<typeof PaymentFailedEventSchema>;
|
||||||
|
export type PaymentSuccessEventData = z.output<typeof PaymentSuccessEventSchema>;
|
||||||
|
export type PaymentWebSocketEventInput = z.input<
|
||||||
|
typeof PaymentWebSocketEventSchema
|
||||||
|
>;
|
||||||
|
export type PaymentWebSocketEventData = z.output<
|
||||||
|
typeof PaymentWebSocketEventSchema
|
||||||
|
>;
|
||||||
@@ -27,12 +27,10 @@ export const UserSchema = z.object({
|
|||||||
avatarUrl: stringOrEmpty,
|
avatarUrl: stringOrEmpty,
|
||||||
loginProvider: stringOrEmpty,
|
loginProvider: stringOrEmpty,
|
||||||
isGuest: booleanOrFalse,
|
isGuest: booleanOrFalse,
|
||||||
/** 是否为 VIP 会员(订阅中或未过期) —— Stripe webhook 更新 */
|
/** 是否为 VIP 会员(订阅中或未过期) */
|
||||||
isVip: booleanOrFalse,
|
isVip: booleanOrFalse,
|
||||||
/** 语音聊天剩余分钟数(订阅生效后每天补充;用完为 0 不变) */
|
/** 语音聊天剩余分钟数(订阅生效后每天补充;用完为 0 不变) */
|
||||||
voiceMinutesRemaining: numberOrZero,
|
voiceMinutesRemaining: numberOrZero,
|
||||||
/** Stripe Customer ID —— 首次 Checkout 完成后由 webhook 设置,用于 Customer Portal 自助管理 */
|
|
||||||
stripeCustomerId: z.string().nullable().default(null),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export type UserInput = z.input<typeof UserSchema>;
|
export type UserInput = z.input<typeof UserSchema>;
|
||||||
|
|||||||
@@ -71,13 +71,19 @@ export class ApiPath {
|
|||||||
|
|
||||||
// ============ 支付相关 ============
|
// ============ 支付相关 ============
|
||||||
/** 创建充值订单 */
|
/** 创建充值订单 */
|
||||||
static readonly paymentCreateOrder = `${ApiPath._payment}/order/create`;
|
static readonly paymentCreateOrder = `${ApiPath._payment}/create-order`;
|
||||||
|
|
||||||
/** 查询订单状态 */
|
/** 查询订单状态 */
|
||||||
static readonly paymentOrderStatus = `${ApiPath._payment}/order/status`;
|
static readonly paymentOrderStatus = `${ApiPath._payment}/order-status`;
|
||||||
|
|
||||||
/** 获取商品套餐列表 */
|
/** 获取商品套餐列表 */
|
||||||
static readonly paymentProducts = `${ApiPath._payment}/products`;
|
static readonly paymentPlans = `${ApiPath._payment}/plans`;
|
||||||
|
|
||||||
|
/** 查询当前用户 VIP 状态 */
|
||||||
|
static readonly paymentVipStatus = `${ApiPath._payment}/vip-status`;
|
||||||
|
|
||||||
|
/** @deprecated PAYWALL_API 使用 paymentPlans。 */
|
||||||
|
static readonly paymentProducts = ApiPath.paymentPlans;
|
||||||
|
|
||||||
/** 申请退款 */
|
/** 申请退款 */
|
||||||
static readonly paymentRefund = `${ApiPath._payment}/refund`;
|
static readonly paymentRefund = `${ApiPath._payment}/refund`;
|
||||||
@@ -103,6 +109,9 @@ export class ApiPath {
|
|||||||
/** 上传图片 */
|
/** 上传图片 */
|
||||||
static readonly chatUploadImage = `${ApiPath._chat}/upload-image`;
|
static readonly chatUploadImage = `${ApiPath._chat}/upload-image`;
|
||||||
|
|
||||||
|
/** 解锁私密消息 */
|
||||||
|
static readonly chatUnlockPrivate = `${ApiPath._chat}/unlock-private`;
|
||||||
|
|
||||||
// ============ 数据看板相关 ============
|
// ============ 数据看板相关 ============
|
||||||
private static readonly _metrics = `${ApiPath._baseUrl}/metrics`;
|
private static readonly _metrics = `${ApiPath._baseUrl}/metrics`;
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import {
|
|||||||
SendMessageRequest,
|
SendMessageRequest,
|
||||||
SttData,
|
SttData,
|
||||||
SyncMessage,
|
SyncMessage,
|
||||||
|
UnlockPrivateRequest,
|
||||||
|
UnlockPrivateResponse,
|
||||||
} from "@/data/dto/chat";
|
} from "@/data/dto/chat";
|
||||||
|
|
||||||
export class ChatApi {
|
export class ChatApi {
|
||||||
@@ -81,6 +83,24 @@ export class ChatApi {
|
|||||||
unwrap(env) as Record<string, unknown>
|
unwrap(env) as Record<string, unknown>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解锁私密消息
|
||||||
|
*/
|
||||||
|
async unlockPrivateMessage(
|
||||||
|
body: UnlockPrivateRequest,
|
||||||
|
): Promise<UnlockPrivateResponse> {
|
||||||
|
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||||
|
ApiPath.chatUnlockPrivate,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: body.toJson(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return UnlockPrivateResponse.fromJson(
|
||||||
|
unwrap(env) as Record<string, unknown>,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -8,5 +8,6 @@ export * from "./auth_api";
|
|||||||
export * from "./chat_api";
|
export * from "./chat_api";
|
||||||
export * from "./http_client";
|
export * from "./http_client";
|
||||||
export * from "./metrics_api";
|
export * from "./metrics_api";
|
||||||
|
export * from "./payment_api";
|
||||||
export * from "./response_helper";
|
export * from "./response_helper";
|
||||||
export * from "./user_api";
|
export * from "./user_api";
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
/**
|
||||||
|
* Payment API
|
||||||
|
*
|
||||||
|
* 付费墙 / 充值相关接口
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
CreatePaymentOrderRequest,
|
||||||
|
CreatePaymentOrderResponse,
|
||||||
|
PaymentOrderStatusResponse,
|
||||||
|
PaymentPlansResponse,
|
||||||
|
PaymentVipStatusResponse,
|
||||||
|
} from "@/data/dto/payment";
|
||||||
|
|
||||||
|
import { ApiPath } from "./api_path";
|
||||||
|
import { httpClient } from "./http_client";
|
||||||
|
import { ApiEnvelope, unwrap } from "./response_helper";
|
||||||
|
|
||||||
|
export class PaymentApi {
|
||||||
|
/**
|
||||||
|
* 获取套餐列表
|
||||||
|
*/
|
||||||
|
async getPlans(): Promise<PaymentPlansResponse> {
|
||||||
|
const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.paymentPlans);
|
||||||
|
return PaymentPlansResponse.fromJson(
|
||||||
|
unwrap(env) as Record<string, unknown>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建支付订单
|
||||||
|
*/
|
||||||
|
async createOrder(
|
||||||
|
body: CreatePaymentOrderRequest,
|
||||||
|
): Promise<CreatePaymentOrderResponse> {
|
||||||
|
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||||
|
ApiPath.paymentCreateOrder,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: body.toJson(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return CreatePaymentOrderResponse.fromJson(
|
||||||
|
unwrap(env) as Record<string, unknown>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询支付订单状态
|
||||||
|
*/
|
||||||
|
async getOrderStatus(
|
||||||
|
orderId: string,
|
||||||
|
): Promise<PaymentOrderStatusResponse> {
|
||||||
|
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||||
|
ApiPath.paymentOrderStatus,
|
||||||
|
{
|
||||||
|
query: { order_id: orderId },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return PaymentOrderStatusResponse.fromJson(
|
||||||
|
unwrap(env) as Record<string, unknown>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询当前用户 VIP 状态
|
||||||
|
*/
|
||||||
|
async getVipStatus(): Promise<PaymentVipStatusResponse> {
|
||||||
|
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||||
|
ApiPath.paymentVipStatus,
|
||||||
|
);
|
||||||
|
return PaymentVipStatusResponse.fromJson(
|
||||||
|
unwrap(env) as Record<string, unknown>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全局单例
|
||||||
|
*/
|
||||||
|
export const paymentApi = new PaymentApi();
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
/**
|
|
||||||
* Stripe Node.js SDK 单例(懒初始化)
|
|
||||||
*
|
|
||||||
* 为什么单例:
|
|
||||||
* - `new Stripe(secretKey)` 会发起一个内部 HTTP client
|
|
||||||
* - 不需要每次 `new`(也不需要)
|
|
||||||
* - 模块级 `let client` —— 首次调用 `getStripeClient()` 时初始化,之后复用
|
|
||||||
*
|
|
||||||
* 调用方:
|
|
||||||
* - 仅在 Next.js API route / Server Component 用(secret key 不要暴露给 client bundle)
|
|
||||||
* - client 端用 `@stripe/stripe-js` 的 `loadStripe(publishableKey)`
|
|
||||||
*/
|
|
||||||
import Stripe from "stripe";
|
|
||||||
|
|
||||||
let _client: Stripe | null = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取 Stripe SDK 单例(懒初始化)
|
|
||||||
* - 首次调用会 `new Stripe(secretKey)`,后续直接返回 cache
|
|
||||||
* - 如果 `STRIPE_SECRET_KEY` 未设置,抛错(避免 silent failure)
|
|
||||||
*/
|
|
||||||
export function getStripeClient(): Stripe {
|
|
||||||
if (_client) return _client;
|
|
||||||
|
|
||||||
const secretKey = process.env.STRIPE_SECRET_KEY;
|
|
||||||
if (!secretKey) {
|
|
||||||
throw new Error(
|
|
||||||
"STRIPE_SECRET_KEY is not set. Please configure it in .env.local (or your env).",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
_client = new Stripe(secretKey, {
|
|
||||||
// Stripe API 版本(跟 SDK 22.2.1 默认版本对应 —— "2026-05-27.dahlia")
|
|
||||||
// 用 `as never` 绕过 SDK 的字符串字面量联合类型限制(SDK 22.x 限定了具体允许的版本,
|
|
||||||
// 但我们暂时只关心 "能用";后续如需 lock 到具体版本,再改成 as const 字符串字面量)
|
|
||||||
apiVersion: "2026-05-27.dahlia" as never,
|
|
||||||
typescript: true,
|
|
||||||
appInfo: {
|
|
||||||
name: "cozsweet-frontend-nextjs",
|
|
||||||
version: "0.1.0",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return _client;
|
|
||||||
}
|
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
/**
|
|
||||||
* Stripe webhook 事件处理器
|
|
||||||
*
|
|
||||||
* 4 个核心事件:
|
|
||||||
* - `checkout.session.completed` 订阅首次购买 / 续费成功(返回 session URL 时 Stripe 触发)
|
|
||||||
* - `customer.subscription.deleted` 订阅取消(用户在 Portal 取消 / 不续费)
|
|
||||||
* - `customer.subscription.updated` 订阅状态变化(plan 升级 / 降级 / 重新激活)
|
|
||||||
* - `invoice.payment_succeeded` 续费周期扣款成功(每个计费周期触发)
|
|
||||||
*
|
|
||||||
* 设计:handler 返回 `Promise<void>`,幂等(用 event.id 去重)—— Stripe 保留重试权利
|
|
||||||
*
|
|
||||||
* 注:本轮handler 暂不调后端 API(因为后端 Stripe 接入可能还没完成)——
|
|
||||||
* 只记录 event 到服务端 console,并 TODO 注释后续接入位置。
|
|
||||||
* webhook 验签 + 分发在 `/api/payment/webhook` API route 里处理(见 route.ts)。
|
|
||||||
*/
|
|
||||||
import type Stripe from "stripe";
|
|
||||||
import { getStripeClient } from "./stripe-client";
|
|
||||||
import { Logger } from "@/utils";
|
|
||||||
|
|
||||||
const log = new Logger("LibStripeStripeEvents");
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 4 个事件的主分发器
|
|
||||||
* @returns true 如果事件已处理;false 如果忽略
|
|
||||||
*/
|
|
||||||
export async function dispatchStripeEvent(
|
|
||||||
event: Stripe.Event,
|
|
||||||
): Promise<boolean> {
|
|
||||||
switch (event.type) {
|
|
||||||
case "checkout.session.completed":
|
|
||||||
await handleCheckoutCompleted(event);
|
|
||||||
return true;
|
|
||||||
case "customer.subscription.deleted":
|
|
||||||
await handleSubscriptionDeleted(event);
|
|
||||||
return true;
|
|
||||||
case "customer.subscription.updated":
|
|
||||||
case "customer.subscription.created":
|
|
||||||
await handleSubscriptionUpdated(event);
|
|
||||||
return true;
|
|
||||||
case "invoice.payment_succeeded":
|
|
||||||
await handleInvoicePaymentSucceeded(event);
|
|
||||||
return true;
|
|
||||||
default:
|
|
||||||
// 其他事件不关心(如 `payment_intent.succeeded`、试用结束警告等)
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// Handler 1: checkout.session.completed
|
|
||||||
// ============================================================
|
|
||||||
/**
|
|
||||||
* 首次购买 / 续费成功 → 设置 user.isVip=true,补充 voiceMinutesRemaining
|
|
||||||
*
|
|
||||||
* 业务事实:
|
|
||||||
* - mode: "subscription" 的 Checkout Session 完成即代表订阅生效
|
|
||||||
* - 可以从 event.data.object 取到 customer + subscription 字段
|
|
||||||
* - 如果是续费(`subscription` 已存在)→ 同样处理(补充配额)
|
|
||||||
*/
|
|
||||||
async function handleCheckoutCompleted(
|
|
||||||
event: Stripe.CheckoutSessionCompletedEvent,
|
|
||||||
): Promise<void> {
|
|
||||||
const session = event.data.object;
|
|
||||||
const customerId =
|
|
||||||
typeof session.customer === "string" ? session.customer : session.customer?.id;
|
|
||||||
const subscriptionId =
|
|
||||||
typeof session.subscription === "string"
|
|
||||||
? session.subscription
|
|
||||||
: session.subscription?.id;
|
|
||||||
|
|
||||||
log.debug("[stripe-events] checkout.session.completed", {
|
|
||||||
eventId: event.id,
|
|
||||||
customerId,
|
|
||||||
subscriptionId,
|
|
||||||
amountTotal: session.amount_total,
|
|
||||||
currency: session.currency,
|
|
||||||
mode: session.mode,
|
|
||||||
});
|
|
||||||
|
|
||||||
// TODO: 后端接入 Stripe 后,这里调后端 API
|
|
||||||
// POST /api/internal/users/:userId/set-vip
|
|
||||||
// { isVip: true, voiceMinutes: <plan's voiceMinutesPerDay> }
|
|
||||||
// 本轮先不接(后端可能还没好)——
|
|
||||||
// 业务后端收到 webhook 后会自己更新 user.isVip + voiceMinutesRemaining
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// Handler 2: customer.subscription.deleted
|
|
||||||
// ============================================================
|
|
||||||
/**
|
|
||||||
* 订阅取消 → user.isVip=false
|
|
||||||
*
|
|
||||||
* 注意:voiceMinutesRemaining 保留(不清零)—— 不然已经发送的语音会消失
|
|
||||||
* (业务决定)
|
|
||||||
*/
|
|
||||||
async function handleSubscriptionDeleted(
|
|
||||||
event: Stripe.CustomerSubscriptionDeletedEvent,
|
|
||||||
): Promise<void> {
|
|
||||||
const subscription = event.data.object;
|
|
||||||
const customerId =
|
|
||||||
typeof subscription.customer === "string"
|
|
||||||
? subscription.customer
|
|
||||||
: subscription.customer.id;
|
|
||||||
|
|
||||||
log.debug("[stripe-events] customer.subscription.deleted", {
|
|
||||||
eventId: event.id,
|
|
||||||
customerId,
|
|
||||||
subscriptionId: subscription.id,
|
|
||||||
canceledAt: subscription.canceled_at,
|
|
||||||
status: subscription.status,
|
|
||||||
});
|
|
||||||
|
|
||||||
// TODO: POST /api/internal/users/:userId/set-vip { isVip: false }
|
|
||||||
// voiceMinutesRemaining 不动(保留余额)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// Handler 3: customer.subscription.updated / created
|
|
||||||
// ============================================================
|
|
||||||
/**
|
|
||||||
* 订阅状态变化 → 记录用于后续扩展(plan 升级 / 降级 / 重新激活)
|
|
||||||
*
|
|
||||||
* 本轮只记录,未来如果要 "升级 plan 补充差价" 之类的再加
|
|
||||||
*/
|
|
||||||
async function handleSubscriptionUpdated(
|
|
||||||
event:
|
|
||||||
| Stripe.CustomerSubscriptionUpdatedEvent
|
|
||||||
| Stripe.CustomerSubscriptionCreatedEvent,
|
|
||||||
): Promise<void> {
|
|
||||||
const subscription = event.data.object;
|
|
||||||
const customerId =
|
|
||||||
typeof subscription.customer === "string"
|
|
||||||
? subscription.customer
|
|
||||||
: subscription.customer.id;
|
|
||||||
|
|
||||||
log.debug(`[stripe-events] customer.subscription.${event.type}`, {
|
|
||||||
eventId: event.id,
|
|
||||||
customerId,
|
|
||||||
subscriptionId: subscription.id,
|
|
||||||
status: subscription.status,
|
|
||||||
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
||||||
itemsCount: subscription.items.data.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
// TODO: 如果要处理 plan 升级 / 降级 → POST /api/internal/users/:userId/update-subscription
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================
|
|
||||||
// Handler 4: invoice.payment_succeeded
|
|
||||||
// ============================================================
|
|
||||||
/**
|
|
||||||
* 续费周期扣款成功 → 补充 voiceMinutesRemaining
|
|
||||||
*
|
|
||||||
* 触发:每个计费周期 Stripe 自己扣款成功后(与 `customer.subscription.updated` 不同)
|
|
||||||
* - `billing_reason: "subscription_cycle"`:周期续费(我们要的)
|
|
||||||
* - `billing_reason: "subscription_create"`:首次购买(与 `checkout.session.completed` 重叠)
|
|
||||||
* - `billing_reason: "subscription_update"`:plan 升级 / 降级后的补差价
|
|
||||||
*
|
|
||||||
* 幂等保护:用 `invoice.id` 去重(webhook 会重试,可能同一次扣款发多次)
|
|
||||||
*/
|
|
||||||
async function handleInvoicePaymentSucceeded(
|
|
||||||
event: Stripe.InvoicePaymentSucceededEvent,
|
|
||||||
): Promise<void> {
|
|
||||||
const invoice = event.data.object;
|
|
||||||
const customerId =
|
|
||||||
typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id;
|
|
||||||
|
|
||||||
// 只关心周期续费(不对首次购买重复补充)
|
|
||||||
if (invoice.billing_reason !== "subscription_cycle") {
|
|
||||||
log.debug(
|
|
||||||
`[stripe-events] invoice.payment_succeeded (skipped, billing_reason=${invoice.billing_reason})`,
|
|
||||||
{ eventId: event.id, invoiceId: invoice.id },
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
log.debug("[stripe-events] invoice.payment_succeeded (subscription_cycle)", {
|
|
||||||
eventId: event.id,
|
|
||||||
invoiceId: invoice.id,
|
|
||||||
customerId,
|
|
||||||
amountPaid: invoice.amount_paid,
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// TODO: POST /api/internal/users/:userId/top-up-voice-minutes
|
|
||||||
// { minutes: <plan's voiceMinutesPerDay> }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 注:stripe-client 保留给未来扩展使用(例如主动调 `stripe.subscriptions.update()` 升级 plan)
|
|
||||||
// 本轮 handler 没直接调用 getStripeClient()(webhook 是事件驱动,不需要反向查 Stripe)
|
|
||||||
export const _internal_stripeClient = getStripeClient;
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
/**
|
|
||||||
* Stripe product / price id 映射
|
|
||||||
*
|
|
||||||
* 为什么不直接存到 `subscription-plans.ts`:
|
|
||||||
* - product/price id 是部署环境配置(不同环境不同 product)
|
|
||||||
* - 套餐本身的 `name` / `price` / `highlight` 是业务常量(不随环境变)
|
|
||||||
* - 分离后,套餐表只包含业务字段,产品 id 走 env —— 避免硬编码 + 生产安全
|
|
||||||
*
|
|
||||||
* env 命名规范:
|
|
||||||
* - STRIPE_PRODUCT_<PLAN_ID_UPPER> → Product ID
|
|
||||||
* - STRIPE_PRICE_<PLAN_ID_UPPER> → Price ID
|
|
||||||
* - 例:STRIPE_PRODUCT_MONTHLY, STRIPE_PRICE_QUARTERLY
|
|
||||||
*/
|
|
||||||
import type { SubscriptionPlanId } from "@/data/constants/subscription-plans";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取 Stripe Product ID(从 env)
|
|
||||||
*
|
|
||||||
* @throws Error 如果 env 未配置(避免 silent failure)
|
|
||||||
*/
|
|
||||||
export function getPlanProductId(planId: SubscriptionPlanId): string {
|
|
||||||
const envKey = `STRIPE_PRODUCT_${planId.toUpperCase()}`;
|
|
||||||
const productId = process.env[envKey];
|
|
||||||
if (!productId || productId.startsWith("prod_replace_")) {
|
|
||||||
throw new Error(
|
|
||||||
`Stripe product id is not configured. Set ${envKey} in .env.local.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return productId;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取 Stripe Price ID(从 env)
|
|
||||||
*
|
|
||||||
* Price ID 是真正用在 `stripe.checkout.sessions.create({ line_items: [{ price: "price_xxx" }] })` 里的
|
|
||||||
*
|
|
||||||
* @throws Error 如果 env 未配置
|
|
||||||
*/
|
|
||||||
export function getPlanPriceId(planId: SubscriptionPlanId): string {
|
|
||||||
const envKey = `STRIPE_PRICE_${planId.toUpperCase()}`;
|
|
||||||
const priceId = process.env[envKey];
|
|
||||||
if (!priceId || priceId.startsWith("price_replace_")) {
|
|
||||||
throw new Error(
|
|
||||||
`Stripe price id is not configured. Set ${envKey} in .env.local.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return priceId;
|
|
||||||
}
|
|
||||||
@@ -21,6 +21,7 @@ import { AuthStatusChecker } from "@/stores/auth/auth-status-checker";
|
|||||||
import { OAuthSessionSync } from "@/stores/auth/oauth-session-sync";
|
import { OAuthSessionSync } from "@/stores/auth/oauth-session-sync";
|
||||||
import { ChatAuthSync } from "@/stores/chat/chat-auth-sync";
|
import { ChatAuthSync } from "@/stores/chat/chat-auth-sync";
|
||||||
import { ChatProvider } from "@/stores/chat/chat-context";
|
import { ChatProvider } from "@/stores/chat/chat-context";
|
||||||
|
import { PaymentProvider } from "@/stores/payment";
|
||||||
import { SidebarProvider } from "@/stores/sidebar/sidebar-context";
|
import { SidebarProvider } from "@/stores/sidebar/sidebar-context";
|
||||||
import { UserAuthSync } from "@/stores/user/user-auth-sync";
|
import { UserAuthSync } from "@/stores/user/user-auth-sync";
|
||||||
import { UserProvider } from "@/stores/user/user-context";
|
import { UserProvider } from "@/stores/user/user-context";
|
||||||
@@ -39,6 +40,7 @@ export function RootProviders({ children }: RootProvidersProps) {
|
|||||||
<OAuthSessionSync />
|
<OAuthSessionSync />
|
||||||
<UserProvider>
|
<UserProvider>
|
||||||
<UserAuthSync />
|
<UserAuthSync />
|
||||||
|
<PaymentProvider>
|
||||||
<SidebarProvider>
|
<SidebarProvider>
|
||||||
<ChatProvider>
|
<ChatProvider>
|
||||||
<ChatAuthSync />
|
<ChatAuthSync />
|
||||||
@@ -46,6 +48,7 @@ export function RootProviders({ children }: RootProvidersProps) {
|
|||||||
<div id="toast-portal" />
|
<div id="toast-portal" />
|
||||||
</ChatProvider>
|
</ChatProvider>
|
||||||
</SidebarProvider>
|
</SidebarProvider>
|
||||||
|
</PaymentProvider>
|
||||||
</UserProvider>
|
</UserProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -53,10 +53,7 @@ export const loadQuotaActor = fromPromise<{
|
|||||||
remaining: number;
|
remaining: number;
|
||||||
total: number;
|
total: number;
|
||||||
}>(async () => {
|
}>(async () => {
|
||||||
log.debug("[chat-machine] loadQuotaActor ENTRY");
|
return readGuestQuota();
|
||||||
const result = await readGuestQuota();
|
|
||||||
log.debug("[chat-machine] loadQuotaActor DONE", result);
|
|
||||||
return result;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -76,16 +73,7 @@ export const loadHistoryActor = fromPromise<{
|
|||||||
localCount: number;
|
localCount: number;
|
||||||
networkCount: number;
|
networkCount: number;
|
||||||
}>(async () => {
|
}>(async () => {
|
||||||
log.debug("[chat-machine] loadHistoryActor ENTRY");
|
return readAndSyncHistory();
|
||||||
const result = await readAndSyncHistory();
|
|
||||||
log.debug("[chat-machine] loadHistoryActor DONE", {
|
|
||||||
finalCount: result.messages.length,
|
|
||||||
localCount: result.localCount,
|
|
||||||
networkCount: result.networkCount,
|
|
||||||
hasMore: result.hasMore,
|
|
||||||
localOverwritten: result.localOverwritten,
|
|
||||||
});
|
|
||||||
return result;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -100,83 +88,30 @@ export const loadHistoryActor = fromPromise<{
|
|||||||
export const sendMessageHttpActor = fromPromise<
|
export const sendMessageHttpActor = fromPromise<
|
||||||
{ reply: UiMessage },
|
{ reply: UiMessage },
|
||||||
{ content: string }
|
{ content: string }
|
||||||
>(async ({ input, self }) => {
|
>(async ({ input }) => {
|
||||||
log.debug("[chat-machine] sendMessageHttpActor ENTRY", {
|
|
||||||
contentLength: input.content.length,
|
|
||||||
contentPreview: input.content.slice(0, 50),
|
|
||||||
selfId: self.id,
|
|
||||||
selfPath: "<actor path>",
|
|
||||||
});
|
|
||||||
log.debug("[chat-machine] sendMessageHttpActor calling chatRepo.sendMessage");
|
|
||||||
const result = await chatRepo.sendMessage(input.content);
|
const result = await chatRepo.sendMessage(input.content);
|
||||||
log.debug("[chat-machine] sendMessageHttpActor chatRepo.sendMessage DONE", {
|
|
||||||
success: result.success,
|
|
||||||
error: result.success ? null : Result.isErr(result) ? result.error : null,
|
|
||||||
});
|
|
||||||
if (Result.isErr(result)) {
|
if (Result.isErr(result)) {
|
||||||
log.error("[chat-machine] sendMessageHttpActor result isErr, throwing");
|
log.error("[chat-machine] sendMessageHttpActor failed", { error: result.error });
|
||||||
throw result.error;
|
throw result.error;
|
||||||
}
|
}
|
||||||
|
return { reply: sendResponseToUiMessage(result.data) };
|
||||||
// 一次发送 = 一次返回 —— 直接转 reply → UiMessage
|
|
||||||
log.debug("[chat-machine] sendMessageHttpActor converting reply to UiMessage", {
|
|
||||||
replyLength: result.data.reply.length,
|
|
||||||
replyPreview: result.data.reply.slice(0, 50),
|
|
||||||
messageId: result.data.messageId,
|
|
||||||
timestamp: result.data.timestamp,
|
|
||||||
});
|
|
||||||
|
|
||||||
const reply = sendResponseToUiMessage(result.data);
|
|
||||||
log.debug("[chat-machine] sendMessageHttpActor done", {
|
|
||||||
replyContentLength: reply.content.length,
|
|
||||||
});
|
|
||||||
return { reply };
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/** 翻历史(pagination)—— 不走 local-first,纯 server fetch */
|
/** 翻历史(pagination)—— 不走 local-first,纯 server fetch */
|
||||||
export const loadMoreHistoryActor = fromPromise<
|
export const loadMoreHistoryActor = fromPromise<
|
||||||
{ messages: UiMessage[]; hasMore: boolean; newOffset: number },
|
{ messages: UiMessage[]; hasMore: boolean; newOffset: number },
|
||||||
{ offset: number }
|
{ offset: number }
|
||||||
>(async ({ input, self }) => {
|
>(async ({ input }) => {
|
||||||
log.debug("[chat-machine] loadMoreHistoryActor ENTRY", {
|
|
||||||
inputOffset: input.offset,
|
|
||||||
pageSize: PAGE_SIZE,
|
|
||||||
selfPath: "<actor path>",
|
|
||||||
});
|
|
||||||
log.debug("[chat-machine] loadMoreHistoryActor calling chatRepo.getHistory", {
|
|
||||||
pageSize: PAGE_SIZE,
|
|
||||||
offset: input.offset,
|
|
||||||
});
|
|
||||||
const result = await chatRepo.getHistory(PAGE_SIZE, input.offset);
|
const result = await chatRepo.getHistory(PAGE_SIZE, input.offset);
|
||||||
log.debug("[chat-machine] loadMoreHistoryActor chatRepo.getHistory DONE", {
|
|
||||||
success: result.success,
|
|
||||||
error: result.success ? null : Result.isErr(result) ? result.error : null,
|
|
||||||
responseType: result.success ? typeof result.data : "err",
|
|
||||||
});
|
|
||||||
if (Result.isErr(result)) {
|
if (Result.isErr(result)) {
|
||||||
log.error("[chat-machine] loadMoreHistoryActor result isErr, throwing", {
|
log.error("[chat-machine] loadMoreHistoryActor failed", { error: result.error });
|
||||||
error: result.error,
|
|
||||||
});
|
|
||||||
throw result.error;
|
throw result.error;
|
||||||
}
|
}
|
||||||
log.debug("[chat-machine] loadMoreHistoryActor result data", {
|
|
||||||
rawMessagesCount: result.data.messages.length,
|
|
||||||
});
|
|
||||||
const page = localMessagesToUi(result.data.messages);
|
const page = localMessagesToUi(result.data.messages);
|
||||||
log.debug("[chat-machine] loadMoreHistoryActor AFTER UiMessage mapping", {
|
|
||||||
uiMessagesCount: page.length,
|
|
||||||
});
|
|
||||||
const hasMore = page.length >= PAGE_SIZE;
|
|
||||||
const newOffset = input.offset + page.length;
|
|
||||||
log.debug("[chat-machine] loadMoreHistoryActor result", {
|
|
||||||
pageSize: page.length,
|
|
||||||
hasMore,
|
|
||||||
newOffset,
|
|
||||||
});
|
|
||||||
return {
|
return {
|
||||||
messages: page,
|
messages: page,
|
||||||
hasMore,
|
hasMore: page.length >= PAGE_SIZE,
|
||||||
newOffset,
|
newOffset: input.offset + page.length,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -196,40 +131,14 @@ export const loadMoreHistoryActor = fromPromise<
|
|||||||
*/
|
*/
|
||||||
export const chatWebSocketActor = fromCallback<ChatEvent, { token: string }>(
|
export const chatWebSocketActor = fromCallback<ChatEvent, { token: string }>(
|
||||||
({ sendBack, input }) => {
|
({ sendBack, input }) => {
|
||||||
log.debug("[chat-machine] chatWebSocketActor ENTRY", {
|
|
||||||
hasToken: !!input.token,
|
|
||||||
tokenLength: input.token?.length ?? 0,
|
|
||||||
tokenPrefix: input.token?.slice(0, 10) ?? "EMPTY",
|
|
||||||
selfPath: "<actor path>",
|
|
||||||
});
|
|
||||||
log.debug("[chat-machine] chatWebSocketActor creating ChatWebSocket instance");
|
|
||||||
const ws = createChatWebSocket(input.token);
|
const ws = createChatWebSocket(input.token);
|
||||||
log.debug("[chat-machine] chatWebSocketActor createChatWebSocket DONE", {
|
|
||||||
wsType: ws.constructor.name,
|
|
||||||
});
|
|
||||||
|
|
||||||
// 写入 module-level 共享引用 —— sendMessageWsActor 借此调 ws.sendMessage()
|
|
||||||
activeChatWebSocket = ws;
|
activeChatWebSocket = ws;
|
||||||
log.debug("[chat-machine] chatWebSocketActor activeChatWebSocket SET", {
|
|
||||||
isConnected: ws.isConnected,
|
|
||||||
});
|
|
||||||
|
|
||||||
ws.onConnected = (userId) => {
|
ws.onConnected = (userId) => {
|
||||||
log.debug("[chat-machine] WS onConnected", {
|
log.debug("[chat-machine] WS connected", { userId });
|
||||||
userId,
|
|
||||||
userIdPrefix: userId?.slice(0, 8) ?? "EMPTY",
|
|
||||||
});
|
|
||||||
sendBack({ type: "ChatWebSocketConnected", userId });
|
sendBack({ type: "ChatWebSocketConnected", userId });
|
||||||
};
|
};
|
||||||
ws.onSentence = (p) => {
|
ws.onSentence = (p) => {
|
||||||
log.debug("[chat-machine] WS onSentence", {
|
|
||||||
index: p.index,
|
|
||||||
total: p.total,
|
|
||||||
done: p.done,
|
|
||||||
textLength: p.text.length,
|
|
||||||
textPreview: p.text.slice(0, 50),
|
|
||||||
textSuffix: p.text.slice(-20),
|
|
||||||
});
|
|
||||||
sendBack({
|
sendBack({
|
||||||
type: "ChatAISentenceReceived",
|
type: "ChatAISentenceReceived",
|
||||||
index: p.index,
|
index: p.index,
|
||||||
@@ -239,23 +148,14 @@ export const chatWebSocketActor = fromCallback<ChatEvent, { token: string }>(
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
ws.onError = (msg) => {
|
ws.onError = (msg) => {
|
||||||
log.error("[chat-machine] WS onError", {
|
log.error("[chat-machine] WS error", { errorMessage: msg });
|
||||||
errorMessage: msg,
|
|
||||||
errorLength: msg?.length ?? 0,
|
|
||||||
});
|
|
||||||
sendBack({ type: "ChatWebSocketError", errorMessage: msg });
|
sendBack({ type: "ChatWebSocketError", errorMessage: msg });
|
||||||
};
|
};
|
||||||
log.debug("[chat-machine] chatWebSocketActor calling ws.connect()");
|
|
||||||
ws.connect();
|
ws.connect();
|
||||||
log.debug("[chat-machine] chatWebSocketActor ws.connect() called");
|
|
||||||
return () => {
|
return () => {
|
||||||
log.debug(
|
log.debug("[chat-machine] chatWebSocketActor cleanup");
|
||||||
"[chat-machine] chatWebSocketActor CLEANUP (parent state exit / logout / cross-transition / unmount)",
|
|
||||||
);
|
|
||||||
// 清空 module-level 引用 —— 严格用 `=== ws` 判等,避免覆盖更新的实例
|
|
||||||
if (activeChatWebSocket === ws) {
|
if (activeChatWebSocket === ws) {
|
||||||
activeChatWebSocket = null;
|
activeChatWebSocket = null;
|
||||||
log.debug("[chat-machine] chatWebSocketActor activeChatWebSocket CLEARED");
|
|
||||||
}
|
}
|
||||||
ws.disconnect();
|
ws.disconnect();
|
||||||
};
|
};
|
||||||
@@ -283,28 +183,16 @@ export const chatWebSocketActor = fromCallback<ChatEvent, { token: string }>(
|
|||||||
*/
|
*/
|
||||||
export const sendMessageWsActor = fromPromise<void, { content: string }>(
|
export const sendMessageWsActor = fromPromise<void, { content: string }>(
|
||||||
async ({ input }) => {
|
async ({ input }) => {
|
||||||
log.debug("[chat-machine] sendMessageWsActor ENTRY", {
|
|
||||||
contentLength: input.content.length,
|
|
||||||
contentPreview: input.content.slice(0, 50),
|
|
||||||
});
|
|
||||||
const ws = getActiveChatWebSocket();
|
const ws = getActiveChatWebSocket();
|
||||||
if (!ws) {
|
if (!ws) {
|
||||||
log.error("[chat-machine] sendMessageWsActor no activeChatWebSocket");
|
log.error("[chat-machine] sendMessageWsActor no active WebSocket");
|
||||||
throw new Error("[chat-machine] sendMessageWs: no active WebSocket (actor not running)");
|
throw new Error("[chat-machine] sendMessageWs: no active WebSocket (actor not running)");
|
||||||
}
|
}
|
||||||
log.debug("[chat-machine] sendMessageWsActor calling ws.sendMessage", {
|
|
||||||
isConnected: ws.isConnected,
|
|
||||||
});
|
|
||||||
const ok = ws.sendMessage(input.content);
|
const ok = ws.sendMessage(input.content);
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
log.error(
|
log.error("[chat-machine] sendMessageWsActor WebSocket not OPEN");
|
||||||
"[chat-machine] sendMessageWsActor ws.sendMessage returned false (not OPEN)",
|
|
||||||
);
|
|
||||||
throw new Error("[chat-machine] sendMessageWs: WebSocket not OPEN");
|
throw new Error("[chat-machine] sendMessageWs: WebSocket not OPEN");
|
||||||
}
|
}
|
||||||
log.debug(
|
|
||||||
"[chat-machine] sendMessageWsActor ws.sendMessage OK, awaiting AI sentence stream",
|
|
||||||
);
|
|
||||||
// resolve 不返值 —— AI reply 由 chatWebSocketActor 的 ChatAISentenceReceived 流回
|
// resolve 不返值 —— AI reply 由 chatWebSocketActor 的 ChatAISentenceReceived 流回
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -219,9 +219,6 @@ export const chatMachine = setup({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
// ========================================================================
|
|
||||||
// guestSession(游客会话 —— 不连 WS,2 个 init 任务并行)
|
|
||||||
// ========================================================================
|
|
||||||
guestSession: {
|
guestSession: {
|
||||||
on: {
|
on: {
|
||||||
ChatLogout: "#chat.idle",
|
ChatLogout: "#chat.idle",
|
||||||
@@ -342,13 +339,9 @@ export const chatMachine = setup({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// 删除 loadingMore(游客无翻页)
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
// ========================================================================
|
|
||||||
// userSession(非游客会话 —— WS 父级 + history 子级)
|
|
||||||
// ========================================================================
|
|
||||||
userSession: {
|
userSession: {
|
||||||
// 父级 on:把 WS / AI 流句 事件从 ready.on 上提到 userSession.on
|
// 父级 on:把 WS / AI 流句 事件从 ready.on 上提到 userSession.on
|
||||||
// —— 任何 child state(initializing / ready / sendingViaWs / sendingViaHttp / loadingMore)
|
// —— 任何 child state(initializing / ready / sendingViaWs / sendingViaHttp / loadingMore)
|
||||||
@@ -360,7 +353,6 @@ export const chatMachine = setup({
|
|||||||
// —— XState v5: child handler 替换 parent;复制 action
|
// —— XState v5: child handler 替换 parent;复制 action
|
||||||
on: {
|
on: {
|
||||||
ChatLogout: "#chat.idle",
|
ChatLogout: "#chat.idle",
|
||||||
ChatGuestLogin: "#chat.guestSession",
|
|
||||||
ChatNonGuestLogin: {
|
ChatNonGuestLogin: {
|
||||||
target: "#chat.userSession",
|
target: "#chat.userSession",
|
||||||
reenter: true,
|
reenter: true,
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* @file Payment store barrel.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export * from "./payment-context";
|
||||||
|
export * from "./payment-events";
|
||||||
|
export * from "./payment-machine";
|
||||||
|
export * from "./payment-machine.actors";
|
||||||
|
export * from "./payment-state";
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PaymentContext:基于 XState v5 的 React Context Provider
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
type Dispatch,
|
||||||
|
type ReactNode,
|
||||||
|
createContext,
|
||||||
|
useContext,
|
||||||
|
useMemo,
|
||||||
|
} from "react";
|
||||||
|
import { useMachine } from "@xstate/react";
|
||||||
|
|
||||||
|
import { paymentMachine } from "./payment-machine";
|
||||||
|
import type {
|
||||||
|
PaymentEvent,
|
||||||
|
PaymentState as MachineContext,
|
||||||
|
} from "./payment-machine";
|
||||||
|
|
||||||
|
export interface PaymentContextState {
|
||||||
|
status: string;
|
||||||
|
plans: MachineContext["plans"];
|
||||||
|
selectedPlanId: string;
|
||||||
|
payChannel: MachineContext["payChannel"];
|
||||||
|
autoRenew: boolean;
|
||||||
|
agreed: boolean;
|
||||||
|
currentOrderId: string | null;
|
||||||
|
payParams: Record<string, unknown> | null;
|
||||||
|
orderStatus: MachineContext["orderStatus"];
|
||||||
|
vipStatus: MachineContext["vipStatus"];
|
||||||
|
errorMessage: string | null;
|
||||||
|
launchNonce: number;
|
||||||
|
isLoadingPlans: boolean;
|
||||||
|
isCreatingOrder: boolean;
|
||||||
|
isPollingOrder: boolean;
|
||||||
|
isCheckingVipStatus: boolean;
|
||||||
|
isPaid: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PaymentStateCtx = createContext<PaymentContextState | null>(null);
|
||||||
|
const PaymentDispatchCtx = createContext<Dispatch<PaymentEvent> | null>(null);
|
||||||
|
|
||||||
|
export interface PaymentProviderProps {
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PaymentProvider({ children }: PaymentProviderProps) {
|
||||||
|
const [state, send] = useMachine(paymentMachine);
|
||||||
|
|
||||||
|
const paymentState = useMemo<PaymentContextState>(
|
||||||
|
() => ({
|
||||||
|
status: String(state.value),
|
||||||
|
plans: state.context.plans,
|
||||||
|
selectedPlanId: state.context.selectedPlanId,
|
||||||
|
payChannel: state.context.payChannel,
|
||||||
|
autoRenew: state.context.autoRenew,
|
||||||
|
agreed: state.context.agreed,
|
||||||
|
currentOrderId: state.context.currentOrderId,
|
||||||
|
payParams: state.context.payParams,
|
||||||
|
orderStatus: state.context.orderStatus,
|
||||||
|
vipStatus: state.context.vipStatus,
|
||||||
|
errorMessage: state.context.errorMessage,
|
||||||
|
launchNonce: state.context.launchNonce,
|
||||||
|
isLoadingPlans: state.matches("loadingPlans"),
|
||||||
|
isCreatingOrder: state.matches("creatingOrder"),
|
||||||
|
isPollingOrder:
|
||||||
|
state.matches("pollingOrder") || state.matches("waitingForPayment"),
|
||||||
|
isCheckingVipStatus: state.matches("checkingVipStatus"),
|
||||||
|
isPaid: state.matches("paid"),
|
||||||
|
}),
|
||||||
|
[state],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PaymentStateCtx.Provider value={paymentState}>
|
||||||
|
<PaymentDispatchCtx.Provider value={send}>
|
||||||
|
{children}
|
||||||
|
</PaymentDispatchCtx.Provider>
|
||||||
|
</PaymentStateCtx.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePaymentState(): PaymentContextState {
|
||||||
|
const ctx = useContext(PaymentStateCtx);
|
||||||
|
if (!ctx)
|
||||||
|
throw new Error("usePaymentState must be used inside <PaymentProvider>");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePaymentDispatch(): Dispatch<PaymentEvent> {
|
||||||
|
const ctx = useContext(PaymentDispatchCtx);
|
||||||
|
if (!ctx)
|
||||||
|
throw new Error("usePaymentDispatch must be used inside <PaymentProvider>");
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* Payment 状态机:事件联合
|
||||||
|
*/
|
||||||
|
import type { PayChannel } from "@/data/dto/payment";
|
||||||
|
|
||||||
|
export type PaymentEvent =
|
||||||
|
| { type: "PaymentInit" }
|
||||||
|
| { type: "PaymentPlanSelected"; planId: string }
|
||||||
|
| { type: "PaymentPayChannelChanged"; payChannel: PayChannel }
|
||||||
|
| { type: "PaymentAutoRenewChanged"; autoRenew: boolean }
|
||||||
|
| { type: "PaymentAgreementChanged"; agreed: boolean }
|
||||||
|
| { type: "PaymentCreateOrderSubmitted" }
|
||||||
|
| { type: "PaymentRefreshVipStatus" }
|
||||||
|
| { type: "PaymentLaunchFailed"; errorMessage: string }
|
||||||
|
| { type: "PaymentErrorCleared" }
|
||||||
|
| { type: "PaymentReset" };
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Payment 状态机:Actors(异步服务)
|
||||||
|
*/
|
||||||
|
import { fromPromise } from "xstate";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CreatePaymentOrderResponse,
|
||||||
|
PayChannel,
|
||||||
|
PaymentOrderStatusResponse,
|
||||||
|
PaymentPlansResponse,
|
||||||
|
PaymentVipStatusResponse,
|
||||||
|
} from "@/data/dto/payment";
|
||||||
|
import { paymentRepository } from "@/data/repositories/payment_repository";
|
||||||
|
import type { IPaymentRepository } from "@/data/repositories/interfaces";
|
||||||
|
import { Result } from "@/utils";
|
||||||
|
|
||||||
|
const paymentRepo: IPaymentRepository = paymentRepository;
|
||||||
|
|
||||||
|
export const loadPaymentPlansActor = fromPromise<PaymentPlansResponse>(
|
||||||
|
async () => {
|
||||||
|
const result = await paymentRepo.getPlans();
|
||||||
|
if (Result.isErr(result)) throw result.error;
|
||||||
|
return result.data;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export const createPaymentOrderActor = fromPromise<
|
||||||
|
CreatePaymentOrderResponse,
|
||||||
|
{ planId: string; payChannel: PayChannel; autoRenew: boolean }
|
||||||
|
>(async ({ input }) => {
|
||||||
|
const result = await paymentRepo.createOrder(
|
||||||
|
input.planId,
|
||||||
|
input.payChannel,
|
||||||
|
input.autoRenew,
|
||||||
|
);
|
||||||
|
if (Result.isErr(result)) throw result.error;
|
||||||
|
return result.data;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pollPaymentOrderStatusActor = fromPromise<
|
||||||
|
PaymentOrderStatusResponse,
|
||||||
|
{ orderId: string }
|
||||||
|
>(async ({ input }) => {
|
||||||
|
const result = await paymentRepo.getOrderStatus(input.orderId);
|
||||||
|
if (Result.isErr(result)) throw result.error;
|
||||||
|
return result.data;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const loadPaymentVipStatusActor =
|
||||||
|
fromPromise<PaymentVipStatusResponse>(async () => {
|
||||||
|
const result = await paymentRepo.getVipStatus();
|
||||||
|
if (Result.isErr(result)) throw result.error;
|
||||||
|
return result.data;
|
||||||
|
});
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
/**
|
||||||
|
* Payment 状态机(XState v5)
|
||||||
|
*/
|
||||||
|
import { assign, setup } from "xstate";
|
||||||
|
|
||||||
|
import type { PaymentPlan } from "@/data/dto/payment";
|
||||||
|
|
||||||
|
import type { PaymentEvent } from "./payment-events";
|
||||||
|
import { initialState, type PaymentState } from "./payment-state";
|
||||||
|
import {
|
||||||
|
createPaymentOrderActor,
|
||||||
|
loadPaymentPlansActor,
|
||||||
|
loadPaymentVipStatusActor,
|
||||||
|
pollPaymentOrderStatusActor,
|
||||||
|
} from "./payment-machine.actors";
|
||||||
|
|
||||||
|
export type { PaymentEvent } from "./payment-events";
|
||||||
|
export type { PaymentState } from "./payment-state";
|
||||||
|
export { initialState } from "./payment-state";
|
||||||
|
|
||||||
|
const POLL_DELAY_MS = 4000;
|
||||||
|
|
||||||
|
function toErrorMessage(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultAutoRenewForPlan(planId: string): boolean {
|
||||||
|
return !planId.includes("lifetime") && !planId.startsWith("dol_");
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDefaultPlanId(plans: readonly PaymentPlan[]): string {
|
||||||
|
return (
|
||||||
|
plans.find((plan) => plan.planId === "vip_monthly")?.planId ??
|
||||||
|
plans.find((plan) => plan.orderType.startsWith("vip_"))?.planId ??
|
||||||
|
plans[0]?.planId ??
|
||||||
|
""
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetOrderState() {
|
||||||
|
return {
|
||||||
|
currentOrderId: null,
|
||||||
|
payParams: null,
|
||||||
|
orderStatus: null,
|
||||||
|
errorMessage: null,
|
||||||
|
} satisfies Partial<PaymentState>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const paymentMachine = setup({
|
||||||
|
types: {
|
||||||
|
context: {} as PaymentState,
|
||||||
|
events: {} as PaymentEvent,
|
||||||
|
},
|
||||||
|
actors: {
|
||||||
|
loadPlans: loadPaymentPlansActor,
|
||||||
|
createOrder: createPaymentOrderActor,
|
||||||
|
pollOrderStatus: pollPaymentOrderStatusActor,
|
||||||
|
loadVipStatus: loadPaymentVipStatusActor,
|
||||||
|
},
|
||||||
|
}).createMachine({
|
||||||
|
/** @xstate-layout N4IgpgJg5mDOIC5QAcCGBPAtmAdgFwGIAFDbfAGVQFccBjACwDFUBLAG0gG0AGAXURQB7WCzwtBOASAAeiACwAmADQh0iAIwA2bnIB0CuQE5j67t20AOBQF9rKtFlx5dLCB2KknASRyie-JBBkYVFxSUDZBAVDPUMFdQs5dXUAVk0Adk0AZhSUlTUEdUMLXXV0w00LCyzzc00U23tPfBc3MA9HfAAlMAAzACc4egA1FmQAZTxUPCpYfylgkTEJKUjo2PjE5LTMnLzVRBTq3R1iuRTdzWz0xqDm5zZBVAgWHCgiNlQcWAIICTAXDgAG6CADWAIcZAeTxebw+X1gCFeINo0zC-nmgUWoRWEQ0WQsKV0lXSSQuFk0MUM6XyiAs6l0RmMxXSWS0FIUNjsd060Oer3en2+BDA-X6gn6umQnzwvQlmCl910j35cKFiORglRyxwGL4CxCOtW+MJxIspNS6QpVJpB0KpMZKTZBiSWXiMQst0hTl0g2e6A6UJ8fn1WMNYWNhRShiyujOCiq5yOSXUtKihm4jOilTkbKO6Ru3O9LT9EADJF58Jw4zAHFoeC4oaESwjeMKhlMunS3BqCiycm4VviWTTpnSCn02iycSdigMmi9StL5fuFYAwvQvjhaxuvjAIJjmzjwqBIgkrPoe9wFNxUhk5HI09TNLoauOMtxzRYO4ZF7zfWA-qBk4ACCVB4IIPTbgA7rubyNgER5Gm256xpocjVDkCgXNoCiaGmVSZjkSRJOhqTRlyTT-suwH4CBUCDGAUJwfuh5BOGuKnhoVREnhuTxCkWg4WmVp6AOphaEUKScvUf5QgBQEVsxfoNgA8v0ECiuMVAAEaYKIDYHk27EtpxMiIJyRRxuY6iKPScQ1I+drJOOXbqFh6RHLeTpyT6NFKU4a4qWA6maf02l6QZXDqIhJnHpGCQJG5FLnBUeHlPhdqVCUD5WhmpJVDGnpFkugFlrReA9AMQyjBMUwzHMxnYshXGFEYmZ8YJGbnOkWjKHa-aZnEFRWPEZR9b5JZlSuvIAKJihKa4cKggxGbFzWtq1RTqBOBjFISBYKFamRphRjIxJkTrXmkySTc4tAqQKoWir8-yAiC4KKv+D2AWIbzPf0SLAlqaISHq60cSe5lRCRr47VkGQUgS2SjtGeiksyn6JvSDQld9j3-RpL2iuKkrStMcr9Aqxb3QTUAA0DKKg7qfBsRtZlrGSxJpNwHb0vehijm+XYjfUD7xBhxVUfJwRsGwT1E-0r3bu9YIQkqsvy4TYWMyDOrgwaplQ2sMRxpsKY7NkuRptksYpEYiQI9GKTXoW0s+prCthcrAKap9NNSoIcte6KuvauirMxYb8VtusZsJBbGRW-sBTuTojJyJU1xuuh0Z3YHwfay9fwq376v-p7ReA5q4dg6zCgQ0bkZx3ECfbEnexPjUjKsjGmimAOWT9vnlf04rIoLWTMqU9TGtB1rY86zXzMG2GTex6brdbHeuzW85Y3nVkrIWNwgnJHh+fQawf1QIwEoBfgFU9LAYB4GzkORhSmZWjtO3GAO9QLBPj7K+DM-dM4fmqFLHk8kr6hDeHffoD9CDSFgPVAEqBegNn6AACgHGYAAlAQAOcCb6IOQe-derUjB6G-KfeoToMhD3OARC81JpxH2pNEGMbsYE+gYGAWgoIBS1UmNMWYPtVb+yVAIoRIixhiIamHFerMmofzbF-Ls9J4jcIAUcESHYTjTnoaYMwpJeEB1kcIt4oj6oSJLr7YG0jvr0EEdYqAtjxEamBrXFmvBOBRzXjHVqmif46P-uYfRdpM4MgyCNbYFQcgWJka4uRNiFF2J+CTCUUpp7yi+vJKx8i6peOUfrVRjdgnQ1Cdov+MRIlAKysUE4hIYw6ASPbWy+cinpJKQ1CepNckU3yZY1J7jPFKOXuU-xgSkKbWqdoLRv9dENNOvbYkboT45mSJSEerAIBPzgK-ShVSzwEiJCSMkVpKRGFtAUAshg4y2VPkUXMHZPJ7NcIc6qsARgZK8Sclq0MOwvk6kcXIMRNg2zkOkXQ4KYzYU5N2Ps+deisA4Ac5BQVfohUVhFfSeBDKAvmWc00lzLTWluaOB8jyCz9gTAyjsaRUXosgBVeapMlqAVWsSjmJoLnmiuZS6ko46i6ApL1OlGZsLXhZewNlyDn7HLUVQ6G7kyWCopTckVzk+ripvL2aogDoi2G5DgQQml4BYnuNHIFkQAC0mUCj2qJMyN17qMyn3zq4DgtqSXcVdZsPMmdFAJBHHaC4sL3JskMNGdp05fx43kiqWEgoER+r5YUMotKEiVHtrsQko5PKlAyjGfsmF7z52XBm42GhqQMm7L2TkVhpyslHGUWMw5BLlBPrkVk3S6YAxrc3fusKeE5DiZ61Mzk0hEhzmkct15eaUT4S0UeQ6gl2vkP1VON49BulJGYG6R7L7XwFOQm1m7-UIE0HhOG84Bx7quE6xAMQXyjp0e+bQPZuljOKYo2Yw62z9xKPUW95hEnfkaQUfu762naLiKyDInyIBAa2jeF8v9rzfmMAJHddIeylAATZKSJI5UYrQ2qvsRIew7JqIlKoQs70dqSCfbC34CymusEAA */
|
||||||
|
id: "payment",
|
||||||
|
initial: "idle",
|
||||||
|
context: initialState,
|
||||||
|
states: {
|
||||||
|
idle: {
|
||||||
|
on: {
|
||||||
|
PaymentInit: "loadingPlans",
|
||||||
|
PaymentRefreshVipStatus: "checkingVipStatus",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
loadingPlans: {
|
||||||
|
invoke: {
|
||||||
|
src: "loadPlans",
|
||||||
|
onDone: {
|
||||||
|
target: "ready",
|
||||||
|
actions: assign(({ context, event }) => {
|
||||||
|
const plans = event.output.plans;
|
||||||
|
const selectedPlanId =
|
||||||
|
context.selectedPlanId || getDefaultPlanId(plans);
|
||||||
|
return {
|
||||||
|
plans,
|
||||||
|
selectedPlanId,
|
||||||
|
autoRenew: defaultAutoRenewForPlan(selectedPlanId),
|
||||||
|
errorMessage: null,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
onError: {
|
||||||
|
target: "ready",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
errorMessage: toErrorMessage(event.error),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
ready: {
|
||||||
|
on: {
|
||||||
|
PaymentInit: "loadingPlans",
|
||||||
|
PaymentPlanSelected: {
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
...resetOrderState(),
|
||||||
|
selectedPlanId: event.planId,
|
||||||
|
autoRenew: defaultAutoRenewForPlan(event.planId),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
PaymentPayChannelChanged: {
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
payChannel: event.payChannel,
|
||||||
|
errorMessage: null,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
PaymentAutoRenewChanged: {
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
autoRenew: event.autoRenew,
|
||||||
|
errorMessage: null,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
PaymentAgreementChanged: {
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
agreed: event.agreed,
|
||||||
|
errorMessage: null,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
PaymentCreateOrderSubmitted: [
|
||||||
|
{
|
||||||
|
guard: ({ context }) =>
|
||||||
|
context.agreed && context.selectedPlanId.length > 0,
|
||||||
|
target: "creatingOrder",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
actions: assign({
|
||||||
|
errorMessage:
|
||||||
|
"Choose a plan and accept the agreement before continuing.",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
PaymentRefreshVipStatus: "checkingVipStatus",
|
||||||
|
PaymentErrorCleared: {
|
||||||
|
actions: assign({ errorMessage: null }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
creatingOrder: {
|
||||||
|
invoke: {
|
||||||
|
src: "createOrder",
|
||||||
|
input: ({ context }) => ({
|
||||||
|
planId: context.selectedPlanId,
|
||||||
|
payChannel: context.payChannel,
|
||||||
|
autoRenew: context.autoRenew,
|
||||||
|
}),
|
||||||
|
onDone: {
|
||||||
|
target: "pollingOrder",
|
||||||
|
actions: assign(({ context, event }) => ({
|
||||||
|
currentOrderId: event.output.orderId,
|
||||||
|
payParams: event.output.payParams,
|
||||||
|
orderStatus: "pending",
|
||||||
|
errorMessage: null,
|
||||||
|
launchNonce: context.launchNonce + 1,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
onError: {
|
||||||
|
target: "failed",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
errorMessage: toErrorMessage(event.error),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
pollingOrder: {
|
||||||
|
invoke: {
|
||||||
|
src: "pollOrderStatus",
|
||||||
|
input: ({ context }) => ({
|
||||||
|
orderId: context.currentOrderId ?? "",
|
||||||
|
}),
|
||||||
|
onDone: [
|
||||||
|
{
|
||||||
|
guard: ({ event }) => event.output.status === "paid",
|
||||||
|
target: "checkingVipStatus",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
orderStatus: event.output.status,
|
||||||
|
errorMessage: null,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
guard: ({ event }) => event.output.status === "failed",
|
||||||
|
target: "failed",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
orderStatus: event.output.status,
|
||||||
|
errorMessage: "Payment failed or was cancelled.",
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
target: "waitingForPayment",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
orderStatus: event.output.status,
|
||||||
|
errorMessage: null,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
onError: {
|
||||||
|
target: "failed",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
errorMessage: toErrorMessage(event.error),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
waitingForPayment: {
|
||||||
|
after: {
|
||||||
|
[POLL_DELAY_MS]: "pollingOrder",
|
||||||
|
},
|
||||||
|
on: {
|
||||||
|
PaymentReset: {
|
||||||
|
target: "ready",
|
||||||
|
actions: assign(resetOrderState),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
checkingVipStatus: {
|
||||||
|
invoke: {
|
||||||
|
src: "loadVipStatus",
|
||||||
|
onDone: [
|
||||||
|
{
|
||||||
|
guard: ({ context }) => context.orderStatus === "paid",
|
||||||
|
target: "paid",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
vipStatus: event.output,
|
||||||
|
errorMessage: null,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
target: "ready",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
vipStatus: event.output,
|
||||||
|
errorMessage: null,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
onError: [
|
||||||
|
{
|
||||||
|
guard: ({ context }) => context.orderStatus === "paid",
|
||||||
|
target: "paid",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
errorMessage: toErrorMessage(event.error),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
target: "ready",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
errorMessage: toErrorMessage(event.error),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
paid: {
|
||||||
|
on: {
|
||||||
|
PaymentReset: {
|
||||||
|
target: "ready",
|
||||||
|
actions: assign(resetOrderState),
|
||||||
|
},
|
||||||
|
PaymentRefreshVipStatus: "checkingVipStatus",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
failed: {
|
||||||
|
on: {
|
||||||
|
PaymentCreateOrderSubmitted: [
|
||||||
|
{
|
||||||
|
guard: ({ context }) =>
|
||||||
|
context.agreed && context.selectedPlanId.length > 0,
|
||||||
|
target: "creatingOrder",
|
||||||
|
actions: assign(resetOrderState),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
PaymentErrorCleared: {
|
||||||
|
target: "ready",
|
||||||
|
actions: assign({ errorMessage: null }),
|
||||||
|
},
|
||||||
|
PaymentReset: {
|
||||||
|
target: "ready",
|
||||||
|
actions: assign(resetOrderState),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
on: {
|
||||||
|
PaymentLaunchFailed: {
|
||||||
|
target: ".failed",
|
||||||
|
actions: assign(({ event }) => ({
|
||||||
|
errorMessage: event.errorMessage,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PaymentMachine = typeof paymentMachine;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/**
|
||||||
|
* Payment 状态机:State 形状 + 初始值
|
||||||
|
*/
|
||||||
|
import type {
|
||||||
|
PayChannel,
|
||||||
|
PaymentOrderStatus,
|
||||||
|
PaymentPlan,
|
||||||
|
PaymentVipStatusResponse,
|
||||||
|
} from "@/data/dto/payment";
|
||||||
|
|
||||||
|
export interface PaymentState {
|
||||||
|
plans: PaymentPlan[];
|
||||||
|
selectedPlanId: string;
|
||||||
|
payChannel: PayChannel;
|
||||||
|
autoRenew: boolean;
|
||||||
|
agreed: boolean;
|
||||||
|
currentOrderId: string | null;
|
||||||
|
payParams: Record<string, unknown> | null;
|
||||||
|
orderStatus: PaymentOrderStatus | null;
|
||||||
|
vipStatus: PaymentVipStatusResponse | null;
|
||||||
|
errorMessage: string | null;
|
||||||
|
launchNonce: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const initialState: PaymentState = {
|
||||||
|
plans: [],
|
||||||
|
selectedPlanId: "",
|
||||||
|
payChannel: "stripe",
|
||||||
|
autoRenew: true,
|
||||||
|
agreed: false,
|
||||||
|
currentOrderId: null,
|
||||||
|
payParams: null,
|
||||||
|
orderStatus: null,
|
||||||
|
vipStatus: null,
|
||||||
|
errorMessage: null,
|
||||||
|
launchNonce: 0,
|
||||||
|
};
|
||||||
@@ -58,7 +58,6 @@ export function toView(u: {
|
|||||||
isGuest?: boolean;
|
isGuest?: boolean;
|
||||||
isVip?: boolean;
|
isVip?: boolean;
|
||||||
voiceMinutesRemaining?: number;
|
voiceMinutesRemaining?: number;
|
||||||
stripeCustomerId?: string | null;
|
|
||||||
}): UserView {
|
}): UserView {
|
||||||
return {
|
return {
|
||||||
id: u.id,
|
id: u.id,
|
||||||
@@ -72,7 +71,6 @@ export function toView(u: {
|
|||||||
isGuest: u.isGuest ?? false,
|
isGuest: u.isGuest ?? false,
|
||||||
isVip: u.isVip ?? false,
|
isVip: u.isVip ?? false,
|
||||||
voiceMinutesRemaining: u.voiceMinutesRemaining ?? 0,
|
voiceMinutesRemaining: u.voiceMinutesRemaining ?? 0,
|
||||||
stripeCustomerId: u.stripeCustomerId ?? null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user