React SDK
Payve React SDK 集成指南,提供 React 组件和 Hooks 来简化加密货币支付集成
9 分钟阅读
更新于 2025/8/13
SDKReact组件Hooks
Payve React SDK 专为 React 应用程序设计,提供了声明式组件和自定义 Hooks,让加密货币支付集成变得简单直观。
特性概览
React 原生
专为 React 设计的组件和 Hooks
高度可定制
支持主题定制和自定义样式
响应式
完美适配移动端和桌面端
安装
npm install @payve/react-sdk或者使用 yarn:
yarn add @payve/react-sdk快速开始
1. 配置 Provider
首先在应用的根组件包装 PayveProvider:
import React from 'react';
import { PayveProvider } from '@payve/react-sdk';
import App from './App';
function Root() {
return (
<PayveProvider
apiKey="pk_live_your_api_key_here"
environment="production"
currency="USDT"
network="TRON"
locale="zh"
>
<App />
</PayveProvider>
);
}
export default Root;JSX
代码已折叠
共 19 行
2. 使用支付按钮组件
import React from 'react';
import { PayveButton } from '@payve/react-sdk';
function ProductPage() {
const handlePaymentSuccess = (result) => {
console.log('支付成功:', result);
// 处理支付成功逻辑
};
const handlePaymentError = (error) => {
console.error('支付失败:', error);
// 处理支付失败逻辑
};
return (
<div>
<h1>高级会员</h1>
<p>价格: $99.99 USDT</p>
<PayveButton
amount="99.99"
description="高级会员订阅"
onSuccess={handlePaymentSuccess}
onError={handlePaymentError}
metadata={{
productId: 'premium_subscription',
userId: 'user_123'
}}
>
立即购买
</PayveButton>
</div>
);
}JSX
代码已折叠
共 34 行
组件 API
PayveProvider
用于提供全局配置的 Context Provider。
Props:
| 属性 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
apiKey | string | ✅ | - | API 密钥 |
environment | string | ❌ | 'production' | 环境 |
currency | string | ❌ | 'USDT' | 默认币种 |
network | string | ❌ | 'TRON' | 默认网络 |
locale | string | ❌ | 'zh' | 界面语言 |
theme | object | ❌ | - | 主题配置 |
PayveButton
快速集成的支付按钮组件。
Props:
| 属性 | 类型 | 必填 | 说明 |
|---|---|---|---|
amount | string | ✅ | 支付金额 |
currency | string | ❌ | 币种,覆盖 Provider 设置 |
network | string | ❌ | 网络,覆盖 Provider 设置 |
description | string | ❌ | 订单描述 |
metadata | object | ❌ | 自定义元数据 |
disabled | boolean | ❌ | 是否禁用 |
loading | boolean | ❌ | 是否显示加载状态 |
children | ReactNode | ❌ | 按钮文本 |
className | string | ❌ | 自定义样式类 |
style | object | ❌ | 内联样式 |
onSuccess | function | ❌ | 支付成功回调 |
onError | function | ❌ | 支付失败回调 |
onCancel | function | ❌ | 支付取消回调 |
onExpire | function | ❌ | 支付过期回调 |
PayveModal
弹窗式支付组件。
import { PayveModal } from '@payve/react-sdk';
function CheckoutPage() {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<button onClick={() => setIsOpen(true)}>
打开支付
</button>
<PayveModal
isOpen={isOpen}
onClose={() => setIsOpen(false)}
amount="100.00"
description="商品购买"
onSuccess={(result) => {
console.log('支付成功:', result);
setIsOpen(false);
}}
/>
</div>
);
}JSX
代码已折叠
共 24 行
PayveForm
完整的支付表单组件。
import { PayveForm } from '@payve/react-sdk';
function CustomCheckout() {
return (
<PayveForm
amount="50.00"
showCurrencySelector={true}
showNetworkSelector={true}
showMetadataForm={true}
onSuccess={(result) => console.log('支付成功:', result)}
onError={(error) => console.error('支付失败:', error)}
/>
);
}JSX
代码已折叠
共 14 行
Hooks API
usePayve
获取 Payve 实例和支付方法。
import { usePayve } from '@payve/react-sdk';
function CustomComponent() {
const { payve, createPayment, isLoading, error } = usePayve();
const handleCustomPayment = async () => {
try {
const payment = await createPayment({
amount: '100.00',
description: '自定义支付'
});
console.log('创建成功:', payment);
} catch (err) {
console.error('创建失败:', err);
}
};
return (
<button onClick={handleCustomPayment} disabled={isLoading}>
{isLoading ? '创建中...' : '创建支付'}
</button>
);
}JSX
代码已折叠
共 23 行
usePayment
管理单个支付的状态。
import { usePayment } from '@payve/react-sdk';
function PaymentTracker({ paymentId }) {
const { payment, isLoading, error, refresh } = usePayment(paymentId);
if (isLoading) return <div>加载中...</div>;
if (error) return <div>错误: {error.message}</div>;
return (
<div>
<h3>支付状态: {payment?.status}</h3>
<p>金额: {payment?.amount} {payment?.currency}</p>
<button onClick={refresh}>刷新状态</button>
</div>
);
}JSX
代码已折叠
共 16 行
usePaymentStatus
实时监听支付状态变化。
import { usePaymentStatus } from '@payve/react-sdk';
function RealTimeStatus({ paymentId }) {
const status = usePaymentStatus(paymentId);
useEffect(() => {
if (status === 'paid') {
// 支付成功的处理
showSuccessNotification();
}
}, [status]);
return <div>当前状态: {status}</div>;
}JSX
代码已折叠
共 14 行
完整示例
电商产品页
import React, { useState } from 'react';
import {
PayveProvider,
PayveButton,
usePayve
} from '@payve/react-sdk';
// 产品组件
function Product({ product }) {
const [quantity, setQuantity] = useState(1);
const [isProcessing, setIsProcessing] = useState(false);
const handlePaymentSuccess = (result) => {
setIsProcessing(false);
// 显示成功消息
alert('支付成功!订单正在处理中...');
// 发送到后端确认
fetch('/api/orders/confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
paymentId: result.id,
productId: product.id,
quantity
})
});
};
const handlePaymentError = (error) => {
setIsProcessing(false);
alert(`支付失败: ${error.message}`);
};
const totalAmount = (product.price * quantity).toFixed(2);
return (
<div className="product-card">
<img src={product.image} alt={product.name} />
<h2>{product.name}</h2>
<p>{product.description}</p>
<div className="price">${product.price} USDT</div>
<div className="quantity-selector">
<label>数量:</label>
<input
type="number"
min="1"
value={quantity}
onChange={(e) => setQuantity(Number(e.target.value))}
/>
</div>
<div className="total">
总计: ${totalAmount} USDT
</div>
<PayveButton
amount={totalAmount}
description={`${product.name} x${quantity}`}
metadata={{
productId: product.id,
productName: product.name,
quantity,
customerId: 'user_123'
}}
loading={isProcessing}
onSuccess={handlePaymentSuccess}
onError={handlePaymentError}
style={{
width: '100%',
padding: '12px 24px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '8px',
fontSize: '16px',
cursor: 'pointer'
}}
>
{isProcessing ? '处理中...' : '立即购买'}
</PayveButton>
</div>
);
}
// 主应用
function EcommerceApp() {
const products = [
{
id: 1,
name: '高级会员',
description: '解锁所有高级功能',
price: 99.99,
image: '/images/premium.jpg'
},
{
id: 2,
name: 'API 积分包',
description: '10,000 次 API 调用',
price: 49.99,
image: '/images/api-credits.jpg'
}
];
return (
<PayveProvider
apiKey="pk_live_your_api_key_here"
environment="production"
currency="USDT"
network="TRON"
locale="zh"
theme={{
primaryColor: '#007bff',
borderRadius: '8px'
}}
>
<div className="app">
<header>
<h1>我的商店</h1>
</header>
<main>
<div className="products-grid">
{products.map(product => (
<Product key={product.id} product={product} />
))}
</div>
</main>
</div>
</PayveProvider>
);
}
export default EcommerceApp;JSX
代码已折叠
共 134 行
自定义支付流程
import React, { useState, useEffect } from 'react';
import { usePayve, usePaymentStatus } from '@payve/react-sdk';
function CustomPaymentFlow() {
const [step, setStep] = useState('select'); // select -> payment -> status
const [selectedPlan, setSelectedPlan] = useState(null);
const [currentPayment, setCurrentPayment] = useState(null);
const { createPayment, isLoading } = usePayve();
const paymentStatus = usePaymentStatus(currentPayment?.id);
const plans = [
{ id: 'basic', name: '基础版', price: '9.99', features: ['功能 A', '功能 B'] },
{ id: 'pro', name: '专业版', price: '19.99', features: ['功能 A', '功能 B', '功能 C'] },
{ id: 'enterprise', name: '企业版', price: '49.99', features: ['所有功能', '优先支持'] }
];
const handlePlanSelect = async (plan) => {
setSelectedPlan(plan);
try {
const payment = await createPayment({
amount: plan.price,
description: `${plan.name}订阅`,
metadata: {
planId: plan.id,
planName: plan.name
}
});
setCurrentPayment(payment);
setStep('payment');
} catch (error) {
console.error('创建支付失败:', error);
alert('创建支付失败,请重试');
}
};
useEffect(() => {
if (paymentStatus === 'paid') {
setStep('success');
} else if (paymentStatus === 'failed' || paymentStatus === 'expired') {
setStep('select');
setCurrentPayment(null);
alert('支付失败,请重新选择');
}
}, [paymentStatus]);
const renderPlanSelection = () => (
<div className="plan-selection">
<h2>选择订阅计划</h2>
<div className="plans-grid">
{plans.map(plan => (
<div key={plan.id} className="plan-card">
<h3>{plan.name}</h3>
<div className="price">${plan.price}/月</div>
<ul>
{plan.features.map(feature => (
<li key={feature}>{feature}</li>
))}
</ul>
<button
onClick={() => handlePlanSelect(plan)}
disabled={isLoading}
>
选择此计划
</button>
</div>
))}
</div>
</div>
);
const renderPaymentStep = () => (
<div className="payment-step">
<h2>支付 {selectedPlan?.name}</h2>
<div className="payment-info">
<p>金额: ${selectedPlan?.price} USDT</p>
<p>状态: {paymentStatus || '待支付'}</p>
</div>
{currentPayment && (
<div className="qr-code">
<img src={currentPayment.qrCode} alt="支付二维码" />
<p>请使用支持的钱包扫描二维码完成支付</p>
<div className="payment-address">
<label>或转账到地址:</label>
<input
readOnly
value={currentPayment.address}
onClick={(e) => e.target.select()}
/>
</div>
</div>
)}
<button onClick={() => {
setStep('select');
setCurrentPayment(null);
}}>
重新选择
</button>
</div>
);
const renderSuccessStep = () => (
<div className="success-step">
<h2>🎉 支付成功!</h2>
<p>感谢您订阅 {selectedPlan?.name}</p>
<p>您的账户已升级,请刷新页面查看新功能。</p>
<button onClick={() => window.location.reload()}>
刷新页面
</button>
</div>
);
return (
<div className="custom-payment-flow">
{step === 'select' && renderPlanSelection()}
{step === 'payment' && renderPaymentStep()}
{step === 'success' && renderSuccessStep()}
</div>
);
}JSX
代码已折叠
共 123 行
主题定制
预设主题
import { PayveProvider, themes } from '@payve/react-sdk';
// 使用深色主题
<PayveProvider theme={themes.dark} ...>
<App />
</PayveProvider>
// 使用简约主题
<PayveProvider theme={themes.minimal} ...>
<App />
</PayveProvider>JSX
代码已折叠
共 11 行
自定义主题
const customTheme = {
primaryColor: '#6366f1',
secondaryColor: '#8b5cf6',
backgroundColor: '#ffffff',
surfaceColor: '#f8fafc',
textColor: '#1e293b',
textSecondaryColor: '#64748b',
borderColor: '#e2e8f0',
borderRadius: '12px',
fontFamily: '"Inter", system-ui, sans-serif',
fontSize: '14px',
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)',
// 组件特定样式
button: {
padding: '12px 24px',
fontSize: '16px',
fontWeight: '600',
borderRadius: '8px',
transition: 'all 0.2s ease'
},
modal: {
borderRadius: '16px',
maxWidth: '480px',
padding: '24px'
},
qrCode: {
size: 240,
margin: '16px',
borderRadius: '8px'
}
};
<PayveProvider theme={customTheme} ...>
<App />
</PayveProvider>JSX
代码已折叠
共 38 行
TypeScript 支持
SDK 完全支持 TypeScript,提供完整的类型定义:
import React from 'react';
import {
PayveProvider,
PayveButton,
PaymentResult,
PaymentError
} from '@payve/react-sdk';
interface ProductProps {
id: string;
name: string;
price: string;
}
const Product: React.FC<ProductProps> = ({ id, name, price }) => {
const handleSuccess = (result: PaymentResult) => {
console.log('Payment successful:', result);
};
const handleError = (error: PaymentError) => {
console.error('Payment failed:', error);
};
return (
<PayveButton
amount={price}
description={`Purchase ${name}`}
onSuccess={handleSuccess}
onError={handleError}
metadata={{ productId: id }}
>
Buy Now
</PayveButton>
);
};TYPESCRIPT
代码已折叠
共 35 行
性能优化
代码分割
import React, { lazy, Suspense } from 'react';
// 懒加载支付组件
const PayveModal = lazy(() =>
import('@payve/react-sdk').then(module => ({ default: module.PayveModal }))
);
function App() {
return (
<Suspense fallback={<div>加载中...</div>}>
<PayveModal />
</Suspense>
);
}JSX
代码已折叠
共 14 行
记忆化组件
import React, { memo } from 'react';
import { PayveButton } from '@payve/react-sdk';
const MemoizedPayveButton = memo(PayveButton);
// 使用记忆化组件避免不必要的重渲染
function ProductList({ products }) {
return (
<div>
{products.map(product => (
<MemoizedPayveButton
key={product.id}
amount={product.price}
description={product.name}
/>
))}
</div>
);
}JSX
代码已折叠
共 19 行
测试
单元测试示例
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import { PayveProvider, PayveButton } from '@payve/react-sdk';
// 模拟支付成功
const mockPayve = {
createPayment: jest.fn().mockResolvedValue({
id: 'pay_test_123',
status: 'pending'
})
};
jest.mock('@payve/react-sdk', () => ({
...jest.requireActual('@payve/react-sdk'),
usePayve: () => ({ payve: mockPayve })
}));
test('PayveButton 创建支付并调用回调', async () => {
const onSuccess = jest.fn();
render(
<PayveProvider apiKey="test_key">
<PayveButton
amount="100.00"
onSuccess={onSuccess}
>
Pay Now
</PayveButton>
</PayveProvider>
);
const button = screen.getByText('Pay Now');
fireEvent.click(button);
await waitFor(() => {
expect(mockPayve.createPayment).toHaveBeenCalledWith({
amount: '100.00'
});
});
});JSX
代码已折叠
共 40 行
相关文档
- JavaScript SDK - 原生 JavaScript 集成
- 配置选项 - 详细配置说明
- Vue SDK - Vue.js 集成指南
- 支付 API - 后端 API 文档
