Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84f38f985f | ||
|
|
964a2aa6d9 | ||
|
|
5be0616e78 | ||
|
|
1a44e94bb5 | ||
|
|
c326c6edf1 | ||
|
|
5992c06d67 | ||
|
|
90ad0e0895 | ||
|
|
52aa484202 | ||
|
|
42da18484c | ||
|
|
f4709b784f | ||
|
|
880f0211f3 | ||
|
|
930ce60fcc | ||
|
|
8cf78dc295 | ||
|
|
21cc90a71f | ||
|
|
c9462f4f14 | ||
|
|
d952942627 | ||
|
|
c083880cbc |
65
.env.example
Normal file
65
.env.example
Normal file
@@ -0,0 +1,65 @@
|
||||
# 数据库
|
||||
DATABASE_URL="postgresql://sub2apipay:password@localhost:5432/sub2apipay"
|
||||
|
||||
# Sub2API
|
||||
SUB2API_BASE_URL="https://your-sub2api-domain.com"
|
||||
SUB2API_ADMIN_API_KEY="your-admin-api-key"
|
||||
|
||||
# ── 支付服务商(逗号分隔,决定加载哪些服务商) ───────────────────────────────
|
||||
# 可选值: easypay, stripe
|
||||
# 示例(仅易支付): PAYMENT_PROVIDERS=easypay
|
||||
# 示例(仅 Stripe): PAYMENT_PROVIDERS=stripe
|
||||
# 示例(两者都用): PAYMENT_PROVIDERS=easypay,stripe
|
||||
PAYMENT_PROVIDERS=easypay
|
||||
|
||||
# ── 易支付配置(PAYMENT_PROVIDERS 含 easypay 时必填) ────────────────────────
|
||||
EASY_PAY_PID="your-pid"
|
||||
EASY_PAY_PKEY="your-pkey"
|
||||
EASY_PAY_API_BASE="https://zpayz.cn"
|
||||
EASY_PAY_NOTIFY_URL="https://pay.example.com/api/easy-pay/notify"
|
||||
EASY_PAY_RETURN_URL="https://pay.example.com/pay/result"
|
||||
# 渠道 ID(部分易支付平台需要,可选)
|
||||
#EASY_PAY_CID_ALIPAY=""
|
||||
#EASY_PAY_CID_WXPAY=""
|
||||
|
||||
# ── Stripe 配置(PAYMENT_PROVIDERS 含 stripe 时必填) ────────────────────────
|
||||
#STRIPE_SECRET_KEY="sk_live_..."
|
||||
#STRIPE_PUBLISHABLE_KEY="pk_live_..."
|
||||
#STRIPE_WEBHOOK_SECRET="whsec_..."
|
||||
|
||||
# ── 启用的支付渠道(在已配置服务商支持的渠道中选择) ─────────────────────────
|
||||
# 易支付支持: alipay, wxpay
|
||||
# Stripe 支持: stripe
|
||||
ENABLED_PAYMENT_TYPES="alipay,wxpay"
|
||||
|
||||
# ── 订单配置 ──────────────────────────────────────────────────────────────────
|
||||
ORDER_TIMEOUT_MINUTES="5"
|
||||
MIN_RECHARGE_AMOUNT="1"
|
||||
MAX_RECHARGE_AMOUNT="10000"
|
||||
# 每用户每日累计充值上限,0 = 不限制
|
||||
MAX_DAILY_RECHARGE_AMOUNT="0"
|
||||
# 各渠道全平台每日总限额,0 = 不限制(未设置则使用各服务商默认值)
|
||||
#MAX_DAILY_AMOUNT_ALIPAY="0"
|
||||
#MAX_DAILY_AMOUNT_WXPAY="0"
|
||||
#MAX_DAILY_AMOUNT_STRIPE="0"
|
||||
PRODUCT_NAME="Sub2API 余额充值"
|
||||
|
||||
# ── 手续费(百分比,可选) ─────────────────────────────────────────────────────
|
||||
# 提供商级别(应用于该提供商下所有渠道)
|
||||
#FEE_RATE_PROVIDER_EASYPAY=1.6
|
||||
#FEE_RATE_PROVIDER_STRIPE=5.9
|
||||
# 渠道级别(覆盖提供商级别)
|
||||
#FEE_RATE_ALIPAY=
|
||||
#FEE_RATE_WXPAY=
|
||||
#FEE_RATE_STRIPE=
|
||||
|
||||
# ── 管理员 ────────────────────────────────────────────────────────────────────
|
||||
ADMIN_TOKEN="your-admin-token"
|
||||
|
||||
# ── 应用 ──────────────────────────────────────────────────────────────────────
|
||||
NEXT_PUBLIC_APP_URL="https://pay.example.com"
|
||||
# iframe 允许嵌入的域名(逗号分隔)
|
||||
IFRAME_ALLOW_ORIGINS="https://example.com"
|
||||
# 充值页面底部帮助内容(可选)
|
||||
#PAY_HELP_IMAGE_URL="https://example.com/qrcode.png"
|
||||
#PAY_HELP_TEXT="如需帮助请联系客服微信:xxxxx"
|
||||
44
.github/workflows/release.yml
vendored
Normal file
44
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Create Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Generate changelog
|
||||
id: changelog
|
||||
run: |
|
||||
# Get previous tag
|
||||
PREV_TAG=$(git tag --sort=-v:refname | sed -n '2p')
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
COMMITS=$(git log --pretty=format:"- %s (%h)" HEAD)
|
||||
else
|
||||
COMMITS=$(git log --pretty=format:"- %s (%h)" "${PREV_TAG}..HEAD")
|
||||
fi
|
||||
{
|
||||
echo 'body<<EOF'
|
||||
echo "## What's Changed"
|
||||
echo ""
|
||||
echo "$COMMITS"
|
||||
echo ""
|
||||
echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG:-$(git rev-list --max-parents=0 HEAD | head -1)}...${{ github.ref_name }}"
|
||||
echo 'EOF'
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
body: ${{ steps.changelog.outputs.body }}
|
||||
generate_release_notes: false
|
||||
74
README.en.md
74
README.en.md
@@ -94,16 +94,39 @@ See [`.env.example`](./.env.example) for the full template.
|
||||
|
||||
> `DATABASE_URL` is automatically injected by Docker Compose when using the bundled database.
|
||||
|
||||
### Payment Methods
|
||||
### Payment Providers & Methods
|
||||
|
||||
Control which payment methods are enabled via `ENABLED_PAYMENT_TYPES` (comma-separated):
|
||||
**Step 1**: Declare which payment providers to load via `PAYMENT_PROVIDERS` (comma-separated):
|
||||
|
||||
```env
|
||||
ENABLED_PAYMENT_TYPES=alipay,wxpay,stripe
|
||||
# EasyPay only
|
||||
PAYMENT_PROVIDERS=easypay
|
||||
# Stripe only
|
||||
PAYMENT_PROVIDERS=stripe
|
||||
# Both
|
||||
PAYMENT_PROVIDERS=easypay,stripe
|
||||
```
|
||||
|
||||
**Step 2**: Control which channels are shown to users via `ENABLED_PAYMENT_TYPES`:
|
||||
|
||||
```env
|
||||
# EasyPay supports: alipay, wxpay | Stripe supports: stripe
|
||||
ENABLED_PAYMENT_TYPES=alipay,wxpay
|
||||
```
|
||||
|
||||
#### EasyPay (Alipay / WeChat Pay)
|
||||
|
||||
Any payment provider compatible with the **EasyPay protocol** can be used, such as [ZPay](https://z-pay.cn/?uid=23808) (`https://z-pay.cn/?uid=23808`) (this link contains the author's referral code — feel free to remove it).
|
||||
|
||||
<details>
|
||||
<summary>ZPay Registration QR Code</summary>
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
> **Disclaimer**: Please evaluate the security, reliability, and compliance of any third-party payment provider on your own. This project does not endorse or guarantee any specific provider.
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `EASY_PAY_PID` | EasyPay merchant ID |
|
||||
@@ -123,7 +146,7 @@ ENABLED_PAYMENT_TYPES=alipay,wxpay,stripe
|
||||
| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret (`whsec_...`) |
|
||||
|
||||
> Stripe webhook endpoint: `${NEXT_PUBLIC_APP_URL}/api/stripe/webhook`
|
||||
> Subscribe to: `checkout.session.completed`, `checkout.session.expired`
|
||||
> Subscribe to: `payment_intent.succeeded`, `payment_intent.payment_failed`
|
||||
|
||||
### Business Rules
|
||||
|
||||
@@ -137,10 +160,31 @@ ENABLED_PAYMENT_TYPES=alipay,wxpay,stripe
|
||||
|
||||
### UI Customization (Optional)
|
||||
|
||||
Display a support contact image and description on the right side of the payment page.
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `NEXT_PUBLIC_PAY_HELP_IMAGE_URL` | Help image URL (e.g. customer service QR code) |
|
||||
| `NEXT_PUBLIC_PAY_HELP_TEXT` | Help text displayed on payment page |
|
||||
| `PAY_HELP_IMAGE_URL` | Help image URL — external URL or local path (see below) |
|
||||
| `PAY_HELP_TEXT` | Help text; use `\n` for line breaks, e.g. `Scan to add WeChat\nMon–Fri 9am–6pm` |
|
||||
|
||||
**Two ways to provide the image:**
|
||||
|
||||
- **External URL** (recommended — no Compose changes needed): any publicly accessible image link (CDN, OSS, image hosting).
|
||||
```env
|
||||
PAY_HELP_IMAGE_URL=https://cdn.example.com/help-qr.jpg
|
||||
```
|
||||
|
||||
- **Local file**: place the image in `./uploads/` and reference it as `/uploads/<filename>`.
|
||||
The directory must be mounted in `docker-compose.app.yml` (included by default):
|
||||
```yaml
|
||||
volumes:
|
||||
- ./uploads:/app/public/uploads:ro
|
||||
```
|
||||
```env
|
||||
PAY_HELP_IMAGE_URL=/uploads/help-qr.jpg
|
||||
```
|
||||
|
||||
> Clicking the help image opens it full-screen in the center of the screen.
|
||||
|
||||
### Docker Compose Variables
|
||||
|
||||
@@ -220,16 +264,20 @@ docker compose exec app npx prisma migrate deploy
|
||||
|
||||
## Sub2API Integration
|
||||
|
||||
Configure the recharge URL in the Sub2API admin panel:
|
||||
The following page URLs can be configured in the Sub2API admin panel:
|
||||
|
||||
```
|
||||
https://pay.example.com/pay?user_id={USER_ID}&token={TOKEN}&theme={THEME}
|
||||
```
|
||||
| Page | URL | Description |
|
||||
|------|-----|-------------|
|
||||
| Payment | `https://pay.example.com/pay` | User recharge entry |
|
||||
| My Orders | `https://pay.example.com/pay/orders` | User views their own recharge history |
|
||||
| Order Management | `https://pay.example.com/admin` | Sub2API admin only |
|
||||
|
||||
Sub2API **v0.1.88** and above will automatically append the following parameters — no manual query string needed:
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `user_id` | Sub2API user ID (required) |
|
||||
| `token` | User login token (optional — required to view order history) |
|
||||
| `user_id` | Sub2API user ID |
|
||||
| `token` | User login token (required to view order history) |
|
||||
| `theme` | `light` (default) or `dark` |
|
||||
| `ui_mode` | `standalone` (default) or `embedded` (for iframe) |
|
||||
|
||||
@@ -262,7 +310,7 @@ User submits recharge amount
|
||||
▼
|
||||
User completes payment
|
||||
├─ EasyPay → QR code / H5 redirect
|
||||
└─ Stripe → Checkout Session
|
||||
└─ Stripe → Payment Element (PaymentIntent)
|
||||
│
|
||||
▼
|
||||
Payment callback (signature verified) → Order PAID
|
||||
|
||||
74
README.md
74
README.md
@@ -94,16 +94,39 @@ docker compose up -d --build
|
||||
|
||||
> `DATABASE_URL` 使用自带数据库时由 Compose 自动注入,无需手动填写。
|
||||
|
||||
### 支付方式
|
||||
### 支付服务商与支付方式
|
||||
|
||||
通过 `ENABLED_PAYMENT_TYPES` 控制开启哪些支付方式(逗号分隔):
|
||||
**第一步**:通过 `PAYMENT_PROVIDERS` 声明启用哪些支付服务商(逗号分隔):
|
||||
|
||||
```env
|
||||
ENABLED_PAYMENT_TYPES=alipay,wxpay,stripe
|
||||
# 仅易支付
|
||||
PAYMENT_PROVIDERS=easypay
|
||||
# 仅 Stripe
|
||||
PAYMENT_PROVIDERS=stripe
|
||||
# 两者都用
|
||||
PAYMENT_PROVIDERS=easypay,stripe
|
||||
```
|
||||
|
||||
**第二步**:通过 `ENABLED_PAYMENT_TYPES` 控制向用户展示哪些支付渠道:
|
||||
|
||||
```env
|
||||
# 易支付支持: alipay, wxpay;Stripe 支持: stripe
|
||||
ENABLED_PAYMENT_TYPES=alipay,wxpay
|
||||
```
|
||||
|
||||
#### EasyPay(支付宝 / 微信支付)
|
||||
|
||||
支付提供商只需兼容**易支付(EasyPay)协议**即可接入,例如 [ZPay](https://z-pay.cn/?uid=23808)(`https://z-pay.cn/?uid=23808`)等平台(链接含本项目作者的邀请码,介意可去掉)。
|
||||
|
||||
<details>
|
||||
<summary>ZPay 申请二维码</summary>
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
> **注意**:支付渠道的安全性、稳定性及合规性请自行鉴别,本项目不对任何第三方支付服务商做担保或背书。
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `EASY_PAY_PID` | EasyPay 商户 ID |
|
||||
@@ -123,7 +146,7 @@ ENABLED_PAYMENT_TYPES=alipay,wxpay,stripe
|
||||
| `STRIPE_WEBHOOK_SECRET` | Stripe Webhook 签名密钥(`whsec_...`) |
|
||||
|
||||
> Stripe Webhook 端点:`${NEXT_PUBLIC_APP_URL}/api/stripe/webhook`
|
||||
> 需订阅事件:`checkout.session.completed`、`checkout.session.expired`
|
||||
> 需订阅事件:`payment_intent.succeeded`、`payment_intent.payment_failed`
|
||||
|
||||
### 业务规则
|
||||
|
||||
@@ -137,10 +160,31 @@ ENABLED_PAYMENT_TYPES=alipay,wxpay,stripe
|
||||
|
||||
### UI 定制(可选)
|
||||
|
||||
在充值页面右侧可展示客服联系方式、说明图片等帮助内容。
|
||||
|
||||
| 变量 | 说明 |
|
||||
|------|------|
|
||||
| `NEXT_PUBLIC_PAY_HELP_IMAGE_URL` | 帮助图片 URL(如客服二维码) |
|
||||
| `NEXT_PUBLIC_PAY_HELP_TEXT` | 帮助说明文字 |
|
||||
| `PAY_HELP_IMAGE_URL` | 帮助图片地址(支持外部 URL 或本地路径,见下方说明) |
|
||||
| `PAY_HELP_TEXT` | 帮助说明文字,用 `\n` 换行,如 `扫码加微信\n工作日 9-18 点在线` |
|
||||
|
||||
**图片地址两种方式:**
|
||||
|
||||
- **外部 URL**(推荐,无需改 Compose 配置):直接填图片的公网地址,如 OSS / CDN / 图床链接。
|
||||
```env
|
||||
PAY_HELP_IMAGE_URL=https://cdn.example.com/help-qr.jpg
|
||||
```
|
||||
|
||||
- **本地文件**:将图片放到 `./uploads/` 目录,通过 `/uploads/文件名` 引用。
|
||||
需在 `docker-compose.app.yml` 中挂载目录(默认已包含):
|
||||
```yaml
|
||||
volumes:
|
||||
- ./uploads:/app/public/uploads:ro
|
||||
```
|
||||
```env
|
||||
PAY_HELP_IMAGE_URL=/uploads/help-qr.jpg
|
||||
```
|
||||
|
||||
> 点击帮助图片可在屏幕中央全屏放大查看。
|
||||
|
||||
### Docker Compose 专用
|
||||
|
||||
@@ -220,16 +264,20 @@ docker compose exec app npx prisma migrate deploy
|
||||
|
||||
## 集成到 Sub2API
|
||||
|
||||
在 Sub2API 管理后台将充值链接配置为:
|
||||
在 Sub2API 管理后台可配置以下页面链接:
|
||||
|
||||
```
|
||||
https://pay.example.com/pay?user_id={USER_ID}&token={TOKEN}&theme={THEME}
|
||||
```
|
||||
| 页面 | 链接 | 说明 |
|
||||
|------|------|------|
|
||||
| 充值页面 | `https://pay.example.com/pay` | 用户充值入口 |
|
||||
| 我的订单 | `https://pay.example.com/pay/orders` | 用户查看自己的充值记录 |
|
||||
| 订单管理 | `https://pay.example.com/admin` | 仅 Sub2API 管理员可访问 |
|
||||
|
||||
Sub2API **v0.1.88** 及以上版本会自动拼接以下参数,无需手动添加:
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `user_id` | Sub2API 用户 ID(必填) |
|
||||
| `token` | 用户登录 Token(可选,有 token 才能查看订单历史) |
|
||||
| `user_id` | Sub2API 用户 ID |
|
||||
| `token` | 用户登录 Token(有 token 才能查看订单历史) |
|
||||
| `theme` | `light`(默认)或 `dark` |
|
||||
| `ui_mode` | `standalone`(默认)或 `embedded`(iframe 嵌入) |
|
||||
|
||||
@@ -262,7 +310,7 @@ https://pay.example.com/pay?user_id={USER_ID}&token={TOKEN}&theme={THEME}
|
||||
▼
|
||||
用户完成支付
|
||||
├─ EasyPay → 扫码 / H5 跳转
|
||||
└─ Stripe → Checkout Session
|
||||
└─ Stripe → Payment Element (PaymentIntent)
|
||||
│
|
||||
▼
|
||||
支付回调(签名验证)→ 订单 PAID
|
||||
|
||||
BIN
docs/zpay-preview.png
Normal file
BIN
docs/zpay-preview.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 135 KiB |
@@ -16,6 +16,8 @@
|
||||
"dependencies": {
|
||||
"@prisma/adapter-pg": "7.4.1",
|
||||
"@prisma/client": "^7.4.2",
|
||||
"@stripe/react-stripe-js": "^5.6.1",
|
||||
"@stripe/stripe-js": "^8.9.0",
|
||||
"next": "16.1.6",
|
||||
"pg": "^8.19.0",
|
||||
"qrcode": "^1.5.4",
|
||||
|
||||
42
pnpm-lock.yaml
generated
42
pnpm-lock.yaml
generated
@@ -14,6 +14,12 @@ importers:
|
||||
'@prisma/client':
|
||||
specifier: ^7.4.2
|
||||
version: 7.4.2(prisma@7.4.1(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(typescript@5.9.3))(typescript@5.9.3)
|
||||
'@stripe/react-stripe-js':
|
||||
specifier: ^5.6.1
|
||||
version: 5.6.1(@stripe/stripe-js@8.9.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
'@stripe/stripe-js':
|
||||
specifier: ^8.9.0
|
||||
version: 8.9.0
|
||||
next:
|
||||
specifier: 16.1.6
|
||||
version: 16.1.6(@babel/core@7.29.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
@@ -874,6 +880,17 @@ packages:
|
||||
'@standard-schema/spec@1.1.0':
|
||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||
|
||||
'@stripe/react-stripe-js@5.6.1':
|
||||
resolution: {integrity: sha512-5xBrjkGmFvKvpMod6VvpOaFaa67eRbmieKeFTePZyOr/sUXzm7A3YY91l330pS0usUst5PxTZDUZHWfOc0v1GA==}
|
||||
peerDependencies:
|
||||
'@stripe/stripe-js': '>=8.0.0 <9.0.0'
|
||||
react: '>=16.8.0 <20.0.0'
|
||||
react-dom: '>=16.8.0 <20.0.0'
|
||||
|
||||
'@stripe/stripe-js@8.9.0':
|
||||
resolution: {integrity: sha512-OJkXvUI5GAc56QdiSRimQDvWYEqn475J+oj8RzRtFTCPtkJNO2TWW619oDY+nn1ExR+2tCVTQuRQBbR4dRugww==}
|
||||
engines: {node: '>=12.16'}
|
||||
|
||||
'@swc/helpers@0.5.15':
|
||||
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
|
||||
|
||||
@@ -3613,6 +3630,15 @@ snapshots:
|
||||
|
||||
'@standard-schema/spec@1.1.0': {}
|
||||
|
||||
'@stripe/react-stripe-js@5.6.1(@stripe/stripe-js@8.9.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
|
||||
dependencies:
|
||||
'@stripe/stripe-js': 8.9.0
|
||||
prop-types: 15.8.1
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3(react@19.2.3)
|
||||
|
||||
'@stripe/stripe-js@8.9.0': {}
|
||||
|
||||
'@swc/helpers@0.5.15':
|
||||
dependencies:
|
||||
tslib: 2.8.1
|
||||
@@ -4402,8 +4428,8 @@ snapshots:
|
||||
'@next/eslint-plugin-next': 16.1.6
|
||||
eslint: 9.39.3(jiti@2.6.1)
|
||||
eslint-import-resolver-node: 0.3.9
|
||||
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-plugin-react: 7.37.5(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-plugin-react-hooks: 7.0.1(eslint@9.39.3(jiti@2.6.1))
|
||||
@@ -4425,7 +4451,7 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.3(jiti@2.6.1)):
|
||||
eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)):
|
||||
dependencies:
|
||||
'@nolyfill/is-core-module': 1.0.39
|
||||
debug: 4.4.3
|
||||
@@ -4436,22 +4462,22 @@ snapshots:
|
||||
tinyglobby: 0.2.15
|
||||
unrs-resolver: 1.11.1
|
||||
optionalDependencies:
|
||||
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1))
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
eslint-module-utils@2.12.1(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.3(jiti@2.6.1)):
|
||||
eslint-module-utils@2.12.1(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)):
|
||||
dependencies:
|
||||
debug: 3.2.7
|
||||
optionalDependencies:
|
||||
'@typescript-eslint/parser': 8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3)
|
||||
eslint: 9.39.3(jiti@2.6.1)
|
||||
eslint-import-resolver-node: 0.3.9
|
||||
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1))
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.3(jiti@2.6.1)):
|
||||
eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)):
|
||||
dependencies:
|
||||
'@rtsao/scc': 1.1.0
|
||||
array-includes: 3.1.9
|
||||
@@ -4462,7 +4488,7 @@ snapshots:
|
||||
doctrine: 2.1.0
|
||||
eslint: 9.39.3(jiti@2.6.1)
|
||||
eslint-import-resolver-node: 0.3.9
|
||||
eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.3(jiti@2.6.1))
|
||||
eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.56.1(eslint@9.39.3(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1)))(eslint@9.39.3(jiti@2.6.1))
|
||||
hasown: 2.0.2
|
||||
is-core-module: 2.16.1
|
||||
is-glob: 4.0.3
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "orders" ADD COLUMN "src_host" TEXT,
|
||||
ADD COLUMN "src_url" TEXT;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "orders" ADD COLUMN "user_notes" TEXT;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "orders" ADD COLUMN "pay_amount" DECIMAL(10,2),
|
||||
ADD COLUMN "fee_rate" DECIMAL(5,2);
|
||||
@@ -11,7 +11,10 @@ model Order {
|
||||
userId Int @map("user_id")
|
||||
userEmail String? @map("user_email")
|
||||
userName String? @map("user_name")
|
||||
userNotes String? @map("user_notes")
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
payAmount Decimal? @db.Decimal(10, 2) @map("pay_amount")
|
||||
feeRate Decimal? @db.Decimal(5, 2) @map("fee_rate")
|
||||
rechargeCode String @unique @map("recharge_code")
|
||||
status OrderStatus @default(PENDING)
|
||||
paymentType String @map("payment_type")
|
||||
@@ -34,6 +37,8 @@ model Order {
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
clientIp String? @map("client_ip")
|
||||
srcHost String? @map("src_host")
|
||||
srcUrl String? @map("src_url")
|
||||
|
||||
auditLogs AuditLog[]
|
||||
|
||||
|
||||
@@ -12,10 +12,12 @@ import type {
|
||||
|
||||
class MockProvider implements PaymentProvider {
|
||||
readonly name: string;
|
||||
readonly providerKey: string;
|
||||
readonly supportedTypes: PaymentType[];
|
||||
|
||||
constructor(name: string, types: PaymentType[]) {
|
||||
this.name = name;
|
||||
this.providerKey = name;
|
||||
this.supportedTypes = types;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,18 +9,18 @@ vi.mock('@/lib/config', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
const mockSessionCreate = vi.fn();
|
||||
const mockSessionRetrieve = vi.fn();
|
||||
const mockPaymentIntentCreate = vi.fn();
|
||||
const mockPaymentIntentRetrieve = vi.fn();
|
||||
const mockPaymentIntentCancel = vi.fn();
|
||||
const mockRefundCreate = vi.fn();
|
||||
const mockWebhooksConstructEvent = vi.fn();
|
||||
|
||||
vi.mock('stripe', () => {
|
||||
const StripeMock = function (this: Record<string, unknown>) {
|
||||
this.checkout = {
|
||||
sessions: {
|
||||
create: mockSessionCreate,
|
||||
retrieve: mockSessionRetrieve,
|
||||
},
|
||||
this.paymentIntents = {
|
||||
create: mockPaymentIntentCreate,
|
||||
retrieve: mockPaymentIntentRetrieve,
|
||||
cancel: mockPaymentIntentCancel,
|
||||
};
|
||||
this.refunds = {
|
||||
create: mockRefundCreate,
|
||||
@@ -54,10 +54,10 @@ describe('StripeProvider', () => {
|
||||
});
|
||||
|
||||
describe('createPayment', () => {
|
||||
it('should create a checkout session and return checkoutUrl', async () => {
|
||||
mockSessionCreate.mockResolvedValue({
|
||||
id: 'cs_test_abc123',
|
||||
url: 'https://checkout.stripe.com/pay/cs_test_abc123',
|
||||
it('should create a PaymentIntent and return clientSecret', async () => {
|
||||
mockPaymentIntentCreate.mockResolvedValue({
|
||||
id: 'pi_test_abc123',
|
||||
client_secret: 'pi_test_abc123_secret_xyz',
|
||||
});
|
||||
|
||||
const request: CreatePaymentRequest = {
|
||||
@@ -70,34 +70,26 @@ describe('StripeProvider', () => {
|
||||
|
||||
const result = await provider.createPayment(request);
|
||||
|
||||
expect(result.tradeNo).toBe('cs_test_abc123');
|
||||
expect(result.checkoutUrl).toBe('https://checkout.stripe.com/pay/cs_test_abc123');
|
||||
expect(mockSessionCreate).toHaveBeenCalledWith(
|
||||
expect(result.tradeNo).toBe('pi_test_abc123');
|
||||
expect(result.clientSecret).toBe('pi_test_abc123_secret_xyz');
|
||||
expect(mockPaymentIntentCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
mode: 'payment',
|
||||
payment_method_types: ['card'],
|
||||
amount: 9999,
|
||||
currency: 'cny',
|
||||
automatic_payment_methods: { enabled: true },
|
||||
metadata: { orderId: 'order-001' },
|
||||
expires_at: expect.any(Number),
|
||||
line_items: [
|
||||
expect.objectContaining({
|
||||
price_data: expect.objectContaining({
|
||||
currency: 'cny',
|
||||
unit_amount: 9999,
|
||||
}),
|
||||
quantity: 1,
|
||||
}),
|
||||
],
|
||||
description: 'Sub2API Balance Recharge 99.99 CNY',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
idempotencyKey: 'checkout-order-001',
|
||||
idempotencyKey: 'pi-order-001',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle session with null url', async () => {
|
||||
mockSessionCreate.mockResolvedValue({
|
||||
id: 'cs_test_no_url',
|
||||
url: null,
|
||||
it('should handle null client_secret', async () => {
|
||||
mockPaymentIntentCreate.mockResolvedValue({
|
||||
id: 'pi_test_no_secret',
|
||||
client_secret: null,
|
||||
});
|
||||
|
||||
const request: CreatePaymentRequest = {
|
||||
@@ -108,61 +100,58 @@ describe('StripeProvider', () => {
|
||||
};
|
||||
|
||||
const result = await provider.createPayment(request);
|
||||
expect(result.tradeNo).toBe('cs_test_no_url');
|
||||
expect(result.checkoutUrl).toBeUndefined();
|
||||
expect(result.tradeNo).toBe('pi_test_no_secret');
|
||||
expect(result.clientSecret).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('queryOrder', () => {
|
||||
it('should return paid status for paid session', async () => {
|
||||
mockSessionRetrieve.mockResolvedValue({
|
||||
id: 'cs_test_abc123',
|
||||
payment_status: 'paid',
|
||||
amount_total: 9999,
|
||||
it('should return paid status for succeeded PaymentIntent', async () => {
|
||||
mockPaymentIntentRetrieve.mockResolvedValue({
|
||||
id: 'pi_test_abc123',
|
||||
status: 'succeeded',
|
||||
amount: 9999,
|
||||
});
|
||||
|
||||
const result = await provider.queryOrder('cs_test_abc123');
|
||||
expect(result.tradeNo).toBe('cs_test_abc123');
|
||||
const result = await provider.queryOrder('pi_test_abc123');
|
||||
expect(result.tradeNo).toBe('pi_test_abc123');
|
||||
expect(result.status).toBe('paid');
|
||||
expect(result.amount).toBe(99.99);
|
||||
});
|
||||
|
||||
it('should return failed status for expired session', async () => {
|
||||
mockSessionRetrieve.mockResolvedValue({
|
||||
id: 'cs_test_expired',
|
||||
payment_status: 'unpaid',
|
||||
status: 'expired',
|
||||
amount_total: 5000,
|
||||
it('should return failed status for canceled PaymentIntent', async () => {
|
||||
mockPaymentIntentRetrieve.mockResolvedValue({
|
||||
id: 'pi_test_canceled',
|
||||
status: 'canceled',
|
||||
amount: 5000,
|
||||
});
|
||||
|
||||
const result = await provider.queryOrder('cs_test_expired');
|
||||
const result = await provider.queryOrder('pi_test_canceled');
|
||||
expect(result.status).toBe('failed');
|
||||
expect(result.amount).toBe(50);
|
||||
});
|
||||
|
||||
it('should return pending status for unpaid session', async () => {
|
||||
mockSessionRetrieve.mockResolvedValue({
|
||||
id: 'cs_test_pending',
|
||||
payment_status: 'unpaid',
|
||||
status: 'open',
|
||||
amount_total: 1000,
|
||||
it('should return pending status for requires_payment_method', async () => {
|
||||
mockPaymentIntentRetrieve.mockResolvedValue({
|
||||
id: 'pi_test_pending',
|
||||
status: 'requires_payment_method',
|
||||
amount: 1000,
|
||||
});
|
||||
|
||||
const result = await provider.queryOrder('cs_test_pending');
|
||||
const result = await provider.queryOrder('pi_test_pending');
|
||||
expect(result.status).toBe('pending');
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyNotification', () => {
|
||||
it('should verify and parse checkout.session.completed event', async () => {
|
||||
it('should verify and parse payment_intent.succeeded event', async () => {
|
||||
const mockEvent = {
|
||||
type: 'checkout.session.completed',
|
||||
type: 'payment_intent.succeeded',
|
||||
data: {
|
||||
object: {
|
||||
id: 'cs_test_abc123',
|
||||
id: 'pi_test_abc123',
|
||||
metadata: { orderId: 'order-001' },
|
||||
amount_total: 9999,
|
||||
payment_status: 'paid',
|
||||
amount: 9999,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -172,21 +161,20 @@ describe('StripeProvider', () => {
|
||||
const result = await provider.verifyNotification('{"raw":"body"}', { 'stripe-signature': 'sig_test_123' });
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.tradeNo).toBe('cs_test_abc123');
|
||||
expect(result!.tradeNo).toBe('pi_test_abc123');
|
||||
expect(result!.orderId).toBe('order-001');
|
||||
expect(result!.amount).toBe(99.99);
|
||||
expect(result!.status).toBe('success');
|
||||
});
|
||||
|
||||
it('should return failed status for unpaid session', async () => {
|
||||
it('should return failed status for payment_intent.payment_failed', async () => {
|
||||
const mockEvent = {
|
||||
type: 'checkout.session.completed',
|
||||
type: 'payment_intent.payment_failed',
|
||||
data: {
|
||||
object: {
|
||||
id: 'cs_test_unpaid',
|
||||
id: 'pi_test_failed',
|
||||
metadata: { orderId: 'order-002' },
|
||||
amount_total: 5000,
|
||||
payment_status: 'unpaid',
|
||||
amount: 5000,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -210,19 +198,14 @@ describe('StripeProvider', () => {
|
||||
});
|
||||
|
||||
describe('refund', () => {
|
||||
it('should refund via payment intent from session', async () => {
|
||||
mockSessionRetrieve.mockResolvedValue({
|
||||
id: 'cs_test_abc123',
|
||||
payment_intent: 'pi_test_payment_intent',
|
||||
});
|
||||
|
||||
it('should refund directly using PaymentIntent ID', async () => {
|
||||
mockRefundCreate.mockResolvedValue({
|
||||
id: 're_test_refund_001',
|
||||
status: 'succeeded',
|
||||
});
|
||||
|
||||
const request: RefundRequest = {
|
||||
tradeNo: 'cs_test_abc123',
|
||||
tradeNo: 'pi_test_abc123',
|
||||
orderId: 'order-001',
|
||||
amount: 50,
|
||||
reason: 'customer request',
|
||||
@@ -232,50 +215,34 @@ describe('StripeProvider', () => {
|
||||
expect(result.refundId).toBe('re_test_refund_001');
|
||||
expect(result.status).toBe('success');
|
||||
expect(mockRefundCreate).toHaveBeenCalledWith({
|
||||
payment_intent: 'pi_test_payment_intent',
|
||||
payment_intent: 'pi_test_abc123',
|
||||
amount: 5000,
|
||||
reason: 'requested_by_customer',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle payment intent as object', async () => {
|
||||
mockSessionRetrieve.mockResolvedValue({
|
||||
id: 'cs_test_abc123',
|
||||
payment_intent: { id: 'pi_test_obj_intent', amount: 10000 },
|
||||
});
|
||||
|
||||
it('should handle pending refund status', async () => {
|
||||
mockRefundCreate.mockResolvedValue({
|
||||
id: 're_test_refund_002',
|
||||
status: 'pending',
|
||||
});
|
||||
|
||||
const result = await provider.refund({
|
||||
tradeNo: 'cs_test_abc123',
|
||||
tradeNo: 'pi_test_abc123',
|
||||
orderId: 'order-002',
|
||||
amount: 100,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('pending');
|
||||
expect(mockRefundCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payment_intent: 'pi_test_obj_intent',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw if no payment intent found', async () => {
|
||||
mockSessionRetrieve.mockResolvedValue({
|
||||
id: 'cs_test_no_pi',
|
||||
payment_intent: null,
|
||||
});
|
||||
describe('cancelPayment', () => {
|
||||
it('should cancel a PaymentIntent', async () => {
|
||||
mockPaymentIntentCancel.mockResolvedValue({ id: 'pi_test_abc123', status: 'canceled' });
|
||||
|
||||
await expect(
|
||||
provider.refund({
|
||||
tradeNo: 'cs_test_no_pi',
|
||||
orderId: 'order-003',
|
||||
amount: 20,
|
||||
}),
|
||||
).rejects.toThrow('No payment intent found');
|
||||
await provider.cancelPayment('pi_test_abc123');
|
||||
expect(mockPaymentIntentCancel).toHaveBeenCalledWith('pi_test_abc123');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,12 +5,14 @@ import { useState, useEffect, useCallback, Suspense } from 'react';
|
||||
import OrderTable from '@/components/admin/OrderTable';
|
||||
import OrderDetail from '@/components/admin/OrderDetail';
|
||||
import PaginationBar from '@/components/PaginationBar';
|
||||
import PayPageLayout from '@/components/PayPageLayout';
|
||||
|
||||
interface AdminOrder {
|
||||
id: string;
|
||||
userId: number;
|
||||
userName: string | null;
|
||||
userEmail: string | null;
|
||||
userNotes: string | null;
|
||||
amount: number;
|
||||
status: string;
|
||||
paymentType: string;
|
||||
@@ -19,6 +21,7 @@ interface AdminOrder {
|
||||
completedAt: string | null;
|
||||
failedReason: string | null;
|
||||
expiresAt: string;
|
||||
srcHost: string | null;
|
||||
}
|
||||
|
||||
interface AdminOrderDetail extends AdminOrder {
|
||||
@@ -31,6 +34,8 @@ interface AdminOrderDetail extends AdminOrder {
|
||||
failedAt: string | null;
|
||||
updatedAt: string;
|
||||
clientIp: string | null;
|
||||
srcHost: string | null;
|
||||
srcUrl: string | null;
|
||||
paymentSuccess?: boolean;
|
||||
rechargeSuccess?: boolean;
|
||||
rechargeStatus?: string;
|
||||
@@ -40,6 +45,10 @@ interface AdminOrderDetail extends AdminOrder {
|
||||
function AdminContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams.get('token');
|
||||
const theme = searchParams.get('theme') === 'dark' ? 'dark' : 'light';
|
||||
const uiMode = searchParams.get('ui_mode') || 'standalone';
|
||||
const isDark = theme === 'dark';
|
||||
const isEmbedded = uiMode === 'embedded';
|
||||
|
||||
const [orders, setOrders] = useState<AdminOrder[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
@@ -85,8 +94,11 @@ function AdminContent() {
|
||||
|
||||
if (!token) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-red-500">缺少管理员凭证</div>
|
||||
<div className={`flex min-h-screen items-center justify-center p-4 ${isDark ? 'bg-slate-950' : 'bg-slate-50'}`}>
|
||||
<div className="text-center text-red-500">
|
||||
<p className="text-lg font-medium">缺少管理员凭证</p>
|
||||
<p className="mt-2 text-sm text-gray-500">请从 Sub2API 平台正确访问管理页面</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -151,22 +163,29 @@ function AdminContent() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto min-h-screen max-w-6xl p-4">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Sub2ApiPay 订单管理</h1>
|
||||
<PayPageLayout
|
||||
isDark={isDark}
|
||||
isEmbedded={isEmbedded}
|
||||
maxWidth="full"
|
||||
title="订单管理"
|
||||
subtitle="查看和管理所有充值订单"
|
||||
actions={
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchOrders}
|
||||
className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100"
|
||||
className={[
|
||||
'inline-flex items-center rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors',
|
||||
isDark ? 'border-slate-600 text-slate-200 hover:bg-slate-800' : 'border-slate-300 text-slate-700 hover:bg-slate-100',
|
||||
].join(' ')}
|
||||
>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
}
|
||||
>
|
||||
{error && (
|
||||
<div className="mb-4 rounded-lg bg-red-50 p-3 text-sm text-red-600">
|
||||
<div className={`mb-4 rounded-lg border p-3 text-sm ${isDark ? 'border-red-800 bg-red-950/50 text-red-400' : 'border-red-200 bg-red-50 text-red-600'}`}>
|
||||
{error}
|
||||
<button onClick={() => setError('')} className="ml-2 text-red-400 hover:text-red-600">
|
||||
<button onClick={() => setError('')} className="ml-2 opacity-60 hover:opacity-100">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
@@ -181,9 +200,12 @@ function AdminContent() {
|
||||
setStatusFilter(s);
|
||||
setPage(1);
|
||||
}}
|
||||
className={`rounded-full px-3 py-1 text-sm transition-colors ${
|
||||
statusFilter === s ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
className={[
|
||||
'rounded-full px-3 py-1 text-sm transition-colors',
|
||||
statusFilter === s
|
||||
? (isDark ? 'bg-indigo-500/30 text-indigo-200 ring-1 ring-indigo-400/40' : 'bg-blue-600 text-white')
|
||||
: (isDark ? 'bg-slate-800 text-slate-400 hover:bg-slate-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'),
|
||||
].join(' ')}
|
||||
>
|
||||
{statusLabels[s]}
|
||||
</button>
|
||||
@@ -191,11 +213,11 @@ function AdminContent() {
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="rounded-xl bg-white shadow-sm">
|
||||
<div className={['rounded-xl border', isDark ? 'border-slate-700 bg-slate-800/70' : 'border-slate-200 bg-white shadow-sm'].join(' ')}>
|
||||
{loading ? (
|
||||
<div className="py-12 text-center text-gray-500">加载中...</div>
|
||||
<div className={`py-12 text-center ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>加载中...</div>
|
||||
) : (
|
||||
<OrderTable orders={orders} onRetry={handleRetry} onCancel={handleCancel} onViewDetail={handleViewDetail} />
|
||||
<OrderTable orders={orders} onRetry={handleRetry} onCancel={handleCancel} onViewDetail={handleViewDetail} dark={isDark} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -207,11 +229,12 @@ function AdminContent() {
|
||||
loading={loading}
|
||||
onPageChange={(p) => setPage(p)}
|
||||
onPageSizeChange={(s) => { setPageSize(s); setPage(1); }}
|
||||
isDark={isDark}
|
||||
/>
|
||||
|
||||
{/* Order Detail */}
|
||||
{detailOrder && <OrderDetail order={detailOrder} onClose={() => setDetailOrder(null)} />}
|
||||
</div>
|
||||
{detailOrder && <OrderDetail order={detailOrder} onClose={() => setDetailOrder(null)} dark={isDark} />}
|
||||
</PayPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
|
||||
import { adminCancelOrder, OrderError } from '@/lib/order/service';
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
if (!verifyAdminToken(request)) return unauthorizedResponse();
|
||||
if (!await verifyAdminToken(request)) return unauthorizedResponse();
|
||||
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
|
||||
import { retryRecharge, OrderError } from '@/lib/order/service';
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
if (!verifyAdminToken(request)) return unauthorizedResponse();
|
||||
if (!await verifyAdminToken(request)) return unauthorizedResponse();
|
||||
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { prisma } from '@/lib/db';
|
||||
import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
if (!verifyAdminToken(request)) return unauthorizedResponse();
|
||||
if (!await verifyAdminToken(request)) return unauthorizedResponse();
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { verifyAdminToken, unauthorizedResponse } from '@/lib/admin-auth';
|
||||
import { Prisma, OrderStatus } from '@prisma/client';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
if (!verifyAdminToken(request)) return unauthorizedResponse();
|
||||
if (!await verifyAdminToken(request)) return unauthorizedResponse();
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const page = Math.max(1, Number(searchParams.get('page') || '1'));
|
||||
@@ -34,6 +34,7 @@ export async function GET(request: NextRequest) {
|
||||
userId: true,
|
||||
userName: true,
|
||||
userEmail: true,
|
||||
userNotes: true,
|
||||
amount: true,
|
||||
status: true,
|
||||
paymentType: true,
|
||||
@@ -42,6 +43,7 @@ export async function GET(request: NextRequest) {
|
||||
completedAt: true,
|
||||
failedReason: true,
|
||||
expiresAt: true,
|
||||
srcHost: true,
|
||||
},
|
||||
}),
|
||||
prisma.order.count({ where }),
|
||||
|
||||
@@ -10,7 +10,7 @@ const refundSchema = z.object({
|
||||
});
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
if (!verifyAdminToken(request)) return unauthorizedResponse();
|
||||
if (!await verifyAdminToken(request)) return unauthorizedResponse();
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
@@ -7,6 +7,8 @@ const createOrderSchema = z.object({
|
||||
user_id: z.number().int().positive(),
|
||||
amount: z.number().positive(),
|
||||
payment_type: z.enum(['alipay', 'wxpay', 'stripe']),
|
||||
src_host: z.string().max(253).optional(),
|
||||
src_url: z.string().max(2048).optional(),
|
||||
});
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
@@ -19,7 +21,7 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: '参数错误', details: parsed.error.flatten().fieldErrors }, { status: 400 });
|
||||
}
|
||||
|
||||
const { user_id, amount, payment_type } = parsed.data;
|
||||
const { user_id, amount, payment_type, src_host, src_url } = parsed.data;
|
||||
|
||||
// Validate amount range
|
||||
if (amount < env.MIN_RECHARGE_AMOUNT || amount > env.MAX_RECHARGE_AMOUNT) {
|
||||
@@ -42,6 +44,8 @@ export async function POST(request: NextRequest) {
|
||||
amount,
|
||||
paymentType: payment_type,
|
||||
clientIp,
|
||||
srcHost: src_host,
|
||||
srcUrl: src_url,
|
||||
});
|
||||
|
||||
// 不向客户端暴露 userName / userBalance 等隐私字段
|
||||
|
||||
@@ -29,6 +29,9 @@ export async function GET(request: NextRequest) {
|
||||
methodLimits,
|
||||
helpImageUrl: env.PAY_HELP_IMAGE_URL ?? null,
|
||||
helpText: env.PAY_HELP_TEXT ?? null,
|
||||
stripePublishableKey: env.ENABLED_PAYMENT_TYPES.includes('stripe') && env.STRIPE_PUBLISHABLE_KEY
|
||||
? env.STRIPE_PUBLISHABLE_KEY
|
||||
: null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@@ -24,6 +24,7 @@ function OrdersContent() {
|
||||
const token = (searchParams.get('token') || '').trim();
|
||||
const theme = searchParams.get('theme') === 'dark' ? 'dark' : 'light';
|
||||
const uiMode = searchParams.get('ui_mode') || 'standalone';
|
||||
const srcHost = searchParams.get('src_host') || '';
|
||||
const isDark = theme === 'dark';
|
||||
|
||||
const [isIframeContext, setIsIframeContext] = useState(true);
|
||||
@@ -178,7 +179,7 @@ function OrdersContent() {
|
||||
actions={
|
||||
<>
|
||||
<button type="button" onClick={() => loadOrders(page, pageSize)} className={btnClass}>刷新</button>
|
||||
<a href={buildScopedUrl('/pay')} className={btnClass}>返回充值</a>
|
||||
{!srcHost && <a href={buildScopedUrl('/pay')} className={btnClass}>返回充值</a>}
|
||||
</>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -13,11 +13,12 @@ import type { MethodLimitInfo } from '@/components/PaymentForm';
|
||||
interface OrderResult {
|
||||
orderId: string;
|
||||
amount: number;
|
||||
payAmount?: number;
|
||||
status: string;
|
||||
paymentType: 'alipay' | 'wxpay' | 'stripe';
|
||||
payUrl?: string | null;
|
||||
qrCode?: string | null;
|
||||
checkoutUrl?: string | null;
|
||||
clientSecret?: string | null;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
@@ -29,6 +30,7 @@ interface AppConfig {
|
||||
methodLimits?: Record<string, MethodLimitInfo>;
|
||||
helpImageUrl?: string | null;
|
||||
helpText?: string | null;
|
||||
stripePublishableKey?: string | null;
|
||||
}
|
||||
|
||||
function PayContent() {
|
||||
@@ -38,6 +40,8 @@ function PayContent() {
|
||||
const theme = searchParams.get('theme') === 'dark' ? 'dark' : 'light';
|
||||
const uiMode = searchParams.get('ui_mode') || 'standalone';
|
||||
const tab = searchParams.get('tab');
|
||||
const srcHost = searchParams.get('src_host') || undefined;
|
||||
const srcUrl = searchParams.get('src_url') || undefined;
|
||||
const isDark = theme === 'dark';
|
||||
|
||||
const [isIframeContext, setIsIframeContext] = useState(true);
|
||||
@@ -56,7 +60,7 @@ function PayContent() {
|
||||
const [activeMobileTab, setActiveMobileTab] = useState<'pay' | 'orders'>('pay');
|
||||
|
||||
const [config, setConfig] = useState<AppConfig>({
|
||||
enabledPaymentTypes: ['alipay', 'wxpay', 'stripe'],
|
||||
enabledPaymentTypes: [],
|
||||
minAmount: 1,
|
||||
maxAmount: 1000,
|
||||
maxDailyAmount: 0,
|
||||
@@ -105,6 +109,7 @@ function PayContent() {
|
||||
methodLimits: cfgData.config.methodLimits,
|
||||
helpImageUrl: cfgData.config.helpImageUrl ?? null,
|
||||
helpText: cfgData.config.helpText ?? null,
|
||||
stripePublishableKey: cfgData.config.stripePublishableKey ?? null,
|
||||
});
|
||||
}
|
||||
} else if (cfgRes.status === 404) {
|
||||
@@ -230,6 +235,8 @@ function PayContent() {
|
||||
user_id: effectiveUserId,
|
||||
amount,
|
||||
payment_type: paymentType,
|
||||
src_host: srcHost,
|
||||
src_url: srcUrl,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -251,11 +258,12 @@ function PayContent() {
|
||||
setOrderResult({
|
||||
orderId: data.orderId,
|
||||
amount: data.amount,
|
||||
payAmount: data.payAmount,
|
||||
status: data.status,
|
||||
paymentType: data.paymentType || paymentType,
|
||||
payUrl: data.payUrl,
|
||||
qrCode: data.qrCode,
|
||||
checkoutUrl: data.checkoutUrl,
|
||||
clientSecret: data.clientSecret,
|
||||
expiresAt: data.expiresAt,
|
||||
});
|
||||
|
||||
@@ -300,7 +308,7 @@ function PayContent() {
|
||||
<PayPageLayout
|
||||
isDark={isDark}
|
||||
isEmbedded={isEmbedded}
|
||||
maxWidth={isMobile ? 'sm' : 'full'}
|
||||
maxWidth={isMobile ? 'sm' : 'lg'}
|
||||
title="Sub2API 余额充值"
|
||||
subtitle="安全支付,自动到账"
|
||||
actions={!isMobile ? (
|
||||
@@ -371,7 +379,16 @@ function PayContent() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'form' && (
|
||||
{step === 'form' && config.enabledPaymentTypes.length === 0 && (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-blue-500 border-t-transparent" />
|
||||
<span className={['ml-3 text-sm', isDark ? 'text-slate-400' : 'text-gray-500'].join(' ')}>
|
||||
加载中...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'form' && config.enabledPaymentTypes.length > 0 && (
|
||||
<>
|
||||
{isMobile ? (
|
||||
activeMobileTab === 'pay' ? (
|
||||
@@ -406,6 +423,7 @@ function PayContent() {
|
||||
userName={userInfo?.username}
|
||||
userBalance={userInfo?.balance}
|
||||
enabledPaymentTypes={config.enabledPaymentTypes}
|
||||
methodLimits={config.methodLimits}
|
||||
minAmount={config.minAmount}
|
||||
maxAmount={config.maxAmount}
|
||||
onSubmit={handleSubmit}
|
||||
@@ -438,9 +456,11 @@ function PayContent() {
|
||||
/>
|
||||
)}
|
||||
{helpText && (
|
||||
<p className={['mt-3 text-sm leading-6', isDark ? 'text-slate-300' : 'text-slate-600'].join(' ')}>
|
||||
{helpText}
|
||||
</p>
|
||||
<div className={['mt-3 space-y-1 text-sm leading-6', isDark ? 'text-slate-300' : 'text-slate-600'].join(' ')}>
|
||||
{helpText.split('\\n').map((line, i) => (
|
||||
<p key={i}>{line}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -456,13 +476,16 @@ function PayContent() {
|
||||
token={token || undefined}
|
||||
payUrl={orderResult.payUrl}
|
||||
qrCode={orderResult.qrCode}
|
||||
checkoutUrl={orderResult.checkoutUrl}
|
||||
clientSecret={orderResult.clientSecret}
|
||||
stripePublishableKey={config.stripePublishableKey}
|
||||
paymentType={orderResult.paymentType}
|
||||
amount={orderResult.amount}
|
||||
payAmount={orderResult.payAmount}
|
||||
expiresAt={orderResult.expiresAt}
|
||||
onStatusChange={handleStatusChange}
|
||||
onBack={handleBack}
|
||||
dark={isDark}
|
||||
isEmbedded={isEmbedded}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -8,9 +8,18 @@ function ResultContent() {
|
||||
// Support both ZPAY (out_trade_no) and Stripe (order_id) callback params
|
||||
const outTradeNo = searchParams.get('out_trade_no') || searchParams.get('order_id');
|
||||
const tradeStatus = searchParams.get('trade_status') || searchParams.get('status');
|
||||
const isPopup = searchParams.get('popup') === '1';
|
||||
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isInPopup, setIsInPopup] = useState(false);
|
||||
|
||||
// Detect if opened as a popup window (from stripe-popup or via popup=1 param)
|
||||
useEffect(() => {
|
||||
if (isPopup || window.opener) {
|
||||
setIsInPopup(true);
|
||||
}
|
||||
}, [isPopup]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!outTradeNo) {
|
||||
@@ -42,6 +51,17 @@ function ResultContent() {
|
||||
};
|
||||
}, [outTradeNo]);
|
||||
|
||||
// Auto-close popup window on success
|
||||
const isSuccess = status === 'COMPLETED' || status === 'PAID' || status === 'RECHARGING';
|
||||
|
||||
useEffect(() => {
|
||||
if (!isInPopup || !isSuccess) return;
|
||||
const timer = setTimeout(() => {
|
||||
window.close();
|
||||
}, 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [isInPopup, isSuccess]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
@@ -50,7 +70,6 @@ function ResultContent() {
|
||||
);
|
||||
}
|
||||
|
||||
const isSuccess = status === 'COMPLETED' || status === 'PAID' || status === 'RECHARGING';
|
||||
const isPending = status === 'PENDING';
|
||||
|
||||
return (
|
||||
@@ -65,12 +84,33 @@ function ResultContent() {
|
||||
<p className="mt-2 text-gray-500">
|
||||
{status === 'COMPLETED' ? '余额已成功到账!' : '支付成功,余额正在充值中...'}
|
||||
</p>
|
||||
{isInPopup && (
|
||||
<div className="mt-4 space-y-2">
|
||||
<p className="text-sm text-gray-400">此窗口将在 3 秒后自动关闭</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.close()}
|
||||
className="text-sm text-blue-600 underline hover:text-blue-700"
|
||||
>
|
||||
立即关闭窗口
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : isPending ? (
|
||||
<>
|
||||
<div className="text-6xl text-yellow-500">⏳</div>
|
||||
<h1 className="mt-4 text-xl font-bold text-yellow-600">等待支付</h1>
|
||||
<p className="mt-2 text-gray-500">订单尚未完成支付</p>
|
||||
{isInPopup && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.close()}
|
||||
className="mt-4 text-sm text-blue-600 underline hover:text-blue-700"
|
||||
>
|
||||
关闭窗口
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -85,6 +125,15 @@ function ResultContent() {
|
||||
? '订单已被取消'
|
||||
: '请联系管理员处理'}
|
||||
</p>
|
||||
{isInPopup && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.close()}
|
||||
className="mt-4 text-sm text-blue-600 underline hover:text-blue-700"
|
||||
>
|
||||
关闭窗口
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
267
src/app/pay/stripe-popup/page.tsx
Normal file
267
src/app/pay/stripe-popup/page.tsx
Normal file
@@ -0,0 +1,267 @@
|
||||
'use client';
|
||||
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState, useCallback, Suspense } from 'react';
|
||||
|
||||
// Methods that can be confirmed directly without Payment Element
|
||||
const DIRECT_CONFIRM_METHODS: Record<string, string> = {
|
||||
alipay: 'confirmAlipayPayment',
|
||||
};
|
||||
|
||||
function StripePopupContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const orderId = searchParams.get('order_id') || '';
|
||||
const clientSecret = searchParams.get('client_secret') || '';
|
||||
const pk = searchParams.get('pk') || '';
|
||||
const amount = parseFloat(searchParams.get('amount') || '0') || 0;
|
||||
const theme = searchParams.get('theme') === 'dark' ? 'dark' : 'light';
|
||||
const method = searchParams.get('method') || '';
|
||||
const isDark = theme === 'dark';
|
||||
const hasMissingParams = !orderId || !clientSecret || !pk;
|
||||
|
||||
const [stripeLoaded, setStripeLoaded] = useState(false);
|
||||
const [stripeSubmitting, setStripeSubmitting] = useState(false);
|
||||
const [stripeError, setStripeError] = useState('');
|
||||
const [stripeSuccess, setStripeSuccess] = useState(false);
|
||||
const [stripeLib, setStripeLib] = useState<{
|
||||
stripe: import('@stripe/stripe-js').Stripe;
|
||||
elements: import('@stripe/stripe-js').StripeElements;
|
||||
} | null>(null);
|
||||
|
||||
const directConfirmMethod = DIRECT_CONFIRM_METHODS[method];
|
||||
|
||||
const buildReturnUrl = useCallback(() => {
|
||||
const returnUrl = new URL(window.location.href);
|
||||
returnUrl.pathname = '/pay/result';
|
||||
returnUrl.search = '';
|
||||
returnUrl.searchParams.set('order_id', orderId);
|
||||
returnUrl.searchParams.set('status', 'success');
|
||||
returnUrl.searchParams.set('popup', '1');
|
||||
return returnUrl.toString();
|
||||
}, [orderId]);
|
||||
|
||||
// Initialize Stripe and auto-confirm for direct methods (e.g. Alipay)
|
||||
useEffect(() => {
|
||||
if (hasMissingParams) return;
|
||||
let cancelled = false;
|
||||
import('@stripe/stripe-js').then(({ loadStripe }) => {
|
||||
loadStripe(pk).then((stripe) => {
|
||||
if (cancelled || !stripe) {
|
||||
if (!cancelled) {
|
||||
setStripeError('支付组件加载失败,请关闭窗口重试');
|
||||
setStripeLoaded(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (directConfirmMethod) {
|
||||
// Direct confirm (e.g. Alipay) — immediately redirect, no Payment Element needed
|
||||
const confirmFn = (stripe as unknown as Record<string, Function>)[directConfirmMethod];
|
||||
if (typeof confirmFn === 'function') {
|
||||
confirmFn.call(stripe, clientSecret, {
|
||||
return_url: buildReturnUrl(),
|
||||
}).then((result: { error?: { message?: string } }) => {
|
||||
if (cancelled) return;
|
||||
if (result.error) {
|
||||
setStripeError(result.error.message || '支付失败,请重试');
|
||||
setStripeLoaded(true);
|
||||
}
|
||||
// If no error, the page has already been redirected
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback: create Elements for Payment Element flow
|
||||
const elements = stripe.elements({
|
||||
clientSecret,
|
||||
appearance: {
|
||||
theme: isDark ? 'night' : 'stripe',
|
||||
variables: { borderRadius: '8px' },
|
||||
},
|
||||
});
|
||||
setStripeLib({ stripe, elements });
|
||||
setStripeLoaded(true);
|
||||
});
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [pk, clientSecret, isDark, directConfirmMethod, hasMissingParams, buildReturnUrl]);
|
||||
|
||||
// Mount Payment Element (only for non-direct methods)
|
||||
const stripeContainerRef = useCallback(
|
||||
(node: HTMLDivElement | null) => {
|
||||
if (!node || !stripeLib) return;
|
||||
const existing = stripeLib.elements.getElement('payment');
|
||||
if (existing) {
|
||||
existing.mount(node);
|
||||
} else {
|
||||
stripeLib.elements.create('payment', { layout: 'tabs' }).mount(node);
|
||||
}
|
||||
},
|
||||
[stripeLib],
|
||||
);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!stripeLib || stripeSubmitting) return;
|
||||
setStripeSubmitting(true);
|
||||
setStripeError('');
|
||||
|
||||
const { stripe, elements } = stripeLib;
|
||||
|
||||
const { error } = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: buildReturnUrl(),
|
||||
},
|
||||
redirect: 'if_required',
|
||||
});
|
||||
|
||||
if (error) {
|
||||
setStripeError(error.message || '支付失败,请重试');
|
||||
setStripeSubmitting(false);
|
||||
} else {
|
||||
setStripeSuccess(true);
|
||||
setStripeSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-close after success
|
||||
useEffect(() => {
|
||||
if (!stripeSuccess) return;
|
||||
const timer = setTimeout(() => {
|
||||
window.close();
|
||||
}, 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [stripeSuccess]);
|
||||
|
||||
// Missing params — show error (after all hooks)
|
||||
if (hasMissingParams) {
|
||||
return (
|
||||
<div className={`flex min-h-screen items-center justify-center p-4 ${isDark ? 'bg-slate-950 text-white' : 'bg-slate-50'}`}>
|
||||
<div className="text-center text-red-500">
|
||||
<p className="text-lg font-medium">参数缺失</p>
|
||||
<p className="mt-2 text-sm text-gray-500">请从支付页面正常打开此窗口</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// For direct confirm methods, show a loading/redirecting state
|
||||
if (directConfirmMethod) {
|
||||
return (
|
||||
<div className={`flex min-h-screen items-center justify-center p-4 ${isDark ? 'bg-slate-950' : 'bg-slate-50'}`}>
|
||||
<div className={`w-full max-w-md space-y-4 rounded-2xl border p-6 ${isDark ? 'border-slate-700 bg-slate-900' : 'border-slate-200 bg-white'} shadow-lg`}>
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-blue-600">{'\u00A5'}{amount.toFixed(2)}</div>
|
||||
<p className={`mt-1 text-sm ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
订单号: {orderId}
|
||||
</p>
|
||||
</div>
|
||||
{stripeError ? (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-600">
|
||||
{stripeError}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.close()}
|
||||
className="w-full text-sm text-blue-600 underline hover:text-blue-700"
|
||||
>
|
||||
关闭窗口
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-[#635bff] border-t-transparent" />
|
||||
<span className={`ml-3 text-sm ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
正在跳转到支付页面...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`flex min-h-screen items-center justify-center p-4 ${isDark ? 'bg-slate-950' : 'bg-slate-50'}`}>
|
||||
<div className={`w-full max-w-md space-y-4 rounded-2xl border p-6 ${isDark ? 'border-slate-700 bg-slate-900' : 'border-slate-200 bg-white'} shadow-lg`}>
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-blue-600">{'\u00A5'}{amount.toFixed(2)}</div>
|
||||
<p className={`mt-1 text-sm ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
订单号: {orderId}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!stripeLoaded ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-[#635bff] border-t-transparent" />
|
||||
<span className={`ml-3 text-sm ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
正在加载支付表单...
|
||||
</span>
|
||||
</div>
|
||||
) : stripeSuccess ? (
|
||||
<div className="py-6 text-center">
|
||||
<div className="text-5xl text-green-600">{'\u2713'}</div>
|
||||
<p className={`mt-3 text-sm ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
支付成功,窗口即将自动关闭...
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.close()}
|
||||
className="mt-4 text-sm text-blue-600 underline hover:text-blue-700"
|
||||
>
|
||||
手动关闭窗口
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{stripeError && (
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-600">
|
||||
{stripeError}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={stripeContainerRef}
|
||||
className={`rounded-lg border p-4 ${isDark ? 'border-slate-700 bg-slate-800' : 'border-gray-200 bg-white'}`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={stripeSubmitting}
|
||||
onClick={handleSubmit}
|
||||
className={[
|
||||
'w-full rounded-lg py-3 font-medium text-white shadow-md transition-colors',
|
||||
stripeSubmitting
|
||||
? 'bg-gray-400 cursor-not-allowed'
|
||||
: 'bg-[#635bff] hover:bg-[#5249d9] active:bg-[#4840c4]',
|
||||
].join(' ')}
|
||||
>
|
||||
{stripeSubmitting ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
处理中...
|
||||
</span>
|
||||
) : (
|
||||
`支付 ¥${amount.toFixed(2)}`
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function StripePopupPage() {
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-gray-500">加载中...</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<StripePopupContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import React from 'react';
|
||||
interface PayPageLayoutProps {
|
||||
isDark: boolean;
|
||||
isEmbedded?: boolean;
|
||||
maxWidth?: 'sm' | 'full';
|
||||
maxWidth?: 'sm' | 'lg' | 'full';
|
||||
title: string;
|
||||
subtitle: string;
|
||||
actions?: React.ReactNode;
|
||||
@@ -19,30 +19,37 @@ export default function PayPageLayout({
|
||||
actions,
|
||||
children,
|
||||
}: PayPageLayoutProps) {
|
||||
const maxWidthClass = maxWidth === 'sm' ? 'max-w-lg' : maxWidth === 'lg' ? 'max-w-6xl' : '';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[
|
||||
'relative min-h-screen w-full overflow-hidden p-3 sm:p-4',
|
||||
'relative w-full overflow-hidden',
|
||||
isEmbedded ? 'p-2' : 'min-h-screen p-3 sm:p-4',
|
||||
isDark ? 'bg-slate-950 text-slate-100' : 'bg-slate-100 text-slate-900',
|
||||
].join(' ')}
|
||||
>
|
||||
<div
|
||||
className={[
|
||||
'pointer-events-none absolute -left-20 -top-20 h-56 w-56 rounded-full blur-3xl',
|
||||
isDark ? 'bg-indigo-500/25' : 'bg-sky-300/35',
|
||||
].join(' ')}
|
||||
/>
|
||||
<div
|
||||
className={[
|
||||
'pointer-events-none absolute -right-24 bottom-0 h-64 w-64 rounded-full blur-3xl',
|
||||
isDark ? 'bg-cyan-400/20' : 'bg-indigo-200/45',
|
||||
].join(' ')}
|
||||
/>
|
||||
{!isEmbedded && (
|
||||
<>
|
||||
<div
|
||||
className={[
|
||||
'pointer-events-none absolute -left-20 -top-20 h-56 w-56 rounded-full blur-3xl',
|
||||
isDark ? 'bg-indigo-500/25' : 'bg-sky-300/35',
|
||||
].join(' ')}
|
||||
/>
|
||||
<div
|
||||
className={[
|
||||
'pointer-events-none absolute -right-24 bottom-0 h-64 w-64 rounded-full blur-3xl',
|
||||
isDark ? 'bg-cyan-400/20' : 'bg-indigo-200/45',
|
||||
].join(' ')}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={[
|
||||
'relative mx-auto w-full rounded-3xl border p-4 sm:p-6',
|
||||
maxWidth === 'sm' ? 'max-w-lg' : 'max-w-6xl',
|
||||
maxWidthClass,
|
||||
isDark
|
||||
? 'border-slate-700/70 bg-slate-900/85 shadow-2xl shadow-black/35'
|
||||
: 'border-slate-200/90 bg-white/95 shadow-2xl shadow-slate-300/45',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { PAYMENT_TYPE_META } from '@/lib/pay-utils';
|
||||
|
||||
export interface MethodLimitInfo {
|
||||
@@ -8,6 +8,8 @@ export interface MethodLimitInfo {
|
||||
remaining: number | null;
|
||||
/** 单笔限额,0 = 使用全局 maxAmount */
|
||||
singleMax?: number;
|
||||
/** 手续费率百分比,0 = 无手续费 */
|
||||
feeRate?: number;
|
||||
}
|
||||
|
||||
interface PaymentFormProps {
|
||||
@@ -23,7 +25,7 @@ interface PaymentFormProps {
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
const QUICK_AMOUNTS = [10, 20, 50, 100, 200, 500];
|
||||
const QUICK_AMOUNTS = [10, 20, 50, 100, 200, 500, 1000, 2000];
|
||||
const AMOUNT_TEXT_PATTERN = /^\d*(\.\d{0,2})?$/;
|
||||
|
||||
function hasValidCentPrecision(num: number): boolean {
|
||||
@@ -46,6 +48,13 @@ export default function PaymentForm({
|
||||
const [paymentType, setPaymentType] = useState(enabledPaymentTypes[0] || 'alipay');
|
||||
const [customAmount, setCustomAmount] = useState('');
|
||||
|
||||
// Reset paymentType when enabledPaymentTypes changes (e.g. after config loads)
|
||||
useEffect(() => {
|
||||
if (!enabledPaymentTypes.includes(paymentType)) {
|
||||
setPaymentType(enabledPaymentTypes[0] || 'stripe');
|
||||
}
|
||||
}, [enabledPaymentTypes, paymentType]);
|
||||
|
||||
const handleQuickAmount = (val: number) => {
|
||||
setAmount(val);
|
||||
setCustomAmount(String(val));
|
||||
@@ -75,6 +84,13 @@ export default function PaymentForm({
|
||||
const isMethodAvailable = !methodLimits || (methodLimits[paymentType]?.available !== false);
|
||||
const methodSingleMax = methodLimits?.[paymentType]?.singleMax;
|
||||
const effectiveMax = (methodSingleMax !== undefined && methodSingleMax > 0) ? methodSingleMax : maxAmount;
|
||||
const feeRate = methodLimits?.[paymentType]?.feeRate ?? 0;
|
||||
const feeAmount = feeRate > 0 && selectedAmount > 0
|
||||
? Math.ceil(selectedAmount * feeRate / 100 * 100) / 100
|
||||
: 0;
|
||||
const payAmount = feeRate > 0 && selectedAmount > 0
|
||||
? Math.round((selectedAmount + feeAmount) * 100) / 100
|
||||
: selectedAmount;
|
||||
const isValid = selectedAmount >= minAmount && selectedAmount <= effectiveMax && hasValidCentPrecision(selectedAmount) && isMethodAvailable;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
@@ -150,7 +166,7 @@ export default function PaymentForm({
|
||||
充值金额
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{QUICK_AMOUNTS.filter((val) => val <= effectiveMax).map((val) => (
|
||||
{QUICK_AMOUNTS.filter((val) => val >= minAmount && val <= effectiveMax).map((val) => (
|
||||
<button
|
||||
key={val}
|
||||
type="button"
|
||||
@@ -213,69 +229,97 @@ export default function PaymentForm({
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Payment Type */}
|
||||
<div>
|
||||
<label className={['mb-2 block text-sm font-medium', dark ? 'text-slate-200' : 'text-gray-700'].join(' ')}>
|
||||
支付方式
|
||||
</label>
|
||||
<div className="flex gap-3">
|
||||
{enabledPaymentTypes.map((type) => {
|
||||
const meta = PAYMENT_TYPE_META[type];
|
||||
const isSelected = paymentType === type;
|
||||
const limitInfo = methodLimits?.[type];
|
||||
const isUnavailable = limitInfo !== undefined && !limitInfo.available;
|
||||
{/* Payment Type — only show when multiple types available */}
|
||||
{enabledPaymentTypes.length > 1 && (
|
||||
<div>
|
||||
<label className={['mb-2 block text-sm font-medium', dark ? 'text-slate-200' : 'text-gray-700'].join(' ')}>
|
||||
支付方式
|
||||
</label>
|
||||
<div className="flex gap-3">
|
||||
{enabledPaymentTypes.map((type) => {
|
||||
const meta = PAYMENT_TYPE_META[type];
|
||||
const isSelected = paymentType === type;
|
||||
const limitInfo = methodLimits?.[type];
|
||||
const isUnavailable = limitInfo !== undefined && !limitInfo.available;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
disabled={isUnavailable}
|
||||
onClick={() => !isUnavailable && setPaymentType(type)}
|
||||
title={isUnavailable ? '今日充值额度已满,请使用其他支付方式' : undefined}
|
||||
className={[
|
||||
'relative flex h-[58px] flex-1 flex-col items-center justify-center rounded-lg border px-3 transition-all',
|
||||
isUnavailable
|
||||
? dark
|
||||
? 'cursor-not-allowed border-slate-700 bg-slate-800/50 opacity-50'
|
||||
: 'cursor-not-allowed border-gray-200 bg-gray-50 opacity-50'
|
||||
: isSelected
|
||||
? `${meta?.selectedBorder || 'border-blue-500'} ${meta?.selectedBg || 'bg-blue-50'} text-slate-900 shadow-sm`
|
||||
: dark
|
||||
? 'border-slate-700 bg-slate-900 text-slate-200 hover:border-slate-500'
|
||||
: 'border-gray-300 bg-white text-slate-700 hover:border-gray-400',
|
||||
].join(' ')}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
{renderPaymentIcon(type)}
|
||||
<span className="flex flex-col items-start leading-none">
|
||||
<span className="text-xl font-semibold tracking-tight">{meta?.label || type}</span>
|
||||
{isUnavailable ? (
|
||||
<span className="text-[10px] tracking-wide text-red-400">今日额度已满</span>
|
||||
) : meta?.sublabel ? (
|
||||
<span
|
||||
className={`text-[10px] tracking-wide ${dark && !isSelected ? 'text-slate-400' : 'text-slate-600'}`}
|
||||
>
|
||||
{meta.sublabel}
|
||||
</span>
|
||||
) : null}
|
||||
return (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
disabled={isUnavailable}
|
||||
onClick={() => !isUnavailable && setPaymentType(type)}
|
||||
title={isUnavailable ? '今日充值额度已满,请使用其他支付方式' : undefined}
|
||||
className={[
|
||||
'relative flex h-[58px] flex-1 flex-col items-center justify-center rounded-lg border px-3 transition-all',
|
||||
isUnavailable
|
||||
? dark
|
||||
? 'cursor-not-allowed border-slate-700 bg-slate-800/50 opacity-50'
|
||||
: 'cursor-not-allowed border-gray-200 bg-gray-50 opacity-50'
|
||||
: isSelected
|
||||
? `${meta?.selectedBorder || 'border-blue-500'} ${meta?.selectedBg || 'bg-blue-50'} text-slate-900 shadow-sm`
|
||||
: dark
|
||||
? 'border-slate-700 bg-slate-900 text-slate-200 hover:border-slate-500'
|
||||
: 'border-gray-300 bg-white text-slate-700 hover:border-gray-400',
|
||||
].join(' ')}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
{renderPaymentIcon(type)}
|
||||
<span className="flex flex-col items-start leading-none">
|
||||
<span className="text-xl font-semibold tracking-tight">{meta?.label || type}</span>
|
||||
{isUnavailable ? (
|
||||
<span className="text-[10px] tracking-wide text-red-400">今日额度已满</span>
|
||||
) : meta?.sublabel ? (
|
||||
<span
|
||||
className={`text-[10px] tracking-wide ${dark && !isSelected ? 'text-slate-400' : 'text-slate-600'}`}
|
||||
>
|
||||
{meta.sublabel}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 当前选中渠道额度不足时的提示 */}
|
||||
{(() => {
|
||||
const limitInfo = methodLimits?.[paymentType];
|
||||
if (!limitInfo || limitInfo.available) return null;
|
||||
return (
|
||||
<p className={['mt-2 text-xs', dark ? 'text-amber-300' : 'text-amber-600'].join(' ')}>
|
||||
所选支付方式今日额度已满,请切换到其他支付方式
|
||||
</p>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
{/* 当前选中渠道额度不足时的提示 */}
|
||||
{(() => {
|
||||
const limitInfo = methodLimits?.[paymentType];
|
||||
if (!limitInfo || limitInfo.available) return null;
|
||||
return (
|
||||
<p className={['mt-2 text-xs', dark ? 'text-amber-300' : 'text-amber-600'].join(' ')}>
|
||||
所选支付方式今日额度已满,请切换到其他支付方式
|
||||
</p>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Fee Detail */}
|
||||
{feeRate > 0 && selectedAmount > 0 && (
|
||||
<div
|
||||
className={[
|
||||
'rounded-xl border px-4 py-3 text-sm',
|
||||
dark ? 'border-slate-700 bg-slate-800/60 text-slate-300' : 'border-slate-200 bg-slate-50 text-slate-600',
|
||||
].join(' ')}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span>充值金额</span>
|
||||
<span>¥{selectedAmount.toFixed(2)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between mt-1">
|
||||
<span>手续费({feeRate}%)</span>
|
||||
<span>¥{feeAmount.toFixed(2)}</span>
|
||||
</div>
|
||||
<div className={[
|
||||
'flex items-center justify-between mt-1.5 pt-1.5 border-t font-medium',
|
||||
dark ? 'border-slate-700 text-slate-100' : 'border-slate-200 text-slate-900',
|
||||
].join(' ')}>
|
||||
<span>实付金额</span>
|
||||
<span>¥{payAmount.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
@@ -291,7 +335,7 @@ export default function PaymentForm({
|
||||
: 'cursor-not-allowed bg-gray-300'
|
||||
}`}
|
||||
>
|
||||
{loading ? '处理中...' : `立即充值 ¥${selectedAmount || 0}`}
|
||||
{loading ? '处理中...' : `立即充值 ¥${(feeRate > 0 && selectedAmount > 0 ? payAmount : selectedAmount || 0).toFixed(2)}`}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState, useCallback } from 'react';
|
||||
import { useEffect, useMemo, useState, useCallback, useRef } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
interface PaymentQRCodeProps {
|
||||
@@ -8,13 +8,16 @@ interface PaymentQRCodeProps {
|
||||
token?: string;
|
||||
payUrl?: string | null;
|
||||
qrCode?: string | null;
|
||||
checkoutUrl?: string | null;
|
||||
clientSecret?: string | null;
|
||||
stripePublishableKey?: string | null;
|
||||
paymentType?: 'alipay' | 'wxpay' | 'stripe';
|
||||
amount: number;
|
||||
payAmount?: number;
|
||||
expiresAt: string;
|
||||
onStatusChange: (status: string) => void;
|
||||
onBack: () => void;
|
||||
dark?: boolean;
|
||||
isEmbedded?: boolean;
|
||||
}
|
||||
|
||||
const TEXT_EXPIRED = '\u8BA2\u5355\u5DF2\u8D85\u65F6';
|
||||
@@ -25,35 +28,44 @@ const TEXT_BACK = '\u8FD4\u56DE';
|
||||
const TEXT_CANCEL_ORDER = '\u53D6\u6D88\u8BA2\u5355';
|
||||
const TERMINAL_STATUSES = new Set(['COMPLETED', 'FAILED', 'CANCELLED', 'EXPIRED', 'REFUNDED', 'REFUND_FAILED']);
|
||||
|
||||
function isSafeCheckoutUrl(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === 'https:' && parsed.hostname.endsWith('.stripe.com');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default function PaymentQRCode({
|
||||
orderId,
|
||||
token,
|
||||
payUrl,
|
||||
qrCode,
|
||||
checkoutUrl,
|
||||
clientSecret,
|
||||
stripePublishableKey,
|
||||
paymentType,
|
||||
amount,
|
||||
payAmount: payAmountProp,
|
||||
expiresAt,
|
||||
onStatusChange,
|
||||
onBack,
|
||||
dark = false,
|
||||
isEmbedded = false,
|
||||
}: PaymentQRCodeProps) {
|
||||
const displayAmount = payAmountProp ?? amount;
|
||||
const hasFeeDiff = payAmountProp !== undefined && payAmountProp !== amount;
|
||||
const [timeLeft, setTimeLeft] = useState('');
|
||||
const [expired, setExpired] = useState(false);
|
||||
const [qrDataUrl, setQrDataUrl] = useState('');
|
||||
const [imageLoading, setImageLoading] = useState(false);
|
||||
const [stripeOpened, setStripeOpened] = useState(false);
|
||||
const [cancelBlocked, setCancelBlocked] = useState(false);
|
||||
|
||||
// Stripe Payment Element state
|
||||
const [stripeLoaded, setStripeLoaded] = useState(false);
|
||||
const [stripeSubmitting, setStripeSubmitting] = useState(false);
|
||||
const [stripeError, setStripeError] = useState('');
|
||||
const [stripeSuccess, setStripeSuccess] = useState(false);
|
||||
const [stripeLib, setStripeLib] = useState<{
|
||||
stripe: import('@stripe/stripe-js').Stripe;
|
||||
elements: import('@stripe/stripe-js').StripeElements;
|
||||
} | null>(null);
|
||||
// Track selected payment method in Payment Element (for embedded popup decision)
|
||||
const [stripePaymentMethod, setStripePaymentMethod] = useState('card');
|
||||
const [popupBlocked, setPopupBlocked] = useState(false);
|
||||
const paymentMethodListenerAdded = useRef(false);
|
||||
|
||||
const qrPayload = useMemo(() => {
|
||||
const value = (qrCode || payUrl || '').trim();
|
||||
return value;
|
||||
@@ -93,6 +105,123 @@ export default function PaymentQRCode({
|
||||
};
|
||||
}, [qrPayload]);
|
||||
|
||||
// Initialize Stripe Payment Element
|
||||
const isStripe = paymentType === 'stripe';
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStripe || !clientSecret || !stripePublishableKey) return;
|
||||
let cancelled = false;
|
||||
|
||||
import('@stripe/stripe-js').then(({ loadStripe }) => {
|
||||
loadStripe(stripePublishableKey).then((stripe) => {
|
||||
if (cancelled) return;
|
||||
if (!stripe) {
|
||||
setStripeError('支付组件加载失败,请刷新页面重试');
|
||||
setStripeLoaded(true);
|
||||
return;
|
||||
}
|
||||
const elements = stripe.elements({
|
||||
clientSecret,
|
||||
appearance: {
|
||||
theme: dark ? 'night' : 'stripe',
|
||||
variables: {
|
||||
borderRadius: '8px',
|
||||
},
|
||||
},
|
||||
});
|
||||
setStripeLib({ stripe, elements });
|
||||
setStripeLoaded(true);
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [isStripe, clientSecret, stripePublishableKey, dark]);
|
||||
|
||||
// Mount Payment Element when container is available
|
||||
const stripeContainerRef = useCallback(
|
||||
(node: HTMLDivElement | null) => {
|
||||
if (!node || !stripeLib) return;
|
||||
let pe = stripeLib.elements.getElement('payment');
|
||||
if (pe) {
|
||||
pe.mount(node);
|
||||
} else {
|
||||
pe = stripeLib.elements.create('payment', { layout: 'tabs' });
|
||||
pe.mount(node);
|
||||
}
|
||||
if (!paymentMethodListenerAdded.current) {
|
||||
paymentMethodListenerAdded.current = true;
|
||||
pe.on('change', (event: { value?: { type?: string } }) => {
|
||||
if (event.value?.type) {
|
||||
setStripePaymentMethod(event.value.type);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
[stripeLib],
|
||||
);
|
||||
|
||||
const handleStripeSubmit = async () => {
|
||||
if (!stripeLib || stripeSubmitting) return;
|
||||
|
||||
// In embedded mode, Alipay redirects to a page with X-Frame-Options that breaks iframe
|
||||
if (isEmbedded && stripePaymentMethod === 'alipay') {
|
||||
handleOpenPopup();
|
||||
return;
|
||||
}
|
||||
|
||||
setStripeSubmitting(true);
|
||||
setStripeError('');
|
||||
|
||||
const { stripe, elements } = stripeLib;
|
||||
const returnUrl = new URL(window.location.href);
|
||||
returnUrl.pathname = '/pay/result';
|
||||
returnUrl.searchParams.set('order_id', orderId);
|
||||
returnUrl.searchParams.set('status', 'success');
|
||||
|
||||
const { error } = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: returnUrl.toString(),
|
||||
},
|
||||
redirect: 'if_required',
|
||||
});
|
||||
|
||||
if (error) {
|
||||
setStripeError(error.message || '支付失败,请重试');
|
||||
setStripeSubmitting(false);
|
||||
} else {
|
||||
// Payment succeeded (or no redirect needed)
|
||||
setStripeSuccess(true);
|
||||
setStripeSubmitting(false);
|
||||
// Polling will pick up the status change
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenPopup = () => {
|
||||
if (!clientSecret || !stripePublishableKey) return;
|
||||
setPopupBlocked(false);
|
||||
const popupUrl = new URL(window.location.href);
|
||||
popupUrl.pathname = '/pay/stripe-popup';
|
||||
popupUrl.search = '';
|
||||
popupUrl.searchParams.set('order_id', orderId);
|
||||
popupUrl.searchParams.set('client_secret', clientSecret);
|
||||
popupUrl.searchParams.set('pk', stripePublishableKey);
|
||||
popupUrl.searchParams.set('amount', String(amount));
|
||||
popupUrl.searchParams.set('theme', dark ? 'dark' : 'light');
|
||||
popupUrl.searchParams.set('method', stripePaymentMethod);
|
||||
|
||||
const popup = window.open(
|
||||
popupUrl.toString(),
|
||||
'stripe_payment',
|
||||
'width=500,height=700,scrollbars=yes',
|
||||
);
|
||||
if (!popup || popup.closed) {
|
||||
setPopupBlocked(true);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const updateTimer = () => {
|
||||
const now = Date.now();
|
||||
@@ -169,7 +298,6 @@ export default function PaymentQRCode({
|
||||
}
|
||||
};
|
||||
|
||||
const isStripe = paymentType === 'stripe';
|
||||
const isWx = paymentType === 'wxpay';
|
||||
const iconSrc = isStripe ? '' : isWx ? '/icons/wxpay.svg' : '/icons/alipay.svg';
|
||||
const channelLabel = isStripe ? 'Stripe' : isWx ? '\u5FAE\u4FE1' : '\u652F\u4ED8\u5B9D';
|
||||
@@ -196,7 +324,12 @@ export default function PaymentQRCode({
|
||||
return (
|
||||
<div className="flex flex-col items-center space-y-4">
|
||||
<div className="text-center">
|
||||
<div className="text-4xl font-bold text-blue-600">{'\u00A5'}{amount.toFixed(2)}</div>
|
||||
<div className="text-4xl font-bold text-blue-600">{'\u00A5'}{displayAmount.toFixed(2)}</div>
|
||||
{hasFeeDiff && (
|
||||
<div className={['mt-1 text-sm', dark ? 'text-slate-400' : 'text-gray-500'].join(' ')}>
|
||||
到账 ¥{amount.toFixed(2)}
|
||||
</div>
|
||||
)}
|
||||
<div className={`mt-1 text-sm ${expired ? 'text-red-500' : dark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
{expired ? TEXT_EXPIRED : `${TEXT_REMAINING}: ${timeLeft}`}
|
||||
</div>
|
||||
@@ -205,48 +338,72 @@ export default function PaymentQRCode({
|
||||
{!expired && (
|
||||
<>
|
||||
{isStripe ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!checkoutUrl || !isSafeCheckoutUrl(checkoutUrl) || stripeOpened}
|
||||
onClick={() => {
|
||||
if (checkoutUrl && isSafeCheckoutUrl(checkoutUrl)) {
|
||||
window.open(checkoutUrl, '_blank', 'noopener,noreferrer');
|
||||
setStripeOpened(true);
|
||||
}
|
||||
}}
|
||||
className={[
|
||||
'inline-flex items-center gap-2 rounded-lg px-8 py-3 font-medium text-white shadow-md transition-colors',
|
||||
!checkoutUrl || !isSafeCheckoutUrl(checkoutUrl) || stripeOpened
|
||||
? 'bg-gray-400 cursor-not-allowed'
|
||||
: 'bg-[#635bff] hover:bg-[#5249d9] active:bg-[#4840c4]',
|
||||
].join(' ')}
|
||||
>
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
|
||||
<line x1="1" y1="10" x2="23" y2="10" />
|
||||
</svg>
|
||||
{stripeOpened ? '\u5DF2\u6253\u5F00\u652F\u4ED8\u9875\u9762' : '\u524D\u5F80 Stripe \u652F\u4ED8'}
|
||||
</button>
|
||||
{stripeOpened && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (checkoutUrl && isSafeCheckoutUrl(checkoutUrl)) {
|
||||
window.open(checkoutUrl, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
}}
|
||||
className={['text-sm underline', dark ? 'text-slate-400 hover:text-slate-300' : 'text-gray-500 hover:text-gray-700'].join(' ')}
|
||||
>
|
||||
{'\u91CD\u65B0\u6253\u5F00\u652F\u4ED8\u9875\u9762'}
|
||||
</button>
|
||||
<div className="w-full max-w-md space-y-4">
|
||||
{!clientSecret || !stripePublishableKey ? (
|
||||
<div className={['rounded-lg border-2 border-dashed p-8 text-center', dark ? 'border-slate-700' : 'border-gray-300'].join(' ')}>
|
||||
<p className={['text-sm', dark ? 'text-slate-400' : 'text-gray-500'].join(' ')}>
|
||||
支付初始化失败,请返回重试
|
||||
</p>
|
||||
</div>
|
||||
) : !stripeLoaded ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-[#635bff] border-t-transparent" />
|
||||
<span className={['ml-3 text-sm', dark ? 'text-slate-400' : 'text-gray-500'].join(' ')}>
|
||||
正在加载支付表单...
|
||||
</span>
|
||||
</div>
|
||||
) : stripeError && !stripeLib ? (
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-600">
|
||||
{stripeError}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
ref={stripeContainerRef}
|
||||
className={['rounded-lg border p-4', dark ? 'border-slate-700 bg-slate-900' : 'border-gray-200 bg-white'].join(' ')}
|
||||
/>
|
||||
{stripeError && (
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-600">
|
||||
{stripeError}
|
||||
</div>
|
||||
)}
|
||||
{stripeSuccess ? (
|
||||
<div className="text-center">
|
||||
<div className="text-4xl text-green-600">{'\u2713'}</div>
|
||||
<p className={['mt-2 text-sm', dark ? 'text-slate-400' : 'text-gray-500'].join(' ')}>
|
||||
支付成功,正在处理订单...
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled={stripeSubmitting}
|
||||
onClick={handleStripeSubmit}
|
||||
className={[
|
||||
'w-full rounded-lg py-3 font-medium text-white shadow-md transition-colors',
|
||||
stripeSubmitting
|
||||
? 'bg-gray-400 cursor-not-allowed'
|
||||
: 'bg-[#635bff] hover:bg-[#5249d9] active:bg-[#4840c4]',
|
||||
].join(' ')}
|
||||
>
|
||||
{stripeSubmitting ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
|
||||
处理中...
|
||||
</span>
|
||||
) : (
|
||||
`支付 ¥${amount.toFixed(2)}`
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
{popupBlocked && (
|
||||
<div className={['rounded-lg border p-3 text-sm', dark ? 'border-amber-700 bg-amber-900/30 text-amber-300' : 'border-amber-200 bg-amber-50 text-amber-700'].join(' ')}>
|
||||
弹出窗口被浏览器拦截,请允许本站弹出窗口后重试
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<p className={['text-center text-sm', dark ? 'text-slate-400' : 'text-gray-500'].join(' ')}>
|
||||
{!checkoutUrl || !isSafeCheckoutUrl(checkoutUrl)
|
||||
? '\u652F\u4ED8\u94FE\u63A5\u521B\u5EFA\u5931\u8D25\uFF0C\u8BF7\u8FD4\u56DE\u91CD\u8BD5'
|
||||
: '\u5728\u65B0\u7A97\u53E3\u5B8C\u6210\u652F\u4ED8\u540E\uFF0C\u6B64\u9875\u9762\u5C06\u81EA\u52A8\u66F4\u65B0'}
|
||||
</p>
|
||||
</>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{qrDataUrl && (
|
||||
|
||||
@@ -31,15 +31,18 @@ interface OrderDetailProps {
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
clientIp: string | null;
|
||||
srcHost: string | null;
|
||||
srcUrl: string | null;
|
||||
paymentSuccess?: boolean;
|
||||
rechargeSuccess?: boolean;
|
||||
rechargeStatus?: string;
|
||||
auditLogs: AuditLog[];
|
||||
};
|
||||
onClose: () => void;
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
export default function OrderDetail({ order, onClose }: OrderDetailProps) {
|
||||
export default function OrderDetail({ order, onClose, dark }: OrderDetailProps) {
|
||||
const fields = [
|
||||
{ label: '订单号', value: order.id },
|
||||
{ label: '用户ID', value: order.userId },
|
||||
@@ -54,6 +57,8 @@ export default function OrderDetail({ order, onClose }: OrderDetailProps) {
|
||||
{ label: '充值码', value: order.rechargeCode },
|
||||
{ label: '支付单号', value: order.paymentTradeNo || '-' },
|
||||
{ label: '客户端IP', value: order.clientIp || '-' },
|
||||
{ label: '来源域名', value: order.srcHost || '-' },
|
||||
{ label: '来源页面', value: order.srcUrl || '-' },
|
||||
{ label: '创建时间', value: new Date(order.createdAt).toLocaleString('zh-CN') },
|
||||
{ label: '过期时间', value: new Date(order.expiresAt).toLocaleString('zh-CN') },
|
||||
{ label: '支付时间', value: order.paidAt ? new Date(order.paidAt).toLocaleString('zh-CN') : '-' },
|
||||
@@ -74,46 +79,46 @@ export default function OrderDetail({ order, onClose }: OrderDetailProps) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={onClose}>
|
||||
<div
|
||||
className="max-h-[80vh] w-full max-w-2xl overflow-y-auto rounded-xl bg-white p-6 shadow-xl"
|
||||
className={`max-h-[80vh] w-full max-w-2xl overflow-y-auto rounded-xl p-6 shadow-xl ${dark ? 'bg-slate-800 text-slate-100' : 'bg-white'}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-lg font-bold">订单详情</h3>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-gray-600">
|
||||
<button onClick={onClose} className={dark ? 'text-slate-400 hover:text-slate-200' : 'text-gray-400 hover:text-gray-600'}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{fields.map(({ label, value }) => (
|
||||
<div key={label} className="rounded-lg bg-gray-50 p-3">
|
||||
<div className="text-xs text-gray-500">{label}</div>
|
||||
<div className="mt-1 break-all text-sm font-medium">{value}</div>
|
||||
<div key={label} className={`rounded-lg p-3 ${dark ? 'bg-slate-700/60' : 'bg-gray-50'}`}>
|
||||
<div className={`text-xs ${dark ? 'text-slate-400' : 'text-gray-500'}`}>{label}</div>
|
||||
<div className={`mt-1 break-all text-sm font-medium ${dark ? 'text-slate-200' : ''}`}>{value}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Audit Logs */}
|
||||
<div className="mt-6">
|
||||
<h4 className="mb-3 font-medium text-gray-900">审计日志</h4>
|
||||
<h4 className={`mb-3 font-medium ${dark ? 'text-slate-100' : 'text-gray-900'}`}>审计日志</h4>
|
||||
<div className="space-y-2">
|
||||
{order.auditLogs.map((log) => (
|
||||
<div key={log.id} className="rounded-lg border border-gray-100 bg-gray-50 p-3">
|
||||
<div key={log.id} className={`rounded-lg border p-3 ${dark ? 'border-slate-600 bg-slate-700/60' : 'border-gray-100 bg-gray-50'}`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">{log.action}</span>
|
||||
<span className="text-xs text-gray-400">{new Date(log.createdAt).toLocaleString('zh-CN')}</span>
|
||||
<span className={`text-xs ${dark ? 'text-slate-500' : 'text-gray-400'}`}>{new Date(log.createdAt).toLocaleString('zh-CN')}</span>
|
||||
</div>
|
||||
{log.detail && <div className="mt-1 break-all text-xs text-gray-500">{log.detail}</div>}
|
||||
{log.operator && <div className="mt-1 text-xs text-gray-400">操作者: {log.operator}</div>}
|
||||
{log.detail && <div className={`mt-1 break-all text-xs ${dark ? 'text-slate-400' : 'text-gray-500'}`}>{log.detail}</div>}
|
||||
{log.operator && <div className={`mt-1 text-xs ${dark ? 'text-slate-500' : 'text-gray-400'}`}>操作者: {log.operator}</div>}
|
||||
</div>
|
||||
))}
|
||||
{order.auditLogs.length === 0 && <div className="text-center text-sm text-gray-400">暂无日志</div>}
|
||||
{order.auditLogs.length === 0 && <div className={`text-center text-sm ${dark ? 'text-slate-500' : 'text-gray-400'}`}>暂无日志</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="mt-6 w-full rounded-lg border border-gray-300 py-2 text-sm text-gray-600 hover:bg-gray-50"
|
||||
className={`mt-6 w-full rounded-lg border py-2 text-sm ${dark ? 'border-slate-600 text-slate-300 hover:bg-slate-700' : 'border-gray-300 text-gray-600 hover:bg-gray-50'}`}
|
||||
>
|
||||
关闭
|
||||
</button>
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
interface Order {
|
||||
id: string;
|
||||
userId: number;
|
||||
userName: string | null;
|
||||
userEmail: string | null;
|
||||
userNotes: string | null;
|
||||
amount: number;
|
||||
status: string;
|
||||
paymentType: string;
|
||||
@@ -15,6 +14,7 @@ interface Order {
|
||||
completedAt: string | null;
|
||||
failedReason: string | null;
|
||||
expiresAt: string;
|
||||
srcHost: string | null;
|
||||
rechargeRetryable?: boolean;
|
||||
}
|
||||
|
||||
@@ -23,63 +23,75 @@ interface OrderTableProps {
|
||||
onRetry: (orderId: string) => void;
|
||||
onCancel: (orderId: string) => void;
|
||||
onViewDetail: (orderId: string) => void;
|
||||
dark?: boolean;
|
||||
}
|
||||
|
||||
const STATUS_LABELS: Record<string, { label: string; className: string }> = {
|
||||
PENDING: { label: '待支付', className: 'bg-yellow-100 text-yellow-800' },
|
||||
PAID: { label: '已支付', className: 'bg-blue-100 text-blue-800' },
|
||||
RECHARGING: { label: '充值中', className: 'bg-blue-100 text-blue-800' },
|
||||
COMPLETED: { label: '已完成', className: 'bg-green-100 text-green-800' },
|
||||
EXPIRED: { label: '已超时', className: 'bg-gray-100 text-gray-800' },
|
||||
CANCELLED: { label: '已取消', className: 'bg-gray-100 text-gray-800' },
|
||||
FAILED: { label: '充值失败', className: 'bg-red-100 text-red-800' },
|
||||
REFUNDING: { label: '退款中', className: 'bg-orange-100 text-orange-800' },
|
||||
REFUNDED: { label: '已退款', className: 'bg-purple-100 text-purple-800' },
|
||||
REFUND_FAILED: { label: '退款失败', className: 'bg-red-100 text-red-800' },
|
||||
const STATUS_LABELS: Record<string, { label: string; light: string; dark: string }> = {
|
||||
PENDING: { label: '待支付', light: 'bg-yellow-100 text-yellow-800', dark: 'bg-yellow-500/20 text-yellow-300' },
|
||||
PAID: { label: '已支付', light: 'bg-blue-100 text-blue-800', dark: 'bg-blue-500/20 text-blue-300' },
|
||||
RECHARGING: { label: '充值中', light: 'bg-blue-100 text-blue-800', dark: 'bg-blue-500/20 text-blue-300' },
|
||||
COMPLETED: { label: '已完成', light: 'bg-green-100 text-green-800', dark: 'bg-green-500/20 text-green-300' },
|
||||
EXPIRED: { label: '已超时', light: 'bg-gray-100 text-gray-800', dark: 'bg-slate-600/30 text-slate-400' },
|
||||
CANCELLED: { label: '已取消', light: 'bg-gray-100 text-gray-800', dark: 'bg-slate-600/30 text-slate-400' },
|
||||
FAILED: { label: '充值失败', light: 'bg-red-100 text-red-800', dark: 'bg-red-500/20 text-red-300' },
|
||||
REFUNDING: { label: '退款中', light: 'bg-orange-100 text-orange-800', dark: 'bg-orange-500/20 text-orange-300' },
|
||||
REFUNDED: { label: '已退款', light: 'bg-purple-100 text-purple-800', dark: 'bg-purple-500/20 text-purple-300' },
|
||||
REFUND_FAILED: { label: '退款失败', light: 'bg-red-100 text-red-800', dark: 'bg-red-500/20 text-red-300' },
|
||||
};
|
||||
|
||||
export default function OrderTable({ orders, onRetry, onCancel, onViewDetail }: OrderTableProps) {
|
||||
export default function OrderTable({ orders, onRetry, onCancel, onViewDetail, dark }: OrderTableProps) {
|
||||
const thCls = `px-4 py-3 text-left text-xs font-medium uppercase ${dark ? 'text-slate-400' : 'text-gray-500'}`;
|
||||
const tdMuted = `whitespace-nowrap px-4 py-3 text-sm ${dark ? 'text-slate-400' : 'text-gray-500'}`;
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<table className={`min-w-full divide-y ${dark ? 'divide-slate-700' : 'divide-gray-200'}`}>
|
||||
<thead className={dark ? 'bg-slate-800/50' : 'bg-gray-50'}>
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">订单号</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">用户</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">金额</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">状态</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">支付方式</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">创建时间</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">操作</th>
|
||||
<th className={thCls}>订单号</th>
|
||||
<th className={thCls}>用户名</th>
|
||||
<th className={thCls}>邮箱</th>
|
||||
<th className={thCls}>备注</th>
|
||||
<th className={thCls}>金额</th>
|
||||
<th className={thCls}>状态</th>
|
||||
<th className={thCls}>支付方式</th>
|
||||
<th className={thCls}>来源</th>
|
||||
<th className={thCls}>创建时间</th>
|
||||
<th className={thCls}>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 bg-white">
|
||||
<tbody className={`divide-y ${dark ? 'divide-slate-700/60' : 'divide-gray-200 bg-white'}`}>
|
||||
{orders.map((order) => {
|
||||
const statusInfo = STATUS_LABELS[order.status] || {
|
||||
label: order.status,
|
||||
className: 'bg-gray-100 text-gray-800',
|
||||
light: 'bg-gray-100 text-gray-800',
|
||||
dark: 'bg-slate-600/30 text-slate-400',
|
||||
};
|
||||
return (
|
||||
<tr key={order.id} className="hover:bg-gray-50">
|
||||
<tr key={order.id} className={dark ? 'hover:bg-slate-700/40' : 'hover:bg-gray-50'}>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm">
|
||||
<button onClick={() => onViewDetail(order.id)} className="text-blue-600 hover:underline">
|
||||
<button onClick={() => onViewDetail(order.id)} className={dark ? 'text-indigo-400 hover:underline' : 'text-blue-600 hover:underline'}>
|
||||
{order.id.slice(0, 12)}...
|
||||
</button>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm">
|
||||
<div>{order.userName || '-'}</div>
|
||||
<div className="text-xs text-gray-400">{order.userEmail || `ID: ${order.userId}`}</div>
|
||||
<td className={`whitespace-nowrap px-4 py-3 text-sm ${dark ? 'text-slate-200' : ''}`}>
|
||||
{order.userName || `#${order.userId}`}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm font-medium">¥{order.amount.toFixed(2)}</td>
|
||||
<td className={tdMuted}>{order.userEmail || '-'}</td>
|
||||
<td className={tdMuted}>{order.userNotes || '-'}</td>
|
||||
<td className={`whitespace-nowrap px-4 py-3 text-sm font-medium ${dark ? 'text-slate-200' : ''}`}>¥{order.amount.toFixed(2)}</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm">
|
||||
<span className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${statusInfo.className}`}>
|
||||
<span className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${dark ? statusInfo.dark : statusInfo.light}`}>
|
||||
{statusInfo.label}
|
||||
</span>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm text-gray-500">
|
||||
<td className={tdMuted}>
|
||||
{order.paymentType === 'alipay' ? '支付宝' : '微信支付'}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm text-gray-500">
|
||||
<td className={tdMuted}>
|
||||
{order.srcHost || '-'}
|
||||
</td>
|
||||
<td className={tdMuted}>
|
||||
{new Date(order.createdAt).toLocaleString('zh-CN')}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm">
|
||||
@@ -87,7 +99,7 @@ export default function OrderTable({ orders, onRetry, onCancel, onViewDetail }:
|
||||
{order.rechargeRetryable && (
|
||||
<button
|
||||
onClick={() => onRetry(order.id)}
|
||||
className="rounded bg-blue-100 px-2 py-1 text-xs text-blue-700 hover:bg-blue-200"
|
||||
className={`rounded px-2 py-1 text-xs ${dark ? 'bg-blue-500/20 text-blue-300 hover:bg-blue-500/30' : 'bg-blue-100 text-blue-700 hover:bg-blue-200'}`}
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
@@ -95,7 +107,7 @@ export default function OrderTable({ orders, onRetry, onCancel, onViewDetail }:
|
||||
{order.status === 'PENDING' && (
|
||||
<button
|
||||
onClick={() => onCancel(order.id)}
|
||||
className="rounded bg-red-100 px-2 py-1 text-xs text-red-700 hover:bg-red-200"
|
||||
className={`rounded px-2 py-1 text-xs ${dark ? 'bg-red-500/20 text-red-300 hover:bg-red-500/30' : 'bg-red-100 text-red-700 hover:bg-red-200'}`}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
@@ -107,7 +119,7 @@ export default function OrderTable({ orders, onRetry, onCancel, onViewDetail }:
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{orders.length === 0 && <div className="py-12 text-center text-gray-500">暂无订单</div>}
|
||||
{orders.length === 0 && <div className={`py-12 text-center ${dark ? 'text-slate-500' : 'text-gray-500'}`}>暂无订单</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,10 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getEnv } from '@/lib/config';
|
||||
import crypto from 'crypto';
|
||||
|
||||
export function verifyAdminToken(request: NextRequest): boolean {
|
||||
const token = request.nextUrl.searchParams.get('token');
|
||||
if (!token) return false;
|
||||
|
||||
function isLocalAdminToken(token: string): boolean {
|
||||
const env = getEnv();
|
||||
const expected = Buffer.from(env.ADMIN_TOKEN);
|
||||
const received = Buffer.from(token);
|
||||
@@ -14,6 +11,35 @@ export function verifyAdminToken(request: NextRequest): boolean {
|
||||
return crypto.timingSafeEqual(expected, received);
|
||||
}
|
||||
|
||||
async function isSub2ApiAdmin(token: string): Promise<boolean> {
|
||||
try {
|
||||
const env = getEnv();
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||
const response = await fetch(`${env.SUB2API_BASE_URL}/api/v1/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timeout);
|
||||
if (!response.ok) return false;
|
||||
const data = await response.json();
|
||||
return data.data?.role === 'admin';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyAdminToken(request: NextRequest): Promise<boolean> {
|
||||
const token = request.nextUrl.searchParams.get('token');
|
||||
if (!token) return false;
|
||||
|
||||
// 1. 本地 admin token
|
||||
if (isLocalAdminToken(token)) return true;
|
||||
|
||||
// 2. Sub2API 管理员 token
|
||||
return isSub2ApiAdmin(token);
|
||||
}
|
||||
|
||||
export function unauthorizedResponse() {
|
||||
return NextResponse.json({ error: '未授权' }, { status: 401 });
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { getEnv } from '@/lib/config';
|
||||
|
||||
export class EasyPayProvider implements PaymentProvider {
|
||||
readonly name = 'easy-pay';
|
||||
readonly providerKey = 'easypay';
|
||||
readonly supportedTypes: PaymentType[] = ['alipay', 'wxpay'];
|
||||
readonly defaultLimits = {
|
||||
alipay: { singleMax: 1000, dailyMax: 10000 },
|
||||
|
||||
38
src/lib/order/fee.ts
Normal file
38
src/lib/order/fee.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { initPaymentProviders, paymentRegistry } from '@/lib/payment';
|
||||
|
||||
/**
|
||||
* 获取指定支付渠道的手续费率(百分比)。
|
||||
* 优先级:FEE_RATE_{TYPE} > FEE_RATE_PROVIDER_{KEY} > 0
|
||||
*/
|
||||
export function getMethodFeeRate(paymentType: string): number {
|
||||
// 渠道级别:FEE_RATE_ALIPAY / FEE_RATE_WXPAY / FEE_RATE_STRIPE
|
||||
const methodRaw = process.env[`FEE_RATE_${paymentType.toUpperCase()}`];
|
||||
if (methodRaw !== undefined && methodRaw !== '') {
|
||||
const num = Number(methodRaw);
|
||||
if (Number.isFinite(num) && num >= 0) return num;
|
||||
}
|
||||
|
||||
// 提供商级别:FEE_RATE_PROVIDER_EASYPAY / FEE_RATE_PROVIDER_STRIPE
|
||||
initPaymentProviders();
|
||||
const providerKey = paymentRegistry.getProviderKey(paymentType);
|
||||
if (providerKey) {
|
||||
const providerRaw = process.env[`FEE_RATE_PROVIDER_${providerKey.toUpperCase()}`];
|
||||
if (providerRaw !== undefined && providerRaw !== '') {
|
||||
const num = Number(providerRaw);
|
||||
if (Number.isFinite(num) && num >= 0) return num;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据到账金额和手续费率计算实付金额。
|
||||
* feeAmount = ceil(rechargeAmount * feeRate / 100 * 100) / 100 (进一制到分)
|
||||
* payAmount = rechargeAmount + feeAmount
|
||||
*/
|
||||
export function calculatePayAmount(rechargeAmount: number, feeRate: number): number {
|
||||
if (feeRate <= 0) return rechargeAmount;
|
||||
const feeAmount = Math.ceil(rechargeAmount * feeRate / 100 * 100) / 100;
|
||||
return Math.round((rechargeAmount + feeAmount) * 100) / 100;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { prisma } from '@/lib/db';
|
||||
import { getEnv } from '@/lib/config';
|
||||
import { initPaymentProviders, paymentRegistry } from '@/lib/payment';
|
||||
import { getMethodFeeRate } from './fee';
|
||||
|
||||
/**
|
||||
* 获取指定支付渠道的每日全平台限额(0 = 不限制)。
|
||||
@@ -55,6 +56,8 @@ export interface MethodLimitStatus {
|
||||
available: boolean;
|
||||
/** 单笔限额,0 = 使用全局配置 MAX_RECHARGE_AMOUNT */
|
||||
singleMax: number;
|
||||
/** 手续费率百分比,0 = 无手续费 */
|
||||
feeRate: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,6 +88,7 @@ export async function queryMethodLimits(
|
||||
for (const type of paymentTypes) {
|
||||
const dailyLimit = getMethodDailyLimit(type);
|
||||
const singleMax = getMethodSingleLimit(type);
|
||||
const feeRate = getMethodFeeRate(type);
|
||||
const used = usageMap[type] ?? 0;
|
||||
const remaining = dailyLimit > 0 ? Math.max(0, dailyLimit - used) : null;
|
||||
result[type] = {
|
||||
@@ -93,6 +97,7 @@ export async function queryMethodLimits(
|
||||
remaining,
|
||||
available: dailyLimit === 0 || used < dailyLimit,
|
||||
singleMax,
|
||||
feeRate,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { prisma } from '@/lib/db';
|
||||
import { getEnv } from '@/lib/config';
|
||||
import { generateRechargeCode } from './code-gen';
|
||||
import { getMethodDailyLimit } from './limits';
|
||||
import { getMethodFeeRate, calculatePayAmount } from './fee';
|
||||
import { initPaymentProviders, paymentRegistry } from '@/lib/payment';
|
||||
import type { PaymentType, PaymentNotification } from '@/lib/payment';
|
||||
import { getUser, createAndRedeem, subtractBalance } from '@/lib/sub2api/client';
|
||||
@@ -15,18 +16,22 @@ export interface CreateOrderInput {
|
||||
amount: number;
|
||||
paymentType: PaymentType;
|
||||
clientIp: string;
|
||||
srcHost?: string;
|
||||
srcUrl?: string;
|
||||
}
|
||||
|
||||
export interface CreateOrderResult {
|
||||
orderId: string;
|
||||
amount: number;
|
||||
payAmount: number;
|
||||
feeRate: number;
|
||||
status: string;
|
||||
paymentType: PaymentType;
|
||||
userName: string;
|
||||
userBalance: number;
|
||||
payUrl?: string | null;
|
||||
qrCode?: string | null;
|
||||
checkoutUrl?: string | null;
|
||||
clientSecret?: string | null;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
@@ -94,18 +99,26 @@ export async function createOrder(input: CreateOrderInput): Promise<CreateOrderR
|
||||
}
|
||||
}
|
||||
|
||||
const feeRate = getMethodFeeRate(input.paymentType);
|
||||
const payAmount = calculatePayAmount(input.amount, feeRate);
|
||||
|
||||
const expiresAt = new Date(Date.now() + env.ORDER_TIMEOUT_MINUTES * 60 * 1000);
|
||||
const order = await prisma.order.create({
|
||||
data: {
|
||||
userId: input.userId,
|
||||
userEmail: user.email,
|
||||
userName: user.username,
|
||||
userNotes: user.notes || null,
|
||||
amount: new Prisma.Decimal(input.amount.toFixed(2)),
|
||||
payAmount: new Prisma.Decimal(payAmount.toFixed(2)),
|
||||
feeRate: feeRate > 0 ? new Prisma.Decimal(feeRate.toFixed(2)) : null,
|
||||
rechargeCode: '',
|
||||
status: 'PENDING',
|
||||
paymentType: input.paymentType,
|
||||
expiresAt,
|
||||
clientIp: input.clientIp,
|
||||
srcHost: input.srcHost || null,
|
||||
srcUrl: input.srcUrl || null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -120,9 +133,9 @@ export async function createOrder(input: CreateOrderInput): Promise<CreateOrderR
|
||||
const provider = paymentRegistry.getProvider(input.paymentType);
|
||||
const paymentResult = await provider.createPayment({
|
||||
orderId: order.id,
|
||||
amount: input.amount,
|
||||
amount: payAmount,
|
||||
paymentType: input.paymentType,
|
||||
subject: `${env.PRODUCT_NAME} ${input.amount.toFixed(2)} CNY`,
|
||||
subject: `${env.PRODUCT_NAME} ${payAmount.toFixed(2)} CNY`,
|
||||
notifyUrl: env.EASY_PAY_NOTIFY_URL || '',
|
||||
returnUrl: env.EASY_PAY_RETURN_URL || '',
|
||||
clientIp: input.clientIp,
|
||||
@@ -149,13 +162,15 @@ export async function createOrder(input: CreateOrderInput): Promise<CreateOrderR
|
||||
return {
|
||||
orderId: order.id,
|
||||
amount: input.amount,
|
||||
payAmount,
|
||||
feeRate,
|
||||
status: 'PENDING',
|
||||
paymentType: input.paymentType,
|
||||
userName: user.username,
|
||||
userBalance: user.balance,
|
||||
payUrl: paymentResult.payUrl,
|
||||
qrCode: paymentResult.qrCode,
|
||||
checkoutUrl: paymentResult.checkoutUrl,
|
||||
clientSecret: paymentResult.clientSecret,
|
||||
expiresAt,
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -166,6 +181,7 @@ export async function createOrder(input: CreateOrderInput): Promise<CreateOrderR
|
||||
|
||||
// 支付网关配置缺失或调用失败,转成友好错误
|
||||
const msg = error instanceof Error ? error.message : String(error);
|
||||
console.error(`Payment gateway error (${input.paymentType}):`, error);
|
||||
if (msg.includes('environment variables') || msg.includes('not configured') || msg.includes('not found')) {
|
||||
throw new OrderError('PAYMENT_GATEWAY_ERROR', `支付渠道(${input.paymentType})暂未配置,请联系管理员`, 503);
|
||||
}
|
||||
@@ -308,10 +324,11 @@ export async function confirmPayment(input: {
|
||||
console.error(`${input.providerName} notify: non-positive amount:`, input.paidAmount);
|
||||
return false;
|
||||
}
|
||||
if (!paidAmount.equals(order.amount)) {
|
||||
const expectedAmount = order.payAmount ?? order.amount;
|
||||
if (!paidAmount.equals(expectedAmount)) {
|
||||
console.warn(
|
||||
`${input.providerName} notify: amount changed, use paid amount`,
|
||||
order.amount.toString(),
|
||||
expectedAmount.toString(),
|
||||
paidAmount.toString(),
|
||||
);
|
||||
}
|
||||
@@ -546,15 +563,16 @@ export async function processRefund(input: RefundInput): Promise<RefundResult> {
|
||||
throw new OrderError('INVALID_STATUS', 'Only completed orders can be refunded', 400);
|
||||
}
|
||||
|
||||
const amount = Number(order.amount);
|
||||
const rechargeAmount = Number(order.amount);
|
||||
const refundAmount = Number(order.payAmount ?? order.amount);
|
||||
|
||||
if (!input.force) {
|
||||
try {
|
||||
const user = await getUser(order.userId);
|
||||
if (user.balance < amount) {
|
||||
if (user.balance < rechargeAmount) {
|
||||
return {
|
||||
success: false,
|
||||
warning: `User balance ${user.balance} is lower than refund ${amount}`,
|
||||
warning: `User balance ${user.balance} is lower than refund ${rechargeAmount}`,
|
||||
requireForce: true,
|
||||
};
|
||||
}
|
||||
@@ -582,18 +600,18 @@ export async function processRefund(input: RefundInput): Promise<RefundResult> {
|
||||
await provider.refund({
|
||||
tradeNo: order.paymentTradeNo,
|
||||
orderId: order.id,
|
||||
amount,
|
||||
amount: refundAmount,
|
||||
reason: input.reason,
|
||||
});
|
||||
}
|
||||
|
||||
await subtractBalance(order.userId, amount, `sub2apipay refund order:${order.id}`, `sub2apipay:refund:${order.id}`);
|
||||
await subtractBalance(order.userId, rechargeAmount, `sub2apipay refund order:${order.id}`, `sub2apipay:refund:${order.id}`);
|
||||
|
||||
await prisma.order.update({
|
||||
where: { id: input.orderId },
|
||||
data: {
|
||||
status: 'REFUNDED',
|
||||
refundAmount: new Prisma.Decimal(amount.toFixed(2)),
|
||||
refundAmount: new Prisma.Decimal(refundAmount.toFixed(2)),
|
||||
refundReason: input.reason || null,
|
||||
refundAt: new Date(),
|
||||
forceRefund: input.force || false,
|
||||
@@ -604,7 +622,7 @@ export async function processRefund(input: RefundInput): Promise<RefundResult> {
|
||||
data: {
|
||||
orderId: input.orderId,
|
||||
action: 'REFUND_SUCCESS',
|
||||
detail: JSON.stringify({ amount, reason: input.reason, force: input.force }),
|
||||
detail: JSON.stringify({ rechargeAmount, refundAmount, reason: input.reason, force: input.force }),
|
||||
operator: 'admin',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { paymentRegistry } from './registry';
|
||||
import type { PaymentType } from './types';
|
||||
import { EasyPayProvider } from '@/lib/easy-pay/provider';
|
||||
import { StripeProvider } from '@/lib/stripe/provider';
|
||||
import { getEnv } from '@/lib/config';
|
||||
@@ -37,5 +38,14 @@ export function initPaymentProviders(): void {
|
||||
paymentRegistry.register(new StripeProvider());
|
||||
}
|
||||
|
||||
// 校验 ENABLED_PAYMENT_TYPES 的每个渠道都有对应 provider 已注册
|
||||
const unsupported = env.ENABLED_PAYMENT_TYPES.filter((t) => !paymentRegistry.hasProvider(t as PaymentType));
|
||||
if (unsupported.length > 0) {
|
||||
throw new Error(
|
||||
`ENABLED_PAYMENT_TYPES 含 [${unsupported.join(', ')}],但没有对应的 PAYMENT_PROVIDERS 注册。` +
|
||||
`请检查 PAYMENT_PROVIDERS 配置`,
|
||||
);
|
||||
}
|
||||
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
@@ -30,6 +30,12 @@ export class PaymentProviderRegistry {
|
||||
const provider = this.providers.get(type as PaymentType);
|
||||
return provider?.defaultLimits?.[type];
|
||||
}
|
||||
|
||||
/** 获取指定渠道对应的提供商 key(如 'easypay'、'stripe') */
|
||||
getProviderKey(type: string): string | undefined {
|
||||
const provider = this.providers.get(type as PaymentType);
|
||||
return provider?.providerKey;
|
||||
}
|
||||
}
|
||||
|
||||
export const paymentRegistry = new PaymentProviderRegistry();
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface CreatePaymentResponse {
|
||||
tradeNo: string; // third-party transaction ID
|
||||
payUrl?: string; // H5 payment URL (alipay/wxpay)
|
||||
qrCode?: string; // QR code content
|
||||
checkoutUrl?: string; // Stripe Checkout URL
|
||||
clientSecret?: string; // Stripe PaymentIntent client secret (for embedded Payment Element)
|
||||
}
|
||||
|
||||
/** Response from querying an order's payment status */
|
||||
@@ -62,6 +62,7 @@ export interface MethodDefaultLimits {
|
||||
/** Common interface that all payment providers must implement */
|
||||
export interface PaymentProvider {
|
||||
readonly name: string;
|
||||
readonly providerKey: string;
|
||||
readonly supportedTypes: PaymentType[];
|
||||
/** 各渠道默认限额,key 为 PaymentType(如 'alipay'),可被环境变量覆盖 */
|
||||
readonly defaultLimits?: Record<string, MethodDefaultLimits>;
|
||||
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
|
||||
export class StripeProvider implements PaymentProvider {
|
||||
readonly name = 'stripe';
|
||||
readonly providerKey = 'stripe';
|
||||
readonly supportedTypes: PaymentType[] = ['stripe'];
|
||||
readonly defaultLimits = {
|
||||
stripe: { singleMax: 0, dailyMax: 0 }, // 0 = unlimited
|
||||
@@ -31,50 +32,38 @@ export class StripeProvider implements PaymentProvider {
|
||||
|
||||
async createPayment(request: CreatePaymentRequest): Promise<CreatePaymentResponse> {
|
||||
const stripe = this.getClient();
|
||||
const env = getEnv();
|
||||
|
||||
const timeoutMinutes = Math.max(30, env.ORDER_TIMEOUT_MINUTES); // Stripe minimum is 30 minutes
|
||||
const amountInCents = Math.round(new Prisma.Decimal(request.amount).mul(100).toNumber());
|
||||
|
||||
const session = await stripe.checkout.sessions.create(
|
||||
const pi = await stripe.paymentIntents.create(
|
||||
{
|
||||
mode: 'payment',
|
||||
payment_method_types: ['card'],
|
||||
line_items: [
|
||||
{
|
||||
price_data: {
|
||||
currency: 'cny',
|
||||
product_data: { name: request.subject },
|
||||
unit_amount: Math.round(new Prisma.Decimal(request.amount).mul(100).toNumber()),
|
||||
},
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
amount: amountInCents,
|
||||
currency: 'cny',
|
||||
automatic_payment_methods: { enabled: true },
|
||||
metadata: { orderId: request.orderId },
|
||||
expires_at: Math.floor(Date.now() / 1000) + timeoutMinutes * 60,
|
||||
success_url: `${env.NEXT_PUBLIC_APP_URL}/pay/result?order_id=${request.orderId}&status=success`,
|
||||
cancel_url: `${env.NEXT_PUBLIC_APP_URL}/pay/result?order_id=${request.orderId}&status=cancelled`,
|
||||
description: request.subject,
|
||||
},
|
||||
{ idempotencyKey: `checkout-${request.orderId}` },
|
||||
{ idempotencyKey: `pi-${request.orderId}` },
|
||||
);
|
||||
|
||||
return {
|
||||
tradeNo: session.id,
|
||||
checkoutUrl: session.url || undefined,
|
||||
tradeNo: pi.id,
|
||||
clientSecret: pi.client_secret || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async queryOrder(tradeNo: string): Promise<QueryOrderResponse> {
|
||||
const stripe = this.getClient();
|
||||
const session = await stripe.checkout.sessions.retrieve(tradeNo);
|
||||
const pi = await stripe.paymentIntents.retrieve(tradeNo);
|
||||
|
||||
let status: QueryOrderResponse['status'] = 'pending';
|
||||
if (session.payment_status === 'paid') status = 'paid';
|
||||
else if (session.status === 'expired') status = 'failed';
|
||||
if (pi.status === 'succeeded') status = 'paid';
|
||||
else if (pi.status === 'canceled') status = 'failed';
|
||||
|
||||
return {
|
||||
tradeNo: session.id,
|
||||
tradeNo: pi.id,
|
||||
status,
|
||||
amount: new Prisma.Decimal(session.amount_total || 0).div(100).toNumber(),
|
||||
amount: new Prisma.Decimal(pi.amount).div(100).toNumber(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -90,23 +79,23 @@ export class StripeProvider implements PaymentProvider {
|
||||
env.STRIPE_WEBHOOK_SECRET,
|
||||
);
|
||||
|
||||
if (event.type === 'checkout.session.completed' || event.type === 'checkout.session.async_payment_succeeded') {
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
if (event.type === 'payment_intent.succeeded') {
|
||||
const pi = event.data.object as Stripe.PaymentIntent;
|
||||
return {
|
||||
tradeNo: session.id,
|
||||
orderId: session.metadata?.orderId || '',
|
||||
amount: new Prisma.Decimal(session.amount_total || 0).div(100).toNumber(),
|
||||
status: session.payment_status === 'paid' ? 'success' : 'failed',
|
||||
tradeNo: pi.id,
|
||||
orderId: pi.metadata?.orderId || '',
|
||||
amount: new Prisma.Decimal(pi.amount).div(100).toNumber(),
|
||||
status: 'success',
|
||||
rawData: event,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === 'checkout.session.async_payment_failed') {
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
if (event.type === 'payment_intent.payment_failed') {
|
||||
const pi = event.data.object as Stripe.PaymentIntent;
|
||||
return {
|
||||
tradeNo: session.id,
|
||||
orderId: session.metadata?.orderId || '',
|
||||
amount: new Prisma.Decimal(session.amount_total || 0).div(100).toNumber(),
|
||||
tradeNo: pi.id,
|
||||
orderId: pi.metadata?.orderId || '',
|
||||
amount: new Prisma.Decimal(pi.amount).div(100).toNumber(),
|
||||
status: 'failed',
|
||||
rawData: event,
|
||||
};
|
||||
@@ -119,12 +108,9 @@ export class StripeProvider implements PaymentProvider {
|
||||
async refund(request: RefundRequest): Promise<RefundResponse> {
|
||||
const stripe = this.getClient();
|
||||
|
||||
// Retrieve checkout session to find the payment intent
|
||||
const session = await stripe.checkout.sessions.retrieve(request.tradeNo);
|
||||
if (!session.payment_intent) throw new Error('No payment intent found for session');
|
||||
|
||||
// tradeNo is now the PaymentIntent ID directly
|
||||
const refund = await stripe.refunds.create({
|
||||
payment_intent: typeof session.payment_intent === 'string' ? session.payment_intent : session.payment_intent.id,
|
||||
payment_intent: request.tradeNo,
|
||||
amount: Math.round(new Prisma.Decimal(request.amount).mul(100).toNumber()),
|
||||
reason: 'requested_by_customer',
|
||||
});
|
||||
@@ -137,6 +123,6 @@ export class StripeProvider implements PaymentProvider {
|
||||
|
||||
async cancelPayment(tradeNo: string): Promise<void> {
|
||||
const stripe = this.getClient();
|
||||
await stripe.checkout.sessions.expire(tradeNo);
|
||||
await stripe.paymentIntents.cancel(tradeNo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ export interface Sub2ApiUser {
|
||||
email: string;
|
||||
status: string; // "active", "banned", etc.
|
||||
balance: number;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface Sub2ApiRedeemCode {
|
||||
|
||||
@@ -4,16 +4,27 @@ import type { NextRequest } from 'next/server';
|
||||
export function middleware(request: NextRequest) {
|
||||
const response = NextResponse.next();
|
||||
|
||||
// IFRAME_ALLOW_ORIGINS: 允许嵌入 iframe 的外部域名(逗号分隔)
|
||||
const allowOrigins = process.env.IFRAME_ALLOW_ORIGINS || '';
|
||||
// 自动从 SUB2API_BASE_URL 提取 origin,允许 Sub2API 主站 iframe 嵌入
|
||||
const sub2apiUrl = process.env.SUB2API_BASE_URL || '';
|
||||
const extraOrigins = process.env.IFRAME_ALLOW_ORIGINS || '';
|
||||
|
||||
const origins = allowOrigins
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const origins = new Set<string>();
|
||||
|
||||
if (origins.length > 0) {
|
||||
response.headers.set('Content-Security-Policy', `frame-ancestors 'self' ${origins.join(' ')}`);
|
||||
if (sub2apiUrl) {
|
||||
try {
|
||||
origins.add(new URL(sub2apiUrl).origin);
|
||||
} catch {
|
||||
// ignore invalid URL
|
||||
}
|
||||
}
|
||||
|
||||
for (const s of extraOrigins.split(',')) {
|
||||
const trimmed = s.trim();
|
||||
if (trimmed) origins.add(trimmed);
|
||||
}
|
||||
|
||||
if (origins.size > 0) {
|
||||
response.headers.set('Content-Security-Policy', `frame-ancestors 'self' ${[...origins].join(' ')}`);
|
||||
}
|
||||
|
||||
return response;
|
||||
|
||||
Reference in New Issue
Block a user