@seaverse/payment-sdk 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,408 +1,842 @@
1
1
  # @seaverse/payment-sdk
2
2
 
3
- SeaVerse Payment SDK - Credit management and payment checkout for SeaVerse applications.
3
+ SeaVerse Payment SDK - 一站式支付解决方案,提供积分管理、支付弹窗、订阅管理和订单跟踪功能。
4
4
 
5
- ## Features
5
+ > **最新版本**: v0.8.0 | **文档语言**: 中文优先(包含英文说明)
6
6
 
7
- - **Credit Query** - Query user credit balance, pool details, and transaction history
8
- - **Payment Checkout** - Show payment modal for one-time purchases and subscriptions
9
- - **Multi-tenant Support** - Isolated credit accounts per application
10
- - **TypeScript** - Full type definitions included
11
- - **Web Component** - Uses `@seaart/payment-component` for payment UI
12
-
13
- ## Installation
7
+ ## 📦 安装
14
8
 
15
9
  ```bash
16
10
  npm install @seaverse/payment-sdk
17
- # or
11
+ #
18
12
  pnpm add @seaverse/payment-sdk
19
13
  ```
20
14
 
21
- > **Note**: `@seaart/payment-component` is bundled into the SDK, no need to install it separately.
22
-
23
- ## Quick Start
15
+ ## 🚀 快速开始
24
16
 
25
- ### Credit Query
17
+ ### 1. 积分套餐购买弹窗(推荐使用)
26
18
 
27
- Query user credit accounts and transaction history:
19
+ 最简单的集成方式 - 3 行代码完成支付流程:
28
20
 
29
21
  ```typescript
30
- import { PaymentClient } from '@seaverse/payment-sdk';
31
-
32
- const client = new PaymentClient({
33
- appId: 'seaverse',
34
- token: 'your-bearer-token',
22
+ import { CreditPackageModal } from '@seaverse/payment-sdk';
23
+
24
+ // 创建弹窗
25
+ const modal = new CreditPackageModal({
26
+ sdkConfig: {
27
+ environment: 'development', // 环境:'development' | 'production'
28
+ countryCode: 'SG', // 国家代码
29
+ accountToken: 'user-token', // 用户认证令牌(可选)
30
+ },
31
+ onPaymentSuccess: (orderId, transactionId) => {
32
+ console.log('支付成功!', { orderId, transactionId });
33
+ },
35
34
  });
36
35
 
37
- // Get credit detail with 4-pool breakdown
38
- const detail = await client.getCreditDetail();
39
- console.log(`Total Balance: ${detail.total_balance}`);
36
+ // 打开弹窗
37
+ modal.open();
38
+ ```
40
39
 
41
- detail.pools.forEach(pool => {
42
- console.log(`${pool.type}: ${pool.balance}`);
40
+ **效果**:
41
+ - ✅ 自动展示预设积分套餐(120/240/520/1200 积分)
42
+ - ✅ 自动初始化支付 SDK
43
+ - ✅ 自动创建订单
44
+ - ✅ 显示购买成功弹窗(带动画效果)
45
+ - ✅ 自动刷新积分余额
46
+
47
+ ### 2. 通用套餐弹窗(自定义套餐)
48
+
49
+ 适用于特殊促销、破冰包、首充包等场景:
50
+
51
+ ```typescript
52
+ import { GenericPackageModal, type GenericPackage } from '@seaverse/payment-sdk';
53
+
54
+ // 定义自定义套餐
55
+ const packages: GenericPackage[] = [
56
+ {
57
+ id: 'pkg_value',
58
+ name: 'Ice Breaker Pack',
59
+ price: '0.49',
60
+ currency: 'USD',
61
+ credits: '120',
62
+ bonus_percentage: 20,
63
+ day_limit: 1, // 每日限购1次
64
+ package_type: 'iceBreaker',
65
+ },
66
+ {
67
+ id: 'pkg_pro',
68
+ name: 'Emergency Pack',
69
+ price: '0.99',
70
+ currency: 'USD',
71
+ credits: '240',
72
+ day_limit: 3, // 每日限购3次
73
+ package_type: 'emergency',
74
+ },
75
+ ];
76
+
77
+ // 创建弹窗
78
+ const modal = new GenericPackageModal({
79
+ packages: packages,
80
+ sdkConfig: {
81
+ environment: 'development',
82
+ countryCode: 'SG',
83
+ accountToken: 'user-token',
84
+ },
85
+ onPaymentSuccess: (orderId, transactionId, pkg) => {
86
+ console.log(`${pkg.name} 购买成功!`, orderId);
87
+ },
88
+ onPaymentFailed: (error, pkg) => {
89
+ if (error.message.includes('limit')) {
90
+ alert(`${pkg.name} 已达购买限额`);
91
+ }
92
+ },
43
93
  });
44
94
 
45
- // List transactions
46
- const transactions = await client.listTransactions({ page_size: 10 });
95
+ modal.open();
47
96
  ```
48
97
 
49
- ### Payment Checkout
98
+ ## 📖 核心功能模块
99
+
100
+ ### ⭐️ 推荐功能(新用户优先使用)
101
+
102
+ | 功能 | 组件 | 使用场景 | 文档 |
103
+ | ------------------ | ---------------------- | ---------------------- | ----------------------------------------------- |
104
+ | **积分套餐购买** | `CreditPackageModal` | 标准积分购买(最简单) | [👉 查看](#creditpackagemodal---标准积分购买) |
105
+ | **自定义套餐购买** | `GenericPackageModal` | 促销活动、特殊套餐 | [👉 查看](#genericpackagemodal---自定义套餐购买) |
106
+ | **购买成功弹窗** | `PurchaseSuccessModal` | 自动集成,无需手动调用 | [👉 查看](#purchasesuccessmodal---购买成功弹窗) |
107
+
108
+ ### 🔧 高级功能(进阶用户)
109
+
110
+ | 功能 | API | 使用场景 |
111
+ | --------------------- | ---------------------------------------------- | -------------------------- |
112
+ | **积分查询** | `PaymentClient` | 查询用户积分余额、交易记录 |
113
+ | **订阅管理** | `getCurrentSubscription`, `changeSubscription` | 订阅状态查询、升级/降级 |
114
+ | **订单管理** | `checkOrderStatus`, `pollOrderStatus` | 订单状态查询、轮询 |
115
+ | **SeaartPayment SDK** | `SeaartPaymentSDK` | 完全自定义支付流程 |
116
+
117
+ ---
118
+
119
+ ## 📚 详细使用文档
50
120
 
51
- Show payment modal for purchases:
121
+ ### CreditPackageModal - 标准积分购买
122
+
123
+ **适用场景**:
124
+ - ✅ 标准积分套餐购买(120/240/520/1200 积分)
125
+ - ✅ 展示创作力量类型(文生图、图生图等)
126
+ - ✅ 最简单的集成方式
127
+
128
+ #### 基础用法
52
129
 
53
130
  ```typescript
54
- import { PaymentCheckoutClient } from '@seaverse/payment-sdk';
55
- // Import the Web Component styles
56
- import '@seaverse/payment-sdk/style.css';
57
-
58
- const checkoutClient = new PaymentCheckoutClient({
59
- apiHost: 'https://payment.sg.seaverse.dev',
60
- authToken: 'your-jwt-token',
61
- environment: 'development', // or 'production'
62
- debug: true,
131
+ import { CreditPackageModal } from '@seaverse/payment-sdk';
132
+
133
+ const modal = new CreditPackageModal({
134
+ // 语言设置(可选,默认 'en')
135
+ language: 'zh-CN', // 'en' | 'zh-CN'
136
+
137
+ // SDK 配置(必填)
138
+ sdkConfig: {
139
+ environment: 'development', // 'development' | 'production'
140
+ countryCode: 'SG', // ISO 3166-1 国家代码
141
+ accountToken: 'user-token', // 用户认证令牌(可选)
142
+ businessType: 1, // 1=一次性购买, 2=订阅(可选,默认1)
143
+ },
144
+
145
+ // 回调函数
146
+ onPaymentSuccess: (orderId: string, transactionId: string) => {
147
+ console.log('支付成功!', { orderId, transactionId });
148
+ // 刷新用户积分、更新 UI 等
149
+ },
150
+
151
+ onPaymentFailed: (error: Error) => {
152
+ console.error('支付失败:', error.message);
153
+ // 显示错误提示
154
+ },
155
+
156
+ onClose: () => {
157
+ console.log('弹窗关闭');
158
+ },
63
159
  });
64
160
 
65
- // Initialize (loads Web Component)
66
- await checkoutClient.init();
161
+ // 打开弹窗
162
+ modal.open();
67
163
 
68
- // One-time purchase
69
- await checkoutClient.checkout({
70
- productId: 'pkg_starter', // Required
71
- onSuccess: (res) => console.log('Payment success:', res),
72
- onError: (err) => console.error('Payment failed:', err),
73
- });
164
+ // 关闭弹窗(可选)
165
+ modal.close();
74
166
 
75
- // Subscription
76
- await checkoutClient.subscribe({
77
- productId: 'pro', // Required
78
- billing_period: 'month', // Optional: 'month' | 'year' (default: 'month')
79
- onSuccess: (res) => console.log('Subscription success:', res),
80
- });
167
+ // 检查弹窗状态
168
+ console.log('弹窗是否打开:', modal.isOpen());
81
169
  ```
82
170
 
83
- ## API Reference
171
+ #### 预设积分套餐
84
172
 
85
- ### PaymentClient (Credit Query)
173
+ SDK 内置以下积分套餐:
86
174
 
87
- | Method | Description |
88
- |--------|-------------|
89
- | `getCreditDetail()` | Get credit balance with 4-pool breakdown |
90
- | `getCreditAccount()` | Get credit account information (deprecated) |
91
- | `listTransactions(request)` | List credit transactions with filters |
92
- | `setToken(token)` | Update bearer token |
93
- | `setBaseURL(baseURL)` | Update API base URL |
94
- | `setAppId(appId)` | Update application ID |
175
+ | 套餐 | 积分 | 价格 | 说明 |
176
+ | ------- | ---- | ----- | -------- |
177
+ | Starter | 120 | $0.49 | 入门套餐 |
178
+ | Value | 240 | $0.99 | 超值套餐 |
179
+ | Pro | 520 | $1.99 | 专业套餐 |
180
+ | Ultra | 1200 | $4.99 | 旗舰套餐 |
95
181
 
96
- ### PaymentCheckoutClient (Payment Modal)
182
+ #### 环境配置
97
183
 
98
- | Method | Description |
99
- |--------|-------------|
100
- | `init()` | Initialize and load Web Component |
101
- | `checkout(options)` | One-time purchase with payment modal |
102
- | `subscribe(options)` | Subscription purchase with payment modal |
103
- | `showPayment(options)` | Show payment modal with existing transactionId |
104
- | `close()` | Close payment modal |
105
- | `getStatus()` | Get client status |
106
- | `isReady()` | Check if client is initialized |
184
+ SDK 根据 `environment` 自动配置以下参数:
107
185
 
108
- ## Credit Pool Types
186
+ **开发环境 (development)**:
187
+ ```typescript
188
+ {
189
+ scriptUrl: 'https://seaart-publish.sc-api-release.saconsole.com/payment-component/client.js',
190
+ clientId: 'XF49NOfyZ54O16GujB0ptio2',
191
+ orderApiUrl: 'https://payment.sg.seaverse.dev',
192
+ walletApiUrl: 'https://wallet.sg.seaverse.dev',
193
+ }
194
+ ```
109
195
 
110
- The 4-pool credit system:
196
+ **生产环境 (production)**:
197
+ ```typescript
198
+ {
199
+ scriptUrl: 'https://payment-static.seaverse.com/sdk/seaart-payment-component.js',
200
+ clientId: 'prod_client_id',
201
+ orderApiUrl: 'https://payment.seaverse.com',
202
+ walletApiUrl: 'https://wallet.seaverse.com',
203
+ }
204
+ ```
111
205
 
112
- | Pool | Description | Expiration |
113
- |------|-------------|------------|
114
- | `daily` | Daily credits | Next day 00:00 UTC |
115
- | `event` | Event credits | Event deadline |
116
- | `monthly` | Monthly credits | 30 days after grant |
117
- | `permanent` | Permanent credits | Never |
206
+ #### 高级配置(可选)
118
207
 
119
- **Consumption Priority:** Daily → Event → Monthly → Permanent
208
+ 如需覆盖环境配置:
120
209
 
121
- ## Configuration
210
+ ```typescript
211
+ const modal = new CreditPackageModal({
212
+ sdkConfig: {
213
+ environment: 'production',
214
+ countryCode: 'US',
215
+
216
+ // 覆盖默认配置
217
+ scriptUrl: 'https://custom-cdn.com/payment.js',
218
+ clientId: 'custom-client-id',
219
+ orderApiUrl: 'https://custom-api.com',
220
+ },
221
+ });
222
+ ```
223
+
224
+ ---
225
+
226
+ ### GenericPackageModal - 自定义套餐购买
122
227
 
123
- ### PaymentClient Options
228
+ **适用场景**:
229
+ - ✅ 特殊促销套餐(破冰包、告急包、首充包)
230
+ - ✅ 限时优惠活动
231
+ - ✅ 自定义套餐数据和样式
232
+
233
+ #### 基础用法
124
234
 
125
235
  ```typescript
126
- interface PaymentClientOptions {
127
- appId: string; // Application ID for multi-tenant isolation
128
- token: string; // Bearer token for authentication
129
- baseURL?: string; // API base URL (default: 'https://payment.sg.seaverse.dev')
130
- timeout?: number; // Request timeout in ms (default: 30000)
131
- }
236
+ import { GenericPackageModal, type GenericPackage } from '@seaverse/payment-sdk';
237
+
238
+ // 定义套餐数据
239
+ const packages: GenericPackage[] = [
240
+ {
241
+ id: 'pkg_ice_breaker',
242
+ name: 'Ice Breaker Pack',
243
+ price: '0.49',
244
+ currency: 'USD',
245
+ credits: '120',
246
+ base_credits: '100',
247
+ bonus_credits: '20',
248
+ bonus_percentage: 20,
249
+ day_limit: 1,
250
+ package_type: 'iceBreaker',
251
+ },
252
+ ];
253
+
254
+ // 创建弹窗
255
+ const modal = new GenericPackageModal({
256
+ language: 'zh-CN',
257
+ packages: packages,
258
+
259
+ sdkConfig: {
260
+ environment: 'development',
261
+ countryCode: 'SG',
262
+ accountToken: 'user-token',
263
+ },
264
+
265
+ onPaymentSuccess: (orderId, transactionId, pkg) => {
266
+ console.log(`${pkg.name} 购买成功!`, { orderId, transactionId });
267
+ },
268
+
269
+ onPaymentFailed: (error, pkg) => {
270
+ console.error(`${pkg.name} 购买失败:`, error.message);
271
+ },
272
+ });
273
+
274
+ modal.open();
132
275
  ```
133
276
 
134
- ### PaymentCheckoutClient Options
277
+ #### GenericPackage 接口定义
135
278
 
136
279
  ```typescript
137
- interface CheckoutClientConfig {
138
- apiHost: string; // Payment gateway API URL
139
- authToken?: string; // Static JWT token
140
- getAuthToken?: () => string; // Dynamic token getter
141
- environment?: 'development' | 'production'; // Environment
142
- debug?: boolean; // Debug mode
143
- componentTimeout?: number; // Web Component load timeout in ms
280
+ interface GenericPackage {
281
+ // 基础信息(必填)
282
+ id: string; // 套餐唯一标识
283
+ name: string; // 套餐名称
284
+ price: string; // 价格(字符串,支持小数)
285
+ currency: string; // 货币代码(如 'USD')
286
+ credits: string; // 总积分数
287
+
288
+ // 奖励信息(可选)
289
+ base_credits?: string; // 基础积分
290
+ bonus_credits?: string; // 奖励积分
291
+ bonus_percentage?: number; // 奖励百分比(如 20 表示 +20%)
292
+
293
+ // 购买限制(可选,仅用于展示,后端验证)
294
+ day_limit?: number; // 每日限购次数(0 = 无限制)
295
+ lifetime_limit?: number; // 终身限购次数(0 = 无限制)
296
+
297
+ // 分类标识(可选)
298
+ package_type?: 'iceBreaker' | 'emergency' | 'firstCharge' | 'custom';
144
299
  }
145
300
  ```
146
301
 
147
- ### Checkout Options
302
+ #### 预定义套餐示例
303
+
304
+ SDK 提供以下预定义套餐供参考:
148
305
 
149
306
  ```typescript
150
- interface CheckoutOptions {
151
- productId: string; // Product ID (required)
152
- language?: string; // Language setting
153
- userName?: string; // User name for display
154
- redirectUrl?: string; // Redirect URL after payment
155
- onSuccess?: (result: PaymentResult) => void; // Success callback
156
- onError?: (error: CheckoutPaymentError) => void; // Error callback
157
- onClose?: () => void; // Close callback
158
- }
307
+ import {
308
+ EXAMPLE_ICE_BREAKER, // 破冰包
309
+ EXAMPLE_EMERGENCY, // 告急包
310
+ EXAMPLE_FIRST_CHARGE, // 首充包
311
+ EXAMPLE_PACKAGES, // 所有示例套餐数组
312
+ } from '@seaverse/payment-sdk';
313
+
314
+ // 使用预定义套餐
315
+ const modal = new GenericPackageModal({
316
+ packages: [EXAMPLE_ICE_BREAKER, EXAMPLE_EMERGENCY],
317
+ sdkConfig: { /* ... */ },
318
+ });
159
319
  ```
160
320
 
161
- ### Subscription Options
321
+ **预定义套餐详情**:
162
322
 
163
- ```typescript
164
- interface SubscribeOptions extends CheckoutOptions {
165
- billing_period?: 'month' | 'year'; // Optional: billing period (default: 'month')
166
- }
323
+ | 套餐 | 价格 | 积分 | 限制 | 说明 |
324
+ | ---------------------- | ----- | ---- | ------- | ------------------------ |
325
+ | `EXAMPLE_ICE_BREAKER` | $0.49 | 120 | 每日1次 | 破冰包 - 超低价首次破冰 |
326
+ | `EXAMPLE_EMERGENCY` | $0.99 | 240 | 每日3次 | 告急包 - 日常转化主力 |
327
+ | `EXAMPLE_FIRST_CHARGE` | $1.99 | 620 | 终身1次 | 首充包 - 提升首充用户LTV |
328
+
329
+ ---
330
+
331
+ ### PurchaseSuccessModal - 购买成功弹窗
332
+
333
+ **✨ 自动集成** - 无需手动调用,在 `CreditPackageModal` 和 `GenericPackageModal` 支付成功后自动显示。
334
+
335
+ #### 功能特性
336
+
337
+ - ✅ 邮件确认卡片风格设计
338
+ - ✅ 精美动画效果(淡入淡出、缩放、顺序动画)
339
+ - ✅ 显示购买详情(套餐名称、积分数、支付金额)
340
+ - ✅ 支持 ESC 键、点击遮罩、关闭按钮关闭
341
+ - ✅ 自动阻止 body 滚动
342
+ - ✅ 支持中英文切换
343
+
344
+ #### 自动触发流程
345
+
346
+ ```
347
+ 用户点击购买按钮
348
+
349
+ 支付成功
350
+
351
+ CreditPackageModal/GenericPackageModal 关闭
352
+
353
+ PurchaseSuccessModal 自动显示(带动画)
354
+
355
+ 用户关闭成功弹窗
356
+
357
+ 自动刷新积分余额
358
+
359
+ 触发 onPaymentSuccess 回调
167
360
  ```
168
361
 
169
- ### Environment Configuration
362
+ #### 手动使用(可选)
170
363
 
171
- | Environment | API Host |
172
- |-------------|----------|
173
- | `development` | `https://aiart-openresty.dev.seaart.dev` |
174
- | `production` | `https://www.seaart.ai` |
364
+ 如需在其他场景手动调用:
175
365
 
176
- ## Styling and CSS
366
+ ```typescript
367
+ import { PurchaseSuccessModal } from '@seaverse/payment-sdk';
368
+
369
+ const successModal = new PurchaseSuccessModal({
370
+ data: {
371
+ packName: 'Ice Breaker Pack',
372
+ credits: 120,
373
+ amount: '0.49',
374
+ currency: '$',
375
+ orderId: 'order_123',
376
+ transactionId: 'txn_456',
377
+ },
378
+ language: 'zh-CN',
379
+ onClose: () => {
380
+ console.log('成功弹窗关闭');
381
+ },
382
+ });
177
383
 
178
- ### Style Isolation
384
+ successModal.open();
385
+ ```
179
386
 
180
- The SDK uses the bundled `@seaart/payment-component` Web Component for the payment UI. The component's styles (30KB) are optimized for minimal global impact:
387
+ ---
181
388
 
182
- **✅ Well-isolated styles:**
183
- - 218 component-scoped selectors using Vue's `[data-v-*]` attributes
184
- - All component-specific styles are scoped to avoid conflicts
185
- - Major global resets (`*{...}`, `html,body{...}`) have been removed
389
+ ## 🔍 高级功能
186
390
 
187
- **⚠️ Remaining global styles (low risk):**
391
+ ### 积分查询(PaymentClient)
188
392
 
189
- The following global styles are included and may affect your application:
393
+ 查询用户积分余额和交易记录:
190
394
 
191
- ```css
192
- /* App root container (may conflict if you use #app as root element ID) */
193
- #app {
194
- width: 100%;
195
- height: 100%;
196
- background: transparent;
197
- }
395
+ ```typescript
396
+ import { PaymentClient } from '@seaverse/payment-sdk';
198
397
 
199
- /* Custom scrollbar styling (WebKit browsers only) */
200
- ::-webkit-scrollbar { width: 6px; height: 6px }
201
- ::-webkit-scrollbar-track { background: transparent }
202
- ::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 3px }
398
+ const client = new PaymentClient({
399
+ appId: 'seaverse',
400
+ token: 'your-bearer-token',
401
+ baseURL: 'https://payment.sg.seaverse.dev', // 可选
402
+ });
203
403
 
204
- /* Text selection color */
205
- ::selection {
206
- background: #6366f1;
207
- color: #fff;
208
- }
404
+ // 查询积分详情(4 池结构)
405
+ const detail = await client.getCreditDetail();
406
+ console.log('总余额:', detail.total_balance);
407
+
408
+ detail.pools.forEach(pool => {
409
+ console.log(`${pool.type} 池:${pool.balance} 积分`);
410
+ });
411
+
412
+ // 查询交易记录
413
+ const transactions = await client.listTransactions({
414
+ page: 1,
415
+ page_size: 20,
416
+ start_time: '2024-01-01T00:00:00Z',
417
+ end_time: '2024-12-31T23:59:59Z',
418
+ });
419
+
420
+ transactions.transactions.forEach(txn => {
421
+ console.log(`${txn.type}: ${txn.amount} 积分`);
422
+ });
209
423
  ```
210
424
 
211
- **Risk assessment:**
212
- - `#app` selector: **Medium risk** - Only conflicts if your root element uses `id="app"`
213
- - Scrollbar styles: **Low risk** - Only affects scrollbar appearance in WebKit browsers
214
- - Selection color: **Low risk** - Only changes text selection highlight color
425
+ #### 4 池积分系统
426
+
427
+ | 池类型 | 说明 | 过期时间 |
428
+ | ----------- | -------- | -------------- |
429
+ | `daily` | 每日积分 | 次日 00:00 UTC |
430
+ | `event` | 活动积分 | 活动截止日期 |
431
+ | `monthly` | 月度积分 | 授予后 30 天 |
432
+ | `permanent` | 永久积分 | 永不过期 |
215
433
 
216
- **Recommendations:**
217
- 1. ✅ Avoid using `id="app"` for your application's root element
218
- 2. ✅ If you encounter conflicts, please report them as an issue
219
- 3. ✅ Future SDK versions may provide additional isolation options if needed
434
+ **消费优先级**:Daily → Event → Monthly → Permanent
220
435
 
221
- ### CSS Import
436
+ ---
222
437
 
223
- Always import the SDK styles in your application:
438
+ ### 订阅管理
439
+
440
+ 查询和管理用户订阅:
224
441
 
225
442
  ```typescript
226
- import '@seaverse/payment-sdk/style.css';
443
+ import {
444
+ getCurrentSubscription,
445
+ getActiveSubscription,
446
+ changeSubscription,
447
+ restartSubscription,
448
+ } from '@seaverse/payment-sdk';
449
+
450
+ const apiUrl = 'https://payment.sg.seaverse.dev';
451
+ const token = 'user-token';
452
+
453
+ // 查询当前订阅状态
454
+ const current = await getCurrentSubscription(apiUrl, token);
455
+ console.log('订阅状态:', current.subscription_status);
456
+
457
+ // 查询活跃订阅详情
458
+ const active = await getActiveSubscription(apiUrl, token);
459
+ console.log('当前套餐:', active.product_name);
460
+
461
+ // 升级/降级订阅
462
+ const changeResult = await changeSubscription(apiUrl, token, {
463
+ productId: 'pro_plan',
464
+ billingPeriod: 'year',
465
+ redirectUrl: window.location.href,
466
+ });
467
+
468
+ // 重启已取消的订阅
469
+ const restartResult = await restartSubscription(apiUrl, token, {
470
+ subscriptionId: 'sub_123',
471
+ });
227
472
  ```
228
473
 
229
- **Note:** The Web Component is already bundled into the SDK, so you do **not** need to install `@seaart/payment-component` separately.
474
+ ---
230
475
 
231
- ## Usage with Frameworks
476
+ ### 订单管理
232
477
 
233
- ### Vue 3
478
+ 检查订单状态和轮询支付结果:
234
479
 
235
- ```vue
236
- <script setup lang="ts">
237
- import { ref, onMounted } from 'vue';
238
- import { PaymentCheckoutClient } from '@seaverse/payment-sdk';
239
- import '@seaverse/payment-sdk/style.css';
480
+ ```typescript
481
+ import { checkOrderStatus, pollOrderStatus } from '@seaverse/payment-sdk';
482
+
483
+ const apiUrl = 'https://payment.sg.seaverse.dev';
484
+ const token = 'user-token';
485
+
486
+ // 单次查询订单状态
487
+ const status = await checkOrderStatus('transaction_id', apiUrl, token);
488
+ console.log('订单状态:', status.order_status);
489
+
490
+ // 轮询订单状态直到最终状态
491
+ const finalStatus = await pollOrderStatus('transaction_id', apiUrl, token, {
492
+ interval: 2000, // 轮询间隔(毫秒)
493
+ maxAttempts: 30, // 最大尝试次数
494
+ onPoll: (status, attempt) => {
495
+ console.log(`第 ${attempt} 次查询:${status}`);
496
+ },
497
+ });
240
498
 
241
- const checkoutClient = ref<PaymentCheckoutClient | null>(null);
499
+ console.log('最终状态:', finalStatus.order_status);
500
+ ```
242
501
 
243
- onMounted(async () => {
244
- checkoutClient.value = new PaymentCheckoutClient({
245
- apiHost: 'https://payment.sg.seaverse.dev',
246
- authToken: 'your-token',
247
- environment: import.meta.env.DEV ? 'development' : 'production',
248
- });
249
- await checkoutClient.value.init();
502
+ ---
503
+
504
+ ### SeaartPayment SDK(完全自定义)
505
+
506
+ 适用于需要完全控制支付流程的高级场景:
507
+
508
+ ```typescript
509
+ import { SeaartPaymentSDK } from '@seaverse/payment-sdk';
510
+
511
+ // 1. 初始化 SDK(应用启动时)
512
+ const sdk = SeaartPaymentSDK.getInstance();
513
+ await sdk.init({
514
+ scriptUrl: 'https://your-cdn.com/seaart-payment.js',
515
+ clientId: 'your-client-id',
516
+ language: 'en',
517
+ cssUrl: 'https://your-cdn.com/seaart-payment.css', // 可选
250
518
  });
251
519
 
252
- async function handlePurchase() {
253
- await checkoutClient.value?.checkout({
254
- productId: 'pkg_starter',
255
- onSuccess: (res) => console.log('Success:', res),
256
- });
520
+ // 2. 获取支付方式
521
+ const methods = await sdk.getPaymentMethods({
522
+ country_code: 'US',
523
+ business_type: 2, // 1=一次性, 2=订阅
524
+ });
525
+
526
+ // 3. 创建订单支付实例
527
+ const orderPayment = sdk.createOrderPayment({
528
+ orderId: 'order-123',
529
+ accountToken: 'user-token',
530
+ });
531
+
532
+ // 4a. 跳转支付(Link Payment)
533
+ const linkMethod = methods.find(m => m.payment_type === 1);
534
+ const linkPayment = orderPayment.createLinkPayment(linkMethod, {
535
+ callback_url: `${window.location.origin}/payment-callback`,
536
+ });
537
+ await linkPayment.redirectToPayment();
538
+
539
+ // 4b. 嵌入式支付(Dropin Payment)
540
+ const dropinMethod = methods.find(m => m.payment_type === 2);
541
+ const dropinPayment = orderPayment.createDropinPayment(dropinMethod, {
542
+ containerId: '#payment-container',
543
+ onCompleted: (payload) => {
544
+ console.log('支付成功:', payload);
545
+ },
546
+ onFailed: (payload) => {
547
+ console.error('支付失败:', payload);
548
+ },
549
+ });
550
+ await dropinPayment.render();
551
+
552
+ // 5. 处理支付回调(回调页面)
553
+ const result = await sdk.handleCallback(
554
+ { type: 'subscription' },
555
+ 'https://payment-api.com',
556
+ 'auth-token'
557
+ );
558
+ if (result.success) {
559
+ console.log('支付验证成功:', result.data);
257
560
  }
258
- </script>
259
561
  ```
260
562
 
261
- ### React
563
+ ---
262
564
 
263
- ```tsx
264
- import { useEffect, useRef } from 'react';
265
- import { PaymentCheckoutClient } from '@seaverse/payment-sdk';
266
- import '@seaverse/payment-sdk/style.css';
267
-
268
- function PaymentPage() {
269
- const clientRef = useRef<PaymentCheckoutClient | null>(null);
270
-
271
- useEffect(() => {
272
- const init = async () => {
273
- clientRef.current = new PaymentCheckoutClient({
274
- apiHost: 'https://payment.sg.seaverse.dev',
275
- authToken: 'your-token',
276
- environment: process.env.NODE_ENV === 'development' ? 'development' : 'production',
277
- });
278
- await clientRef.current.init();
279
- };
280
- init();
281
- }, []);
282
-
283
- const handlePurchase = async () => {
284
- await clientRef.current?.checkout({
285
- productId: 'pkg_starter',
286
- onSuccess: (res) => console.log('Success:', res),
287
- });
288
- };
565
+ ## ⚙️ 配置选项
566
+
567
+ ### 环境配置(Environment)
568
+
569
+ | 环境 | 值 | 说明 |
570
+ | -------- | --------------- | ------------ |
571
+ | 开发环境 | `'development'` | 开发测试环境 |
572
+ | 生产环境 | `'production'` | 正式生产环境 |
573
+
574
+ ### SDK 配置(sdkConfig)
289
575
 
290
- return <button onClick={handlePurchase}>Purchase</button>;
576
+ ```typescript
577
+ interface PaymentSDKConfig {
578
+ // 必填参数
579
+ environment: 'development' | 'production'; // 环境变量
580
+ countryCode: string; // 国家代码(ISO 3166-1)
581
+
582
+ // 可选参数
583
+ accountToken?: string; // 用户认证令牌
584
+ businessType?: 1 | 2; // 1=一次性购买, 2=订阅(默认 1)
585
+
586
+ // 高级选项(覆盖环境配置)
587
+ scriptUrl?: string; // 自定义脚本 URL
588
+ clientId?: string; // 自定义客户端 ID
589
+ orderApiUrl?: string; // 自定义订单 API 地址
590
+ cssUrl?: string; // 自定义 CSS URL
591
+ scriptTimeout?: number; // 脚本加载超时(默认 10000ms)
592
+ paymentMethodType?: string; // 支付方式类型过滤(默认 'dropin')
291
593
  }
292
594
  ```
293
595
 
294
- ## Migration from v0.1.x
596
+ ---
597
+
598
+ ## 🎨 UI 反馈工具
599
+
600
+ SDK 提供统一的 UI 反馈工具,替代浏览器原生 `alert()`:
295
601
 
296
- ### Breaking Changes
602
+ ```typescript
603
+ import {
604
+ showErrorMessage,
605
+ showSuccessMessage,
606
+ showInfoMessage,
607
+ showLoadingIndicator,
608
+ hideLoadingIndicator,
609
+ } from '@seaverse/payment-sdk';
610
+
611
+ // 错误提示(红色渐变背景)
612
+ showErrorMessage('支付失败,请重试', 3000);
613
+
614
+ // 成功提示(绿色渐变背景)
615
+ showSuccessMessage('支付成功!', 3000);
616
+
617
+ // 信息提示(蓝色渐变背景)
618
+ showInfoMessage('正在处理您的请求...', 3000);
619
+
620
+ // 加载指示器
621
+ const loader = showLoadingIndicator('初始化支付系统...');
622
+ // ... 异步操作
623
+ hideLoadingIndicator(loader);
624
+ ```
297
625
 
298
- 1. **Environment naming changed:**
299
- - `'develop'` `'development'`
300
- - `'release'` → `'production'`
626
+ **特性**:
627
+ - 精美渐变背景 + 图标
628
+ - 自动淡入淡出动画
629
+ - ✅ 自动移除(可配置时长)
630
+ - ✅ 防止重复显示
631
+ - ✅ XSS 防护
301
632
 
302
- 2. **Import CSS file:**
303
- ```typescript
304
- import '@seaverse/payment-sdk/style.css';
305
- ```
633
+ ---
306
634
 
307
- 3. **Configuration options renamed:**
308
- - `sdkCdnUrl` removed (no longer uses CDN)
309
- - `sdkTimeout` → `componentTimeout`
635
+ ## 🛡️ 错误处理
310
636
 
311
- ### Before (v0.1.x)
637
+ ### 业务错误码(BIZ_CODE)
638
+
639
+ | 错误码 | 常量 | 说明 |
640
+ | ------ | ---------------------- | ------------ |
641
+ | `0` | `SUCCESS` | 操作成功 |
642
+ | `400` | `BAD_REQUEST` | 请求参数错误 |
643
+ | `401` | `UNAUTHORIZED` | 未授权 |
644
+ | `500` | `SERVER_ERROR` | 服务器错误 |
645
+ | `4001` | `DAILY_LIMIT_EXCEEDED` | 超过每日限额 |
646
+ | `4002` | `PRODUCT_NOT_FOUND` | 产品不存在 |
647
+ | `4004` | `INSUFFICIENT_BALANCE` | 余额不足 |
648
+ | `4005` | `ORDER_NOT_FOUND` | 订单不存在 |
649
+
650
+ ### 错误处理示例
312
651
 
313
652
  ```typescript
314
- const client = new PaymentCheckoutClient({
315
- apiHost: 'https://payment.sg.seaverse.dev',
316
- authToken: 'token',
317
- environment: 'develop', // Old naming
653
+ const modal = new GenericPackageModal({
654
+ packages: packages,
655
+ sdkConfig: { /* ... */ },
656
+
657
+ onPaymentFailed: (error, pkg) => {
658
+ // 处理限额错误
659
+ if (error.message.includes('Daily limit')) {
660
+ showErrorMessage(`您已达到 ${pkg.name} 的每日购买限额`);
661
+ } else if (error.message.includes('Lifetime limit')) {
662
+ showErrorMessage('此套餐仅限购买一次,您已购买过');
663
+ } else {
664
+ showErrorMessage(`支付失败:${error.message}`);
665
+ }
666
+ },
318
667
  });
319
668
  ```
320
669
 
321
- ### After (v0.2.x+)
670
+ ---
322
671
 
323
- ```typescript
324
- import '@seaverse/payment-sdk/style.css'; // Required!
672
+ ## 🧪 测试卡号(开发环境)
673
+
674
+ 在开发环境测试支付功能:
675
+
676
+ | 字段 | 值 |
677
+ | -------- | ------------------ |
678
+ | 卡号 | `4212345678910006` |
679
+ | 有效期 | `03/30` |
680
+ | CVC | `737` |
681
+ | 3DS 密码 | `password` |
682
+
683
+ ---
684
+
685
+ ## 📊 API 对比表
686
+
687
+ ### CreditPackageModal vs GenericPackageModal
325
688
 
326
- const client = new PaymentCheckoutClient({
327
- apiHost: 'https://payment.sg.seaverse.dev',
328
- authToken: 'token',
329
- environment: 'development', // New naming
689
+ | 特性 | CreditPackageModal | GenericPackageModal |
690
+ | -------------- | ------------------ | --------------------------------- |
691
+ | **套餐数据** | 内置预设套餐 | 外部配置(灵活) |
692
+ | **套餐类型** | 标准积分套餐 | 任意类型(破冰/告急/首充/自定义) |
693
+ | **购买限制** | 无 | 支持每日/终身限购 |
694
+ | **奖励展示** | 无 | 支持奖励百分比 |
695
+ | **配置复杂度** | ⭐️ 简单 | ⭐️⭐️ 中等 |
696
+ | **使用场景** | 标准积分购买 | 特殊促销、限时活动 |
697
+
698
+ **选择建议**:
699
+ - 🎯 **标准积分购买** → 使用 `CreditPackageModal`(推荐新手)
700
+ - 🎁 **特殊促销活动** → 使用 `GenericPackageModal`
701
+
702
+ ---
703
+
704
+ ## 🔄 迁移指南
705
+
706
+ ### 从 v0.8.x 迁移到 v0.9.x
707
+
708
+ **主要变化**:引入环境配置,简化参数
709
+
710
+ ```typescript
711
+ // ✅ 新版本(v0.8.x)
712
+ const modal = new GenericPackageModal({
713
+ packages: packages,
714
+ sdkConfig: {
715
+ environment: 'development', // 只需指定环境
716
+ countryCode: 'SG', // 扁平化参数
717
+ businessType: 1, // 可选,默认 1
718
+ },
330
719
  });
331
720
  ```
332
721
 
333
- ## Error Handling
722
+ **参数变化**:
723
+ - ✅ 新增:`environment` - 自动配置所有 URL
724
+ - ✅ 简化:`countryCode` - 从 `paymentMethodsParams.country_code` 扁平化
725
+ - ✅ 简化:`businessType` - 从 `paymentMethodsParams.business_type` 扁平化
334
726
 
335
- ### Business Error Codes (BIZ_CODE)
727
+ ---
336
728
 
337
- The SDK uses standardized business error codes returned from the API:
729
+ ## 🌐 框架集成
338
730
 
339
- | Code | Constant | Description |
340
- |------|----------|-------------|
341
- | `0` | `SUCCESS` | 操作成功 |
342
- | `400` | `BAD_REQUEST` | 请求参数错误 |
343
- | `401` | `UNAUTHORIZED` | 未授权 |
344
- | `500` | `SERVER_ERROR` | 服务器错误 |
345
- | `4001` | `DAILY_LIMIT_EXCEEDED` | 超过每日限额 |
346
- | `4002` | `PRODUCT_NOT_FOUND` | 商品不存在 |
347
- | `4003` | `PRODUCT_DISABLED` | 商品已禁用 |
348
- | `4004` | `INSUFFICIENT_BALANCE` | 余额不足 |
349
- | `4005` | `ORDER_NOT_FOUND` | 订单不存在 |
350
- | `4006` | `INVALID_ORDER_STATUS` | 订单状态无效 |
351
-
352
- ### Checkout Error Codes
353
-
354
- Payment checkout operations may throw errors with these codes:
355
-
356
- | Code | Description |
357
- |------|-------------|
358
- | `COMPONENT_LOAD_FAILED` | Web Component 加载失败 |
359
- | `COMPONENT_NOT_READY` | Web Component 未就绪 |
360
- | `API_ERROR` | API 请求错误 |
361
- | `CHECKOUT_FAILED` | 结账失败 |
362
- | `PAYMENT_CANCELLED` | 用户取消支付 |
363
- | `PAYMENT_FAILED` | 支付失败 |
364
- | `INVALID_PARAMS` | 参数无效 |
365
- | `UNAUTHORIZED` | 未授权 |
366
- | `NETWORK_ERROR` | 网络错误 |
367
- | `UNKNOWN_ERROR` | 未知错误 |
368
-
369
- ### Error Handling Example
731
+ ### Vue 3
370
732
 
371
- ```typescript
372
- import { PaymentCheckoutClient, isCheckoutPaymentError } from '@seaverse/payment-sdk';
373
-
374
- try {
375
- await checkoutClient.checkout({
376
- productId: 'pkg_starter',
377
- onError: (error) => {
378
- console.error('Payment error:', error.code, error.message);
379
-
380
- // 检查业务错误码
381
- if (error.bizCode === 4004) {
382
- alert('余额不足,请充值后重试');
383
- }
733
+ ```vue
734
+ <script setup lang="ts">
735
+ import { ref } from 'vue';
736
+ import { CreditPackageModal } from '@seaverse/payment-sdk';
737
+
738
+ const showModal = () => {
739
+ const modal = new CreditPackageModal({
740
+ sdkConfig: {
741
+ environment: import.meta.env.DEV ? 'development' : 'production',
742
+ countryCode: 'SG',
743
+ accountToken: userToken.value,
744
+ },
745
+ onPaymentSuccess: (orderId, transactionId) => {
746
+ console.log('支付成功', { orderId, transactionId });
747
+ // 刷新用户数据
384
748
  },
385
749
  });
386
- } catch (error) {
387
- if (isCheckoutPaymentError(error)) {
388
- // 处理支付相关错误
389
- console.error('Checkout error:', error.code);
390
- } else {
391
- // 处理其他错误
392
- console.error('Unknown error:', error);
393
- }
750
+ modal.open();
751
+ };
752
+ </script>
753
+
754
+ <template>
755
+ <button @click="showModal">购买积分</button>
756
+ </template>
757
+ ```
758
+
759
+ ### React
760
+
761
+ ```tsx
762
+ import { CreditPackageModal } from '@seaverse/payment-sdk';
763
+
764
+ function PurchaseButton() {
765
+ const handlePurchase = () => {
766
+ const modal = new CreditPackageModal({
767
+ sdkConfig: {
768
+ environment: process.env.NODE_ENV === 'development' ? 'development' : 'production',
769
+ countryCode: 'SG',
770
+ accountToken: getUserToken(),
771
+ },
772
+ onPaymentSuccess: (orderId, transactionId) => {
773
+ console.log('支付成功', { orderId, transactionId });
774
+ // 刷新用户数据
775
+ },
776
+ });
777
+ modal.open();
778
+ };
779
+
780
+ return <button onClick={handlePurchase}>购买积分</button>;
394
781
  }
395
782
  ```
396
783
 
397
- ## Test Cards (Development)
784
+ ---
785
+
786
+ ## 📝 TypeScript 支持
787
+
788
+ SDK 包含完整的 TypeScript 类型定义:
789
+
790
+ ```typescript
791
+ import type {
792
+ // Modal 相关
793
+ CreditPackageModalOptions,
794
+ GenericPackageModalOptions,
795
+ GenericPackage,
796
+ PurchaseSuccessData,
797
+
798
+ // 配置相关
799
+ PaymentSDKConfig,
800
+ Environment,
801
+ EnvironmentConfig,
802
+
803
+ // 积分相关
804
+ CreditDetailResponse,
805
+ CreditTransaction,
806
+ CreditPoolType,
807
+
808
+ // 订阅相关
809
+ CurrentSubscription,
810
+ ActiveSubscription,
811
+
812
+ // 订单相关
813
+ OrderStatus,
814
+ OrderStatusResponse,
815
+ } from '@seaverse/payment-sdk';
816
+ ```
817
+
818
+ ---
819
+
820
+ ## 🔗 相关链接
821
+
822
+ - 📦 [NPM Package](https://www.npmjs.com/package/@seaverse/payment-sdk)
823
+ - 🐙 [GitHub Repository](https://github.com/SeaVerseAI/sv-sdk)
824
+ - 📖 [API Documentation](https://github.com/SeaVerseAI/sv-sdk/tree/main/packages/payment-sdk)
825
+ - 🐛 [Issue Tracker](https://github.com/SeaVerseAI/sv-sdk/issues)
826
+
827
+ ---
828
+
829
+ ## 📄 许可证
830
+
831
+ MIT License
832
+
833
+ ---
834
+
835
+ ## 🤝 贡献
398
836
 
399
- | Field | Value |
400
- |-------|-------|
401
- | Card Number | `4212345678910006` |
402
- | Expiry | `03/30` |
403
- | CVC | `737` |
404
- | 3DS Password | `password` |
837
+ 欢迎提交 Issue Pull Request!
405
838
 
406
- ## License
839
+ ---
407
840
 
408
- MIT
841
+ **更新日期**: 2026-01-31
842
+ **SDK 版本**: v0.8.0