@dj-test/payment-sdk
v1.0.99
Published
Payment SDK for blockchain-based payment system
Downloads
1,200
Maintainers
Readme
Payment SDK
wagmi 기반의 결제 SDK로, 두 가지 결제 방식을 지원합니다.
주요 기능
1. Pay with Wallet (지갑 연결 결제)
- ✅ 지갑 설치 여부 자동 감지
- ✅ 다양한 지갑 지원 (MetaMask, WalletConnect, Coinbase Wallet)
- ✅ 지갑 선택 UI 제공
- ✅ 실시간 트랜잭션 확인
- ✅ 네트워크 자동 전환
- ✅ 송금 주소, 금액, 코인 설정
2. Pay with Address (주소 결제)
- ✅ QR 코드 생성
- ✅ 주소 복사 기능
- ✅ 만료 시간 표시
- ✅ 결제 안내문
Installation
pnpm add payment-sdk wagmi viem @tanstack/react-queryQuick Start
1. Wrap your app with Providers
import { PaymentProvider, WalletProvider } from 'payment-sdk';
function App() {
return (
<WalletProvider>
<PaymentProvider
apiKey="your-api-key"
environment="production"
baseUrl={process.env.NEXT_PUBLIC_API_URL}
redirectUrl="https://yoursite.com/payment/success"
webhookUrl="https://yoursite.com/api/webhook/payment"
>
<YourApp />
</PaymentProvider>
</WalletProvider>
);
}2. Pay with Wallet
import { PayWithWallet } from 'payment-sdk';
function CheckoutPage() {
return (
<PayWithWallet
toAddress="0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
amount="100"
coinId="USDC"
chainId={11155111} // Sepolia testnet
onSuccess={(txHash) => console.log('Success:', txHash)}
onError={(error) => console.error('Error:', error)}
/>
);
}3. Pay with Address
import { PayWithAddress } from 'payment-sdk';
function PaymentPage() {
return (
<PayWithAddress
walletAddress="0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
amount="100"
coinId="USDC"
chainId={11155111}
publicOrderId="order-uuid"
expiresAt="2025-01-04T15:30:00"
/>
);
}4. Use Wallet Hook (Legacy - EVM Only)
import { useWallet } from 'payment-sdk';
function WalletComponent() {
const {
wallet,
isConnected,
connect,
disconnect,
connectors,
sendPayment,
} = useWallet();
return (
<div>
{!isConnected ? (
<button onClick={() => connect('injected')}>
Connect Wallet
</button>
) : (
<>
<p>Connected: {wallet?.address}</p>
<button onClick={disconnect}>Disconnect</button>
</>
)}
</div>
);
}5. Use Wallet Adapter Hook (Multi-chain Support)
import { useWalletAdapter, WalletTypes } from 'payment-sdk';
function MultiChainWallet() {
const {
wallet,
isConnected,
connect,
disconnect,
chainType,
balance,
sendPayment,
} = useWalletAdapter();
const connectEvm = () => {
connect(WalletTypes.EVM, 'injected'); // MetaMask
};
const connectTron = () => {
connect(WalletTypes.TRON, 'tronlink'); // TronLink
};
return (
<div>
{!isConnected ? (
<>
<button onClick={connectEvm}>Connect MetaMask</button>
<button onClick={connectTron}>Connect TronLink</button>
</>
) : (
<>
<p>Chain: {chainType}</p>
<p>Address: {wallet?.address}</p>
<p>Balance: {balance?.formatted} {balance?.symbol}</p>
<button onClick={disconnect}>Disconnect</button>
</>
)}
</div>
);
}6. Tron Payment Example
import { PayWithWallet } from 'payment-sdk';
function TronPayment() {
return (
<PayWithWallet
toAddress="TXYZoPEU" // Tron address (starts with T)
amount="100"
coinId="USDT"
chainId="mainnet" // Tron mainnet
onSuccess={(txHash) => console.log('Tron TX:', txHash)}
onError={(error) => console.error('Error:', error)}
/>
);
}7. Auto-detect Chain by Address
import { useWalletAdapter } from 'payment-sdk';
function AutoDetectPayment({ depositAddress }: { depositAddress: string }) {
// Automatically selects EVM or Tron adapter based on address format
// 0x... -> EVM adapter
// T... -> Tron adapter
const adapter = useWalletAdapter({ depositAddress });
return (
<div>
<p>Detected Chain: {adapter.chainType}</p>
<button onClick={() => adapter.connect(adapter.adapterType!, 'injected')}>
Connect Wallet
</button>
</div>
);
}Supported Networks
EVM Chains
- Ethereum Mainnet (1)
- Sepolia Testnet (11155111)
- Polygon Mainnet (137)
- Polygon Amoy Testnet (80002)
- Base Mainnet (8453)
- Base Sepolia (84532)
Tron Networks
- Tron Mainnet (
mainnet) - Tron Shasta Testnet (
shasta) - Tron Nile Testnet (
nile)
Supported Wallets
EVM Wallets
- Injected Wallets: MetaMask, Trust Wallet, Brave Wallet
- Desktop: Browser extensions (MetaMask, etc.)
- Mobile Web: In-app browsers + deep links (MetaMask app)
Tron Wallets
- TronLink: Official Tron wallet extension
- TronLink Pro: Mobile wallet with WalletConnect support
Mobile Web Support
SDK follows Daimo Pay approach for mobile web:
- ✅ In-app browser detection: Auto-detects MetaMask in-app browser
- ✅ Deep link support: Opens MetaMask app from regular mobile browsers
- ✅ No WalletConnect needed: Lightweight solution without WC dependency
Mobile Web Flow
Option 1: MetaMask In-App Browser (Recommended)
User opens your site in MetaMask app browser
→ SDK detects window.ethereum
→ Direct wallet connection worksOption 2: Regular Mobile Browser
import { getConnectionStrategy, openMetaMaskDeepLink } from 'payment-sdk';
function ConnectButton() {
const strategy = getConnectionStrategy();
const handleConnect = () => {
if (strategy.type === 'deeplink') {
// Opens MetaMask app
openMetaMaskDeepLink();
} else if (strategy.type === 'injected') {
// Use wagmi connect
connect();
}
};
return <button onClick={handleConnect}>{strategy.message}</button>;
}Mobile Utilities
import {
isMobile,
isMetaMaskBrowser,
isMetaMaskAvailable,
shouldUseDeepLink,
} from 'payment-sdk';
// Check if on mobile device
const mobile = isMobile();
// Check if in MetaMask in-app browser
const inMetaMask = isMetaMaskBrowser();
// Check if MetaMask is available (extension or in-app)
const hasMetaMask = isMetaMaskAvailable();
// Determine if should use deep link
const useDeepLink = shouldUseDeepLink();API Reference
PaymentProvider Props
| Prop | Type | Required | Description | |------|------|----------|-------------| | apiKey | string | Yes | Your API key | | environment | 'production' | 'sandbox' | Yes | Environment | | baseUrl | string | No | Custom API URL | | redirectUrl | string | Yes | Success redirect URL | | webhookUrl | string | Yes | Webhook endpoint URL | | timeout | number | No | Request timeout (default: 30000ms) |
usePayment Hook
Returns:
createOrder(params)- Create a new payment orderisLoading- Loading stateerror- Error objectorder- Created order objecterrorMessage- User-friendly error message
useOrder Hook
const { order, isLoading, error, refetch } = useOrder(publicOrderId);Returns order details and allows manual refresh.
Validation Utils
import { validation } from '@your-company/payment-sdk';
// Validate withdrawal address
const result = validation.validateWithdrawalAddress(fromAddress, toAddress);
if (!result.valid) {
console.error(result.error);
}
// Validate Ethereum address format
const isValid = validation.isValidEthereumAddress(address);Security Features
1. Order ID Security
- Uses UUID for public order IDs (unpredictable)
- Internal database IDs remain hidden
2. Withdrawal Validation
- Prevents sending to your own wallet address
- Validates address format
- Validates amount
3. API Security
- HTTPS required for production
- API key authentication
- Webhook signature verification
Payment Flow
- Create Order: Merchant calls
createOrder() - Redirect: User redirected to payment page
- Payment: User sends crypto to wallet address
- Monitor: System monitors blockchain for deposit
- Complete: Webhook sent to merchant, user redirected to success page
Environment Variables
NEXT_PUBLIC_API_URL=https://api.yourpayment.com
NEXT_PUBLIC_API_KEY=your-api-key-here
NEXT_PUBLIC_REDIRECT_URL=https://yoursite.com/payment/success
NEXT_PUBLIC_WEBHOOK_URL=https://yoursite.com/api/webhook/payment
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=your-walletconnect-project-idGet WalletConnect Project ID at WalletConnect Cloud
Examples
See the examples directory for complete integration examples.
Support
- Documentation: https://docs.yourpayment.com
- Email: [email protected]
- GitHub: https://github.com/yourcompany/payment-sdk
License
MIT
