feat(payment): connect payment service flow

This commit is contained in:
2026-06-18 15:40:59 +08:00
parent 35c30ac31e
commit a347b39001
34 changed files with 759 additions and 889 deletions
+2 -2
View File
@@ -3,8 +3,8 @@
* 订阅取消回跳页
*
* 流程:
* 1. 用户在 Stripe 托管页点 "Cancel" / 关闭页面
* 2. Stripe 重定向到 `/subscription/cancel`
* 1. 用户在支付服务托管页点 "Cancel" / 关闭页面
* 2. 支付服务重定向到 `/subscription/cancel`
* 3. 这个页面显示 "已取消" + 跳回 `/subscription`
*
* 不需要任何后端逻辑(没付款发生)
-1
View File
@@ -7,6 +7,5 @@ export * from "./subscription-banner";
export * from "./subscription-benefits-card";
export * from "./subscription-checkout-button";
export * from "./subscription-cta-button";
export * from "./subscription-manage-button";
export * from "./subscription-plan-card";
export * from "./subscription-user-row";
@@ -2,75 +2,63 @@
/**
* 订阅 checkout 触发按钮
*
* 包装 `SubscriptionCtaButton` —— 加上调 `/api/payment/create-checkout-session` 的逻辑
*
* 流程:
* 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
* 包装 `SubscriptionCtaButton` —— 通过 payment 状态机创建后端订单并拉起支付。
*/
import { useState } from "react";
import { useEffect, useRef } from "react";
import type { SubscriptionPlanId } from "@/data/constants/subscription-plans";
import { ROUTES } from "@/router/routes";
import {
usePaymentDispatch,
usePaymentState,
} from "@/stores/payment/payment-context";
import { SubscriptionCtaButton } from "./subscription-cta-button";
import styles from "./subscription-cta-button.module.css";
import { Logger } from "@/utils";
const log = new Logger("AppSubscriptionComponentsSubscriptionCheckoutButton");
export interface SubscriptionCheckoutButtonProps {
planId: SubscriptionPlanId;
/** 是否可用(未选套餐 / 未勾选协议 → false) */
disabled?: boolean;
}
export function SubscriptionCheckoutButton({
planId,
disabled = false,
}: SubscriptionCheckoutButtonProps) {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const payment = usePaymentState();
const paymentDispatch = usePaymentDispatch();
const launchedNonceRef = useRef(0);
const handleClick = async () => {
if (disabled || isLoading) return;
setIsLoading(true);
setError(null);
try {
// success / cancel URL —— 走当前 origin 的绝对路径
const origin = window.location.origin;
const res = await fetch("/api/payment/create-checkout-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
planId,
successUrl: `${origin}${ROUTES.subscription}/success?session_id={CHECKOUT_SESSION_ID}`,
cancelUrl: `${origin}${ROUTES.subscription}/cancel`,
}),
});
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 checkout URL returned");
}
// 跳转到 Stripe 托管页
window.location.href = url;
} catch (e) {
const err = e as Error;
log.error("[subscription-checkout-button] error", err);
setError(err.message);
setIsLoading(false);
useEffect(() => {
if (!payment.payParams || payment.launchNonce <= launchedNonceRef.current) {
return;
}
launchedNonceRef.current = payment.launchNonce;
const paymentUrl = getPaymentUrl(payment.payParams);
if (!paymentUrl) {
paymentDispatch({
type: "PaymentLaunchFailed",
errorMessage: "Payment parameters did not include a supported URL.",
});
return;
}
window.location.href = paymentUrl;
}, [payment.launchNonce, payment.payParams, paymentDispatch]);
const isLoading =
payment.isCreatingOrder ||
payment.isPollingOrder ||
payment.isCheckingVipStatus;
const label = payment.isPaid
? "Activated"
: payment.isPollingOrder
? "Processing payment..."
: payment.isCreatingOrder
? "Creating order..."
: "Confirm the agreement and Activate";
const handleClick = () => {
if (disabled || isLoading) return;
paymentDispatch({ type: "PaymentCreateOrderSubmitted" });
};
return (
@@ -82,9 +70,9 @@ export function SubscriptionCheckoutButton({
onClick={handleClick}
className={styles.button}
>
Confirm the agreement and Activate
{label}
</SubscriptionCtaButton>
{error ? (
{payment.errorMessage ? (
<p
role="alert"
style={{
@@ -94,9 +82,28 @@ export function SubscriptionCheckoutButton({
textAlign: "center",
}}
>
{error}
{payment.errorMessage}
</p>
) : 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 粉色边框 + 浅粉阴影
* - 三个卡片底部渐变不同:粉 → 紫红 → 紫
*/
import type { SubscriptionPlan, SubscriptionPlanId } from "@/data/constants/subscription-plans";
import styles from "./subscription-plan-card.module.css";
const PER_DAY_GRADIENTS: Record<SubscriptionPlanId, string> = {
monthly: "linear-gradient(90deg, #ff7ab8 0%, #ff5d9c 100%)",
quarterly: "linear-gradient(90deg, #d16bff 0%, #ff5da3 100%)",
annual: "linear-gradient(90deg, #9a4dff 0%, #c44dff 100%)",
};
const PER_DAY_GRADIENTS = [
"linear-gradient(90deg, #ff7ab8 0%, #ff5d9c 100%)",
"linear-gradient(90deg, #d16bff 0%, #ff5da3 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 {
plan: SubscriptionPlan;
plan: SubscriptionPlanView;
selected: boolean;
onClick: () => void;
gradientIndex?: number;
className?: string;
}
@@ -30,6 +41,7 @@ export function SubscriptionPlanCard({
plan,
selected,
onClick,
gradientIndex = 0,
className,
}: SubscriptionPlanCardProps) {
const classes = [
@@ -41,22 +53,26 @@ export function SubscriptionPlanCard({
.filter(Boolean)
.join(" ");
const perDayStyle = { background: PER_DAY_GRADIENTS[plan.id] };
const perDayStyle = {
background: PER_DAY_GRADIENTS[gradientIndex % PER_DAY_GRADIENTS.length],
};
return (
<button
type="button"
onClick={onClick}
aria-pressed={selected}
aria-label={`${plan.name} plan, $${plan.price}`}
aria-label={`${plan.name} plan, ${plan.currencySymbol}${plan.price}`}
className={classes}
>
<p className={styles.name}>{plan.name}</p>
<div className={styles.priceBlock}>
<span className={styles.currency}>$</span>
<span className={styles.currency}>{plan.currencySymbol}</span>
<span className={styles.price}>{plan.price}</span>
</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}>
{plan.perDay}
</div>
@@ -28,11 +28,21 @@
.plansRow {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(92px, 1fr));
gap: var(--spacing-sm);
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 {
margin: var(--spacing-md) 0 0;
padding: 0 var(--spacing-xs);
+111 -36
View File
@@ -14,48 +14,110 @@
* 7. 主操作按钮
* 8. 协议复选框
*/
import { useState } from "react";
import { useEffect, useMemo, useRef } from "react";
import { Checkbox, MobileShell } from "@/app/_components/core";
import { AppConstants } from "@/core/app_constants";
import {
SUBSCRIPTION_PLANS,
type SubscriptionPlanId,
} from "@/data/constants/subscription-plans";
import type { PaymentPlan } from "@/data/dto/payment";
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 {
SubscriptionBackLink,
SubscriptionBanner,
SubscriptionBenefitsCard,
SubscriptionCheckoutButton,
SubscriptionManageButton,
SubscriptionCtaButton,
SubscriptionPlanCard,
SubscriptionUserRow,
} from "./components";
import styles from "./components/subscription-screen.module.css";
import type { SubscriptionPlanView } from "./components/subscription-plan-card";
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() {
const user = useUserState();
const userDispatch = useUserDispatch();
const payment = usePaymentState();
const paymentDispatch = usePaymentDispatch();
const refreshedPaidOrderRef = useRef<string | null>(null);
const initialPlanId =
SUBSCRIPTION_PLANS.find((p) => p.highlight)?.id ?? null;
useEffect(() => {
if (payment.status === "idle") {
paymentDispatch({ type: "PaymentInit" });
}
}, [payment.status, paymentDispatch]);
// 强制类型为 `SubscriptionPlanId` —— 套餐表只有 3 个 id,不会越界
const [selectedPlanId, setSelectedPlanId] = useState<SubscriptionPlanId | null>(
initialPlanId as SubscriptionPlanId | null,
useEffect(() => {
if (!payment.isPaid || !payment.currentOrderId) return;
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 isVip = user.currentUser?.isVip ?? false;
const stripeCustomerId = user.currentUser?.stripeCustomerId ?? null;
const selectedPlan =
vipPlans.find((plan) => plan.id === payment.selectedPlanId) ?? 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 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 (
<MobileShell>
@@ -76,20 +138,31 @@ export function SubscriptionScreen() {
className={styles.plansRow}
aria-label="Choose a subscription plan"
>
{SUBSCRIPTION_PLANS.map((plan) => (
<SubscriptionPlanCard
key={plan.id}
plan={plan}
selected={selectedPlanId === plan.id}
onClick={() => setSelectedPlanId(plan.id)}
/>
))}
{vipPlans.length > 0 ? (
vipPlans.map((plan, index) => (
<SubscriptionPlanCard
key={plan.id}
plan={plan}
gradientIndex={index}
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>
<p className={styles.autoRenewCaption}>
It will automatically renew upon expiration, and can be canceled at
any time
</p>
<p className={styles.autoRenewCaption}>{autoRenewCaption}</p>
<section className={styles.benefitsSlot}>
<SubscriptionBenefitsCard
@@ -99,15 +172,12 @@ export function SubscriptionScreen() {
</section>
<div className={styles.ctaSlot}>
{/*
* 已为 VIP 的用户 → 显示 Manage VIP 按钮(跳转到 Stripe Customer Portal
* VIP 状态从 `user.isVip` 取(webhook 会设置)
*/}
{isVip ? (
<SubscriptionManageButton customerId={stripeCustomerId} />
<SubscriptionCtaButton type="button" disabled>
VIP Activated
</SubscriptionCtaButton>
) : (
<SubscriptionCheckoutButton
planId={selectedPlanId ?? "monthly"}
disabled={!canActivate}
/>
)}
@@ -115,8 +185,13 @@ export function SubscriptionScreen() {
<div className={styles.agreementSlot}>
<Checkbox
checked={agreed}
onChange={setAgreed}
checked={payment.agreed}
onChange={(agreed) =>
paymentDispatch({
type: "PaymentAgreementChanged",
agreed,
})
}
label={
<>
I agree to the{" "}
+5 -5
View File
@@ -3,13 +3,13 @@
* 订阅成功回跳页
*
* 流程:
* 1. 用户在 Stripe 托管页完成结账
* 2. Stripe 重定向到 `/subscription/success?session_id=xxx`
* 1. 用户在支付服务托管页完成结账
* 2. 支付服务重定向到 `/subscription/success`
* 3. 这个页面显示 "购买成功" + 调 `getCurrentUser` 刷新 user
* 4. 点 "返回订阅页" 跳回 `/subscription`
*
* 注意:webhook 会异步触发 + 更新 user.isVip + voiceMinutes
* 此页面拿到 session_id 后 轮询几次 getCurrentUser 等待 webhook 完成(避免 webhook 还没到 user 就还没更新的情况)
* 注意:权益发放由后端支付服务链路异步完成。
* 此页面轮询几次 getCurrentUser 等待 user 状态完成更新。
*/
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
@@ -25,7 +25,7 @@ export default function SubscriptionSuccessPage() {
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const hasRefreshed = useRef(false);
// 轮询 getCurrentUser 等待 webhook 完成
// 轮询 getCurrentUser 等待后端权益发放完成
useEffect(() => {
if (hasRefreshed.current) return;
hasRefreshed.current = true;