nodejs-cryptomus
Version:
A comprehensive Node.js client for the Cryptomus API
587 lines (479 loc) • 14.8 kB
Markdown
# Cryptomus API
A comprehensive Node.js client for the Cryptomus API. This package provides full support for payment processing, payouts, webhooks, and more.
## Installation
```bash
npm install nodejs-cryptomus
```
## Features
- Complete TypeScript support
- Support for both CommonJS and ESM
- Full implementation of all Cryptomus API endpoints
- Payment operations (invoices, static wallets, QR codes, etc.)
- Payout operations
- Webhook handling and validation
- Balance management
- Currency operations and limits
## Quick Start
### Initialize the client
```typescript
import { Cryptomus } from 'nodejs-cryptomus';
const cryptomus = new Cryptomus({
merchantId: 'your-merchant-id',
paymentKey: 'your-payment-api-key',
payoutKey: 'your-payout-api-key' // Optional, required for payout operations
});
```
### Create a payment invoice
```typescript
const invoice = await cryptomus.payment.createInvoice({
amount: '100',
currency: 'USDT',
order_id: 'order-123',
url_return: 'https://your-site.com/success',
url_callback: 'https://your-site.com/webhook'
});
console.log('Payment URL:', invoice.url);
```
### Create a static wallet
```typescript
const wallet = await cryptomus.payment.createStaticWallet({
currency: 'BTC',
order_id: 'wallet-123',
url_callback: 'https://your-site.com/webhook'
});
console.log('Wallet address:', wallet.wallet);
```
### Handle webhooks
```typescript
import express from 'express';
const app = express();
app.post('/webhook', express.json(), (req, res) => {
try {
// Get the signature from the request headers
const signature = req.headers['signature'] as string;
// Parse and validate the webhook
const webhook = cryptomus.paymentWebhook.parsePaymentWebhook(
JSON.stringify(req.body),
signature
);
// Process the webhook based on status
if (webhook.status === 'paid') {
// Payment successful
console.log(`Payment ${webhook.uuid} for order ${webhook.order_id} was successful`);
}
res.status(200).send('OK');
} catch (error) {
console.error('Webhook error:', error);
res.status(400).send('Invalid webhook');
}
});
```
### Create a payout
```typescript
const payout = await cryptomus.payout.createPayout({
amount: '50',
currency: 'USDT',
network: 'TRX',
address: 'recipient-address',
order_id: 'payout-123',
url_callback: 'https://your-site.com/payout-webhook'
});
console.log('Payout created:', payout.uuid);
```
### Check account balance
```typescript
const balance = await cryptomus.balance.getMerchantBalance();
console.log('Available balances:', balance);
```
### Get available currencies
```typescript
const currencies = await cryptomus.currency.getPaymentCurrencies();
console.log('Available payment currencies:', currencies);
```
### Get payment limits
```typescript
const limits = await cryptomus.currency.getPaymentLimits('BTC');
console.log('BTC payment limits:', limits);
```
## Error Handling
The library throws `CryptomusError` for API-related errors:
```typescript
try {
const result = await cryptomus.payment.createInvoice({
// ...params
});
} catch (error) {
if (error instanceof CryptomusError) {
console.error('API Error:', error.message);
console.error('Status code:', error.statusCode);
console.error('Error details:', error.errors);
} else {
console.error('Unexpected error:', error);
}
}
```
## API Documentation
### Payment Operations
#### `payment.createInvoice(params)`
Creates a new payment invoice for cryptocurrency payments.
```typescript
// Parameters
{
amount: string; // Amount to be paid
currency: string; // Currency code (e.g., "USD", "EUR")
order_id: string; // Your internal order ID
url_return?: string; // URL to redirect after payment
url_callback?: string; // Webhook URL to receive payment notifications
is_payment_multiple?: boolean; // Allow multiple payments to this invoice
lifetime?: number; // Invoice lifetime in seconds
to_currency?: string; // Currency in which payment should be accepted
subtract_fee_from_amount?: boolean; // Subtract Cryptomus fee from amount
custom_payload?: string; // Additional information
}
// Returns
{
url: string; // Payment URL
uuid: string; // Cryptomus payment ID
currency: string; // Currency code
status: string; // Payment status
// ...other payment details
}
```
#### `payment.getPaymentInfo(params)`
Retrieves information about a specific payment.
```typescript
// Parameters - One of these is required
{
uuid?: string; // Cryptomus payment ID
order_id?: string; // Your internal order ID
}
// Returns
{
uuid: string; // Cryptomus payment ID
order_id: string; // Your internal order ID
amount: string; // Payment amount
payment_amount: string; // Amount paid
currency: string; // Currency code
status: string; // Payment status
// ...other payment details
}
```
#### `payment.getPaymentHistory(params)`
Retrieves payment history with optional filtering.
```typescript
// Parameters (all optional)
{
date_from?: string; // Start date (YYYY-MM-DD)
date_to?: string; // End date (YYYY-MM-DD)
limit?: number; // Number of records to return (max 100)
offset?: number; // Offset for pagination
order?: 'asc' | 'desc'; // Sort order
status?: string; // Filter by payment status
}
// Returns
{
items: Array<{ // Array of payment objects
uuid: string; // Cryptomus payment ID
order_id: string; // Your internal order ID
amount: string; // Payment amount
currency: string; // Currency code
status: string; // Payment status
// ...other payment details
}>;
count: number; // Total number of matching records
}
```
#### `payment.createStaticWallet(params)`
Creates a static wallet for accepting cryptocurrency payments.
```typescript
// Parameters
{
currency: string; // Cryptocurrency code (e.g., "BTC", "ETH", "USDT")
order_id: string; // Your internal wallet ID
network?: string; // Network for the currency (for multi-network tokens)
url_callback?: string; // Webhook URL for payment notifications
custom_payload?: string; // Additional information
}
// Returns
{
wallet_uuid: string; // Wallet UUID
wallet: string; // Wallet address
currency: string; // Currency code
network: string; // Network name
// ...other wallet details
}
```
#### `payment.blockWallet(params)`
Blocks a previously created static wallet.
```typescript
// Parameters - One of these is required
{
uuid?: string; // Wallet UUID
order_id?: string; // Your internal wallet ID
}
// Returns
{
result: boolean; // Operation success status
}
```
#### `payment.generateQrCode(params)`
Generates a QR code for a payment or wallet address.
```typescript
// Parameters
{
uuid: string; // Payment UUID or wallet UUID
type: 'wallet' | 'invoice'; // Type of UUID provided
}
// Returns
{
qr_code: string; // Base64 encoded QR code image
}
```
#### `payment.refund(params)`
Creates a refund for a completed payment.
```typescript
// Parameters
{
uuid: string; // Payment UUID
address: string; // Refund wallet address
amount?: string; // Amount to refund (omit for full refund)
}
// Returns
{
result: boolean; // Operation success status
}
```
#### `payment.testWebhook(params)`
Tests your webhook endpoint by sending a sample webhook.
```typescript
// Parameters
{
order_id: string; // Your internal order ID
url_callback: string; // Webhook URL to test
}
// Returns
{
result: boolean; // Operation success status
}
```
#### `payment.resendWebhook(params)`
Resends a webhook for a specific payment.
```typescript
// Parameters - One of these is required
{
uuid?: string; // Payment UUID
order_id?: string; // Your internal order ID
}
// Returns
{
result: boolean; // Operation success status
}
```
#### `payment.getServices()`
Retrieves a list of available payment services and currencies.
```typescript
// No parameters required
// Returns
{
services: Array<{
currency: string; // Currency code
network: string; // Network name
is_available: boolean; // Availability status
min_amount: string; // Minimum payment amount
max_amount: string; // Maximum payment amount
}>;
}
```
### Payout Operations
#### `payout.createPayout(params)`
Creates a new cryptocurrency payout to a specified address.
```typescript
// Parameters
{
amount: string; // Amount to payout
currency: string; // Currency code (e.g., "USDT", "BTC")
network: string; // Network for the currency (e.g., "TRX" for USDT-TRC20)
address: string; // Recipient wallet address
order_id: string; // Your internal payout ID
url_callback?: string; // Webhook URL for payout notifications
is_subtract?: boolean; // Subtract fee from amount (default: false)
additional_data?: string; // Additional information for recipient
}
// Returns
{
uuid: string; // Payout UUID
order_id: string; // Your internal payout ID
amount: string; // Payout amount
currency: string; // Currency code
status: string; // Payout status
// ...other payout details
}
```
#### `payout.getPayoutInfo(params)`
Retrieves information about a specific payout.
```typescript
// Parameters - One of these is required
{
uuid?: string; // Payout UUID
order_id?: string; // Your internal payout ID
}
// Returns
{
uuid: string; // Payout UUID
order_id: string; // Your internal payout ID
amount: string; // Payout amount
currency: string; // Currency code
status: string; // Payout status
// ...other payout details
}
```
#### `payout.getPayoutHistory(params)`
Retrieves payout history with optional filtering.
```typescript
// Parameters (all optional)
{
date_from?: string; // Start date (YYYY-MM-DD)
date_to?: string; // End date (YYYY-MM-DD)
limit?: number; // Number of records to return (max 100)
offset?: number; // Offset for pagination
order?: 'asc' | 'desc'; // Sort order
status?: string; // Filter by payout status
}
// Returns
{
items: Array<{ // Array of payout objects
uuid: string; // Payout UUID
order_id: string; // Your internal payout ID
amount: string; // Payout amount
currency: string; // Currency code
status: string; // Payout status
// ...other payout details
}>;
count: number; // Total number of matching records
}
```
#### `payout.getServices()`
Retrieves a list of available payout services and currencies.
```typescript
// No parameters required
// Returns
{
services: Array<{
currency: string; // Currency code
network: string; // Network name
is_available: boolean; // Availability status
commission: string; // Payout commission percentage
min_amount: string; // Minimum payout amount
max_amount: string; // Maximum payout amount
}>;
}
```
### Webhook Handling
#### `paymentWebhook.parseWebhook(payload, signature)`
Generic method to parse and validate any webhook.
```typescript
// Parameters
payload: string; // JSON string of the webhook payload
signature: string; // Signature from the request headers
// Returns
// The parsed and validated webhook payload object
```
#### `paymentWebhook.parsePaymentWebhook(payload, signature)`
Parses and validates a payment webhook.
```typescript
// Parameters
payload: string; // JSON string of the webhook payload
signature: string; // Signature from the request headers
// Returns
{
status: string; // Payment status (e.g., "paid", "partially_paid")
uuid: string; // Payment UUID
order_id: string; // Your internal order ID
amount: string; // Payment amount
payment_amount: string; // Amount actually paid
currency: string; // Currency code
// ...other payment details
}
```
#### `payoutWebhook.parsePayoutWebhook(payload, signature)`
Parses and validates a payout webhook.
```typescript
// Parameters
payload: string; // JSON string of the webhook payload
signature: string; // Signature from the request headers
// Returns
{
status: string; // Payout status (e.g., "confirmed", "failed")
uuid: string; // Payout UUID
order_id: string; // Your internal payout ID
amount: string; // Payout amount
currency: string; // Currency code
// ...other payout details
}
```
### Balance Operations
#### `balance.getMerchantBalance()`
Retrieves the current merchant account balance.
```typescript
// No parameters required
// Returns
{
balances: Array<{
currency: string; // Currency code
balance: string; // Available balance
}>;
}
```
#### `balance.getBusinessBalance()`
Retrieves the business account balance.
```typescript
// No parameters required
// Returns
{
balances: Array<{
currency: string; // Currency code
balance: string; // Available balance
}>;
}
```
### Currency Operations
#### `currency.getPaymentCurrencies()`
Retrieves a list of available payment currencies.
```typescript
// No parameters required
// Returns
{
currencies: Array<{
currency: string; // Currency code
network: string; // Network name
is_available: boolean; // Availability status
}>;
}
```
#### `currency.getPayoutCurrencies()`
Retrieves a list of available payout currencies.
```typescript
// No parameters required
// Returns
{
currencies: Array<{
currency: string; // Currency code
network: string; // Network name
is_available: boolean; // Availability status
}>;
}
```
#### `currency.getPaymentLimits(currency)`
Retrieves payment limits for a specific currency.
```typescript
// Parameters
currency: string; // Currency code (e.g., "BTC", "ETH")
// Returns
{
currency: string; // Currency code
min_amount: string; // Minimum payment amount
max_amount: string; // Maximum payment amount
}
```
## License
MIT