SDK 配置选项
Payve SDK 的详细配置选项和最佳实践指南
9 分钟阅读
更新于 2025/8/13
SDK配置定制设置
本文档详细介绍了 Payve SDK 的所有配置选项,帮助您根据业务需求进行定制。
基础配置
初始化选项
所有 Payve SDK 都支持以下基础配置选项:
const config = {
// 必填项
apiKey: 'pk_live_your_api_key_here',
// 环境配置
environment: 'production', // 'production' | 'sandbox'
baseURL: 'https://api.payve.io', // 自定义 API 端点
// 默认支付设置
currency: 'USDT',
network: 'TRON',
// 界面设置
locale: 'zh',
theme: {/* 主题配置 */},
// 行为设置
autoConnect: true,
retryOnFailure: true,
debug: false
};JAVASCRIPT
代码已折叠
共 21 行
环境配置
生产环境
const payve = new Payve({
apiKey: 'pk_live_your_live_key',
environment: 'production',
debug: false
});沙盒环境
const payve = new Payve({
apiKey: 'pk_test_your_test_key',
environment: 'sandbox',
debug: true
});自定义环境
const payve = new Payve({
apiKey: 'pk_dev_your_dev_key',
baseURL: 'https://dev-api.payve.io',
wsURL: 'wss://dev-ws.payve.io',
debug: true
});支付配置
支持的币种和网络
const supportedAssets = {
'BTC': ['Bitcoin'],
'ETH': ['Ethereum'],
'USDT': ['TRON', 'Ethereum', 'BSC', 'Polygon'],
'USDC': ['Ethereum', 'BSC', 'Polygon', 'Solana'],
'BNB': ['BSC'],
'SOL': ['Solana']
};
// 配置默认币种和网络
const payve = new Payve({
apiKey: 'pk_live_xxx',
currency: 'USDT',
network: 'TRON',
// 允许的币种列表
allowedCurrencies: ['USDT', 'USDC', 'BTC'],
// 网络优先级
networkPriority: {
'USDT': ['TRON', 'BSC', 'Ethereum'],
'USDC': ['Polygon', 'BSC', 'Ethereum']
}
});JAVASCRIPT
代码已折叠
共 24 行
金额和精度设置
const payve = new Payve({
apiKey: 'pk_live_xxx',
// 金额设置
minimumAmount: {
'USDT': '1.00',
'BTC': '0.0001',
'ETH': '0.001'
},
maximumAmount: {
'USDT': '10000.00',
'BTC': '1.00',
'ETH': '10.00'
},
// 精度设置
decimalPlaces: {
'USDT': 2,
'BTC': 8,
'ETH': 6
},
// 金额格式化
formatCurrency: true,
currencySymbol: {
'USDT': '$',
'BTC': '₿',
'ETH': 'Ξ'
}
});JAVASCRIPT
代码已折叠
共 31 行
主题配置
预设主题
import { themes } from '@payve/sdk';
// 使用内置主题
const payve = new Payve({
apiKey: 'pk_live_xxx',
theme: themes.dark
});
// 可用的预设主题
const availableThemes = {
light: themes.light, // 浅色主题
dark: themes.dark, // 深色主题
minimal: themes.minimal, // 简约主题
colorful: themes.colorful // 彩色主题
};JAVASCRIPT
代码已折叠
共 15 行
自定义主题
const customTheme = {
// 基础颜色
colors: {
primary: '#6366f1',
secondary: '#8b5cf6',
success: '#10b981',
warning: '#f59e0b',
error: '#ef4444',
// 背景颜色
background: '#ffffff',
surface: '#f8fafc',
overlay: 'rgba(0, 0, 0, 0.5)',
// 文本颜色
text: {
primary: '#1e293b',
secondary: '#64748b',
disabled: '#94a3b8',
inverse: '#ffffff'
},
// 边框颜色
border: {
default: '#e2e8f0',
focus: '#6366f1',
error: '#ef4444'
}
},
// 字体设置
typography: {
fontFamily: '"Inter", system-ui, sans-serif',
fontSize: {
xs: '12px',
sm: '14px',
base: '16px',
lg: '18px',
xl: '20px',
'2xl': '24px'
},
fontWeight: {
normal: '400',
medium: '500',
semibold: '600',
bold: '700'
},
lineHeight: {
tight: '1.2',
normal: '1.5',
relaxed: '1.75'
}
},
// 间距设置
spacing: {
xs: '4px',
sm: '8px',
md: '16px',
lg: '24px',
xl: '32px',
'2xl': '48px'
},
// 圆角设置
borderRadius: {
sm: '4px',
md: '8px',
lg: '12px',
xl: '16px',
full: '9999px'
},
// 阴影设置
shadows: {
sm: '0 1px 2px rgba(0, 0, 0, 0.05)',
md: '0 4px 6px rgba(0, 0, 0, 0.1)',
lg: '0 10px 15px rgba(0, 0, 0, 0.1)',
xl: '0 25px 50px rgba(0, 0, 0, 0.25)'
},
// 组件特定样式
components: {
button: {
borderRadius: '8px',
padding: '12px 24px',
fontSize: '16px',
fontWeight: '600',
transition: 'all 0.2s ease',
variants: {
primary: {
backgroundColor: '#6366f1',
color: '#ffffff',
'&:hover': {
backgroundColor: '#4f46e5'
}
},
secondary: {
backgroundColor: 'transparent',
color: '#6366f1',
border: '1px solid #6366f1',
'&:hover': {
backgroundColor: '#f1f5f9'
}
}
}
},
modal: {
borderRadius: '16px',
maxWidth: '480px',
padding: '24px',
backgroundColor: '#ffffff',
boxShadow: '0 25px 50px rgba(0, 0, 0, 0.25)'
},
qrCode: {
size: 240,
margin: '16px',
borderRadius: '12px',
backgroundColor: '#ffffff',
padding: '16px'
},
input: {
borderRadius: '8px',
padding: '12px 16px',
fontSize: '16px',
border: '1px solid #e2e8f0',
'&:focus': {
borderColor: '#6366f1',
outline: 'none',
boxShadow: '0 0 0 3px rgba(99, 102, 241, 0.1)'
}
}
}
};
const payve = new Payve({
apiKey: 'pk_live_xxx',
theme: customTheme
});JAVASCRIPT
代码已折叠
共 143 行
响应式主题
const responsiveTheme = {
breakpoints: {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px'
},
components: {
modal: {
'@media (max-width: 768px)': {
maxWidth: '100%',
margin: '16px',
borderRadius: '16px 16px 0 0',
position: 'fixed',
bottom: 0,
left: 0,
right: 0
}
},
qrCode: {
size: 240,
'@media (max-width: 640px)': {
size: 180
}
}
}
};JAVASCRIPT
代码已折叠
共 29 行
本地化配置
语言设置
const payve = new Payve({
apiKey: 'pk_live_xxx',
locale: 'zh', // 中文
// 或使用完整的语言代码
locale: 'zh-CN', // 简体中文
locale: 'zh-TW', // 繁体中文
locale: 'en-US', // 美式英语
locale: 'ja-JP', // 日语
locale: 'ko-KR' // 韩语
});JAVASCRIPT
代码已折叠
共 11 行
自定义文本
const customTexts = {
zh: {
// 按钮文本
buttons: {
pay: '立即支付',
cancel: '取消',
retry: '重试',
confirm: '确认',
close: '关闭'
},
// 状态文本
status: {
pending: '等待支付',
confirming: '确认中',
paid: '支付成功',
failed: '支付失败',
expired: '已过期'
},
// 提示文本
messages: {
scanQR: '请使用支持的钱包扫描二维码',
copyAddress: '或复制地址到钱包',
waitingConfirmation: '等待区块链确认...',
paymentSuccess: '支付成功!',
paymentFailed: '支付失败,请重试',
orderExpired: '订单已过期,请重新下单'
},
// 错误消息
errors: {
networkError: '网络连接失败',
invalidAmount: '金额格式不正确',
insufficientBalance: '余额不足',
unsupportedCurrency: '不支持的币种'
}
}
};
const payve = new Payve({
apiKey: 'pk_live_xxx',
locale: 'zh',
texts: customTexts
});JAVASCRIPT
代码已折叠
共 45 行
货币格式化
const payve = new Payve({
apiKey: 'pk_live_xxx',
// 数字格式化选项
numberFormat: {
locale: 'zh-CN',
minimumFractionDigits: 2,
maximumFractionDigits: 8,
useGrouping: true
},
// 自定义格式化函数
formatAmount: (amount, currency) => {
if (currency === 'USDT') {
return `${parseFloat(amount).toFixed(2)}`;
}
return `${amount} ${currency}`;
}
});JAVASCRIPT
代码已折叠
共 19 行
行为配置
连接设置
const payve = new Payve({
apiKey: 'pk_live_xxx',
// WebSocket 配置
websocket: {
autoConnect: true,
reconnectAttempts: 5,
reconnectInterval: 1000,
heartbeatInterval: 30000,
// 连接事件
onOpen: () => console.log('WebSocket 连接已建立'),
onClose: () => console.log('WebSocket 连接已关闭'),
onError: (error) => console.error('WebSocket 错误:', error)
},
// HTTP 请求配置
http: {
timeout: 30000,
retryAttempts: 3,
retryDelay: 1000,
// 请求拦截器
requestInterceptor: (config) => {
console.log('发送请求:', config);
return config;
},
// 响应拦截器
responseInterceptor: (response) => {
console.log('收到响应:', response);
return response;
}
}
});JAVASCRIPT
代码已折叠
共 35 行
缓存配置
const payve = new Payve({
apiKey: 'pk_live_xxx',
cache: {
// 启用缓存
enabled: true,
// 缓存策略
strategy: 'memory', // 'memory' | 'localStorage' | 'custom'
// 缓存时间(毫秒)
ttl: {
payments: 300000, // 5 分钟
exchangeRates: 60000, // 1 分钟
networkInfo: 600000 // 10 分钟
},
// 自定义缓存实现
customCache: {
get: (key) => {
return localStorage.getItem(`payve_${key}`);
},
set: (key, value, ttl) => {
const item = {
value,
expiry: Date.now() + ttl
};
localStorage.setItem(`payve_${key}`, JSON.stringify(item));
},
delete: (key) => {
localStorage.removeItem(`payve_${key}`);
}
}
}
});JAVASCRIPT
代码已折叠
共 35 行
日志配置
const payve = new Payve({
apiKey: 'pk_live_xxx',
logging: {
// 日志级别
level: 'info', // 'debug' | 'info' | 'warn' | 'error' | 'none'
// 日志输出
output: 'console', // 'console' | 'custom'
// 自定义日志处理器
customLogger: {
debug: (message, data) => console.debug('[Payve Debug]', message, data),
info: (message, data) => console.info('[Payve Info]', message, data),
warn: (message, data) => console.warn('[Payve Warn]', message, data),
error: (message, data) => console.error('[Payve Error]', message, data)
},
// 敏感信息过滤
sensitiveFields: ['apiKey', 'privateKey', 'signature'],
// 日志格式化
formatter: (level, message, data) => {
return {
timestamp: new Date().toISOString(),
level,
message,
data: filterSensitiveData(data)
};
}
}
});JAVASCRIPT
代码已折叠
共 32 行
高级配置
插件系统
// 自定义插件
const analyticsPlugin = {
name: 'analytics',
install(payve) {
// 监听支付事件
payve.on('payment.created', (payment) => {
analytics.track('Payment Created', {
paymentId: payment.id,
amount: payment.amount,
currency: payment.currency
});
});
payve.on('payment.success', (payment) => {
analytics.track('Payment Success', {
paymentId: payment.id,
amount: payment.amount,
currency: payment.currency
});
});
}
};
// 使用插件
const payve = new Payve({
apiKey: 'pk_live_xxx',
plugins: [analyticsPlugin]
});JAVASCRIPT
代码已折叠
共 29 行
中间件
const payve = new Payve({
apiKey: 'pk_live_xxx',
middleware: [
// 请求中间件
{
type: 'request',
handler: async (request, next) => {
// 添加自定义头部
request.headers['X-Client-Version'] = '1.0.0';
// 请求加密
if (request.data) {
request.data = encrypt(request.data);
}
return next(request);
}
},
// 响应中间件
{
type: 'response',
handler: async (response, next) => {
// 响应解密
if (response.data) {
response.data = decrypt(response.data);
}
// 数据验证
if (!validateResponse(response.data)) {
throw new Error('Invalid response data');
}
return next(response);
}
},
// 错误处理中间件
{
type: 'error',
handler: async (error, next) => {
// 错误日志上报
errorReporting.captureException(error);
// 用户友好的错误处理
if (error.code === 'NETWORK_ERROR') {
error.message = '网络连接失败,请检查网络设置';
}
return next(error);
}
}
]
});JAVASCRIPT
代码已折叠
共 55 行
性能监控
const payve = new Payve({
apiKey: 'pk_live_xxx',
performance: {
// 启用性能监控
enabled: true,
// 监控指标
metrics: [
'api_response_time',
'websocket_latency',
'qr_code_generation_time',
'payment_confirmation_time'
],
// 性能数据回调
onMetric: (metric) => {
console.log(`Performance metric: ${metric.name} = ${metric.value}ms`);
// 发送到监控服务
analytics.track('Performance Metric', metric);
},
// 性能阈值告警
thresholds: {
api_response_time: 5000, // 5秒
websocket_latency: 1000, // 1秒
qr_code_generation_time: 2000 // 2秒
},
// 阈值超出回调
onThresholdExceeded: (metric, threshold) => {
console.warn(`Performance threshold exceeded: ${metric.name} (${metric.value}ms > ${threshold}ms)`);
}
}
});JAVASCRIPT
代码已折叠
共 36 行
配置验证
类型检查
import { PayveConfig } from '@payve/sdk';
const config: PayveConfig = {
apiKey: 'pk_live_xxx',
environment: 'production',
currency: 'USDT',
network: 'TRON',
locale: 'zh',
theme: {
colors: {
primary: '#6366f1'
}
},
websocket: {
autoConnect: true,
reconnectAttempts: 5
}
};TYPESCRIPT
代码已折叠
共 20 行
运行时验证
function validateConfig(config) {
const errors = [];
// 必填字段检查
if (!config.apiKey) {
errors.push('apiKey is required');
}
// API 密钥格式检查
if (config.apiKey && !config.apiKey.startsWith('pk_')) {
errors.push('Invalid API key format');
}
// 环境检查
if (config.environment && !['production', 'sandbox'].includes(config.environment)) {
errors.push('Invalid environment');
}
// 币种检查
if (config.currency && !supportedCurrencies.includes(config.currency)) {
errors.push(`Unsupported currency: ${config.currency}`);
}
if (errors.length > 0) {
throw new Error(`Configuration validation failed: ${errors.join(', ')}`);
}
return true;
}
// 使用验证
try {
validateConfig(config);
const payve = new Payve(config);
} catch (error) {
console.error('Configuration error:', error.message);
}JAVASCRIPT
代码已折叠
共 37 行
最佳实践
1. 环境管理
// 使用环境变量
const config = {
apiKey: process.env.PAYVE_API_KEY,
environment: process.env.NODE_ENV === 'production' ? 'production' : 'sandbox',
debug: process.env.NODE_ENV !== 'production'
};
// 配置文件分离
const devConfig = {
apiKey: 'pk_test_xxx',
environment: 'sandbox',
debug: true
};
const prodConfig = {
apiKey: 'pk_live_xxx',
environment: 'production',
debug: false
};
const config = process.env.NODE_ENV === 'production' ? prodConfig : devConfig;JAVASCRIPT
代码已折叠
共 21 行
2. 安全配置
// 不要在前端暴露敏感信息
const payve = new Payve({
apiKey: 'pk_live_xxx', // 只使用公钥
// 安全设置
security: {
validateOrigin: true,
allowedOrigins: ['https://yourdomain.com'],
// CSP 设置
contentSecurityPolicy: {
'connect-src': ['https://api.payve.io', 'wss://ws.payve.io'],
'img-src': ['https://api.payve.io']
}
}
});JAVASCRIPT
代码已折叠
共 16 行
3. 性能优化
const payve = new Payve({
apiKey: 'pk_live_xxx',
// 性能优化设置
optimization: {
// 懒加载组件
lazyLoad: true,
// 预加载关键资源
preload: ['qr-generator', 'websocket'],
// 启用压缩
compression: true,
// 缓存策略
cache: {
strategy: 'aggressive',
maxAge: 300000 // 5分钟
}
}
});JAVASCRIPT
代码已折叠
共 21 行
相关文档
- JavaScript SDK - JavaScript 集成指南
- React SDK - React 集成指南
- 支付 API - 后端 API 文档
- 错误处理 - 错误码说明
