bnksy-sdk
Version:
438 lines (345 loc) • 11.9 kB
Markdown
# bnksy-sdk
Complete SDK for integrating Banksy payments into your application.
## Features
- 🪙 **Crypto Payments** - Accept ETH, USDT, USDC, BNB, POL, TRX, BTC
- 💵 **PIX Payments** - Accept PIX payments (Brazil)
- 🔄 **Fiat-to-Crypto** - Accept fiat and convert to crypto automatically
- 💸 **Crypto Payouts** - Process USDT payouts via smart contract
- 💱 **Fiat-to-Crypto Payouts** - Convert fiat (USD, EUR, BRL) to crypto and send
- 💰 **PIX Payouts** - Send money via PIX to recipients in Brazil
- 🏦 **Crypto Withdrawals** - Withdraw crypto to external wallets
## Installation
```bash
npm install bnksy-sdk
```
## Quick Start
```javascript
import { BanksySDK } from 'bnksy-sdk';
const banksy = new BanksySDK({
apiKey: 'your-api-key' // clientKey or clientSecret from dashboard
});
// Check connection
const status = await banksy.checkStatus();
console.log('Connected:', status);
```
## Creating Payments
### Crypto Payment
```javascript
const payment = await banksy.createPayment({
amount: 100, // 100 USDT
crypto: {
tokenName: 'USDT',
blockchainName: 'eth'
},
successCallback: 'https://yoursite.com/success',
failureCallback: 'https://yoursite.com/failure',
externalClientId: 'order-123'
});
console.log('Payment address:', payment.payment.address);
console.log('QR Code:', payment.payment.qrCode);
```
### PIX Payment (Brazil)
```javascript
const payment = await banksy.createPayment({
amount: 10,
currency: 'BRL',
successCallback: 'https://your-app.com/success',
failureCallback: 'https://your-app.com/failure',
customerName: 'Philip William',
customerEmail: 'philip@email.com',
customerPhone: '11998589706',
externalClientId: 'YOUR-REFERENCE-ID',
details: {
documentNumber: '54944801009', // CPF
birthday: '1990-01-01',
orderNumber: '212912'
}
});
console.log('PIX Code:', payment.payment.pixCode);
```
### Fiat-to-Crypto Payment
Accept USD/EUR and receive crypto:
```javascript
const payment = await banksy.createPayment({
fiatAmount: 50,
fiatCurrency: 'USD',
crypto: {
tokenName: 'USDT',
blockchainName: 'eth'
},
successCallback: 'https://yoursite.com/success',
failureCallback: 'https://yoursite.com/failure'
});
```
## Checking Payment Status
```javascript
// Get payment details
const payment = await banksy.getPayment('payment-id');
console.log('Status:', payment.status);
// Or just get status
const { status } = await banksy.getPaymentStatus('payment-id');
// Get multiple payments
const payments = await banksy.getPayments(['id1', 'id2', 'id3']);
// List all payments with pagination
const { payments, total } = await banksy.getAllPayments({
status: 'success',
skip: 0,
limit: 10
});
```
## Withdrawals
```javascript
const withdraw = await banksy.createWithdraw({
amount: 100,
currency: 'USDT',
address: '0x...'
});
```
## Crypto Payouts (Smart Contract)
For processing payouts via the PayoutProcessor smart contract:
```javascript
// Initialize crypto payout module with your wallet
const payout = banksy.initCryptoPayout({
privateKey: process.env.WALLET_PRIVATE_KEY
});
// Network is automatically detected from your API key:
// - Test keys (ck_test_*) -> Sepolia testnet
// - Live keys (ck_live_*) -> Ethereum mainnet
// Check your client status
const status = await payout.getClientStatus();
console.log('Active:', status.isActive);
console.log('Fee:', status.feePercentage);
// Check balance
const balance = await payout.getBalanceInfo();
console.log('USDT:', balance.usdtBalance);
console.log('Allowance:', balance.allowance);
// Approve USDT (one-time)
if (await payout.needsApproval('1000')) {
await payout.approve('10000');
}
// Process payout
const result = await payout.processPayout(
'0xRecipient...',
'100', // 100 USDT
'invoice-123'
);
console.log('Payout ID:', result.payoutId);
console.log('Fee:', result.feeAmount);
console.log('Net sent:', result.netAmount);
// Batch payouts (gas efficient)
const batch = await payout.processPayoutsBatch([
{ recipient: '0xAddr1...', amount: '100', reference: 'ref-1' },
{ recipient: '0xAddr2...', amount: '200', reference: 'ref-2' },
]);
```
## PIX Payouts (Brazil)
Send money to recipients in Brazil via PIX:
```javascript
// PIX payout module is automatically available
const { pixPayout } = banksy;
// Check account balance
const balance = await pixPayout.getBalance();
console.log('Available:', balance.available, balance.currency);
// Validate CPF before sending
const cpfCheck = await pixPayout.validateCPF('12345678901');
if (!cpfCheck.valid) {
console.error('Invalid CPF');
}
// Send money via PIX
const payout = await pixPayout.create({
amount: 100.00, // R$ 100.00
pixKey: '12345678901', // CPF, email, phone, or random key
pixKeyType: 'CPF', // 'CPF' | 'EMAIL' | 'PHONE' | 'EVP'
recipient: {
name: 'João Silva',
document: '12345678901', // CPF
birthday: '1990-01-15' // Optional
},
reference: 'payment-123' // Your internal reference
});
console.log('Payout ID:', payout.payoutId);
console.log('Status:', payout.status);
// Check payout status
const status = await pixPayout.getStatus(payout.payoutId);
console.log('Current status:', status.status);
// Get payout details
const details = await pixPayout.get(payout.payoutId);
// List all payouts
const { payouts, total } = await pixPayout.list({
status: 'completed',
skip: 0,
limit: 10
});
```
### PIX Key Types
| Type | Description | Example |
|------|-------------|---------|
| `CPF` | Brazilian tax ID | `12345678901` |
| `EMAIL` | Email address | `user@email.com` |
| `PHONE` | Phone number | `11999999999` |
| `EVP` | Random PIX key | `a1b2c3d4-e5f6-...` |
## Fiat-to-Crypto Payouts
Convert fiat currency (USD, EUR, BRL, etc.) to crypto (USDT) and send to recipients:
```javascript
// Fiat-to-crypto payout module is automatically available
const { fiatCryptoPayout } = banksy;
// Get supported currencies
const currencies = await fiatCryptoPayout.getSupportedCurrencies();
console.log('Supported fiats:', currencies.fiatCurrencies);
// [{ code: 'USD', name: 'US Dollar' }, { code: 'EUR', name: 'Euro' }, ...]
// Get current exchange rate
const rate = await fiatCryptoPayout.getExchangeRate('USD', 'USDT');
console.log('Rate:', rate.rate, `1 USDT = $${rate.rate} USD`);
// Get a quote (preview conversion)
const { quote } = await fiatCryptoPayout.getQuote({
wallet: '0xYourWallet...',
fiatAmount: 100,
fiatCurrency: 'USD'
});
console.log('You send:', quote.fiat.amount, quote.fiat.currency);
console.log('Recipient gets:', quote.netAmount, 'USDT');
console.log('Fee:', quote.fees.platformFeeAmount, 'USDT');
// Create payout (Step 1: Lock in rate)
const payout = await fiatCryptoPayout.create({
wallet: '0xYourWallet...', // Your wallet (payer)
recipient: '0xRecipient...', // Recipient wallet
fiatAmount: 100, // Amount in fiat
fiatCurrency: 'USD', // USD, EUR, GBP, BRL, etc.
reference: 'invoice-123'
});
console.log('Payout ID:', payout.payoutId);
console.log('Crypto amount:', payout.crypto.grossAmount, 'USDT');
// Prepare transaction (Step 2: Get TX data for signing)
const { transaction } = await fiatCryptoPayout.prepare(payout.payoutId, '0xYourWallet...');
// Transaction contains: to, data, gasLimit, chainId, nonce, etc.
// Sign and broadcast transaction (Step 3: Client-side with ethers.js)
// const signedTx = await wallet.signTransaction(transaction);
// const txResponse = await provider.sendTransaction(signedTx);
// Confirm payout (Step 4: Finalize)
const confirmed = await fiatCryptoPayout.confirm(payout.payoutId, 'txHash...');
console.log('Status:', confirmed.status); // 'completed'
console.log('TX Hash:', confirmed.transaction.txHash);
// List payouts
const { payouts, pagination } = await fiatCryptoPayout.list({
status: 'completed',
fiatCurrency: 'USD',
page: 1,
limit: 10
});
// Cancel pending payout
await fiatCryptoPayout.cancel(payout.payoutId);
```
### Supported Fiat Currencies
| Code | Currency |
|------|----------|
| `USD` | US Dollar |
| `EUR` | Euro |
| `GBP` | British Pound |
| `BRL` | Brazilian Real |
| `INR` | Indian Rupee |
| `AUD` | Australian Dollar |
| `CAD` | Canadian Dollar |
| `JPY` | Japanese Yen |
| `CNY` | Chinese Yuan |
| `MXN` | Mexican Peso |
## Utility Methods
```javascript
// Get available providers
const providers = await banksy.getProviders();
// Get supported crypto contracts
const contracts = await banksy.getContracts();
// Get API key info
const keyInfo = await banksy.getKeyInfo();
```
## Error Handling
```javascript
try {
const payment = await banksy.createPayment({...});
} catch (error) {
console.error('Payment failed:', error.message);
}
```
## API Reference
### BanksySDK Constructor
```javascript
new BanksySDK({
apiKey: string, // Required: Your API key
serverUrl?: string, // Optional: Server URL (default: https://api.banksy.io)
})
```
### Payment Methods
| Method | Description |
|--------|-------------|
| `createPayment(options)` | Create a new payment |
| `getPayment(id)` | Get payment by ID |
| `getPaymentStatus(id)` | Get payment status |
| `getPayments(ids)` | Get multiple payments |
| `getAllPayments(options)` | List payments with pagination |
| `verifyPayment(id)` | Verify a payment |
| `confirmPayment(id, options)` | Confirm payment manually |
### Withdraw Methods
| Method | Description |
|--------|-------------|
| `createWithdraw(options)` | Create crypto withdrawal |
### Crypto Payout Methods
| Method | Description |
|--------|-------------|
| `initCryptoPayout(config)` | Initialize payout module |
| `payout.getClientStatus()` | Get client registration status |
| `payout.getBalanceInfo()` | Get USDT balance and allowance |
| `payout.needsApproval(amount)` | Check if approval needed |
| `payout.approve(amount)` | Approve USDT spending |
| `payout.processPayout(...)` | Process single payout |
| `payout.processPayoutsBatch(...)` | Process batch payouts |
| `payout.estimateGas(...)` | Estimate gas cost |
### PIX Payout Methods
| Method | Description |
|--------|-------------|
| `pixPayout.create(options)` | Send money via PIX |
| `pixPayout.get(id)` | Get payout by ID |
| `pixPayout.getStatus(id)` | Get payout status |
| `pixPayout.list(options)` | List payouts with pagination |
| `pixPayout.getBalance()` | Get account balance |
| `pixPayout.validateCPF(cpf)` | Validate CPF document |
### Fiat-to-Crypto Payout Methods
| Method | Description |
|--------|-------------|
| `fiatCryptoPayout.getSupportedCurrencies()` | Get supported fiat currencies |
| `fiatCryptoPayout.getExchangeRate(fiat, crypto)` | Get current exchange rate |
| `fiatCryptoPayout.getQuote(options)` | Get payout quote/preview |
| `fiatCryptoPayout.create(options)` | Create fiat-to-crypto payout |
| `fiatCryptoPayout.prepare(id, wallet)` | Prepare transaction for signing |
| `fiatCryptoPayout.confirm(id, txHash)` | Confirm payout with TX hash |
| `fiatCryptoPayout.get(id)` | Get payout by ID |
| `fiatCryptoPayout.list(options)` | List payouts with pagination |
| `fiatCryptoPayout.cancel(id)` | Cancel pending payout |
### Utility Methods
| Method | Description |
|--------|-------------|
| `checkStatus()` | Check API status |
| `getProviders()` | Get available providers |
| `getContracts()` | Get crypto contracts |
| `getKeyInfo()` | Get API key info |
## Supported Tokens
| Token | Blockchains |
|-------|-------------|
| ETH | eth |
| USDT | eth, bsc, pol, trx |
| USDC | eth, bsc, pol |
| BNB | bsc |
| POL | pol |
| TRX | trx |
| BTC | btc |
## Security
⚠️ **Never expose your API key or private key in client-side code!**
```javascript
// Use environment variables
const banksy = new BanksySDK({
apiKey: process.env.BANKSY_API_KEY
});
const payout = banksy.initCryptoPayout({
privateKey: process.env.WALLET_PRIVATE_KEY
});
```
## License
MIT