cryptopayhub-sdk
v1.0.5
Published
Official TypeScript/Node.js SDK for integrating with CryptoPayHub Payment Gateway - Accept crypto payments on TRON, BSC, and Polygon
Maintainers
Readme
CryptoPayHub SDK
Official TypeScript/Node.js SDK for integrating with CryptoPayHub Payment Gateway.
Features
- ✅ Full API Coverage - All 14 gateway endpoints
- ✅ TypeScript Support - Full type definitions included
- ✅ Webhook Verification - Built-in HMAC-SHA256 signature verification
- ✅ Multi-Network - Support for TRON, BSC, and Polygon
- ✅ Easy Integration - Simple, intuitive API
- ✅ Error Handling - Comprehensive error messages
- ✅ Helper Functions - Utility functions for common tasks
Installation
npm install cryptopayhub-sdk
# or
yarn add cryptopayhub-sdk
# or
pnpm add cryptopayhub-sdkQuick Start
import CryptoPayHubSDK from "cryptopayhub-sdk";
// Initialize the SDK
const cryptoPayHub = new CryptoPayHubSDK({
apiKey: "cph_your_api_key_here",
webhookSecret: "whsec_your_webhook_secret_here", // Optional, for webhook verification
baseUrl: "https://api.cryptopayhub.com/api/v1/gateway", // Optional, defaults to production
});
// Create a payment
const payment = await cryptoPayHub.createPayment({
amount: "50.00",
currency: "USDT",
network: "TRON",
reference: "ORDER_12345",
});
console.log(`Payment created! Address: ${payment.address}`);
console.log(`QR Code: ${payment.qrCode}`);Configuration
CryptoPayHubConfig
interface CryptoPayHubConfig {
apiKey: string; // Required: Your API key from CryptoPayHub
webhookSecret?: string; // Optional: For webhook signature verification
baseUrl?: string; // Optional: API base URL (defaults to https://api.cryptopayhub.com/api/v1/gateway)
timeout?: number; // Optional: Request timeout in ms (default: 30000)
}Using Custom Base URL
You can configure the SDK to use a different base URL (e.g., for local development or self-hosted instances):
// Production (default)
const cryptoPayHub = new CryptoPayHubSDK({
apiKey: "cph_your_api_key",
webhookSecret: "whsec_your_secret",
});
// Local development
const cryptoPayHub = new CryptoPayHubSDK({
apiKey: "cph_your_api_key",
webhookSecret: "whsec_your_secret",
baseUrl: "http://localhost:5000/api/v1/gateway",
});
// Self-hosted instance
const cryptoPayHub = new CryptoPayHubSDK({
apiKey: "cph_your_api_key",
webhookSecret: "whsec_your_secret",
baseUrl: "https://your-domain.com/api/v1/gateway",
});
// Get the current base URL
console.log(cryptoPayHub.getBaseUrl()); // "http://localhost:5000/api/v1/gateway"API Methods
Project Management
Get Project Info
const project = await cryptoPayHub.getProjectInfo();
console.log(project.name);
console.log(project.wallets); // Array of wallet addressesRegenerate API Key
const newApiKey = await cryptoPayHub.regenerateApiKey();
console.log(`New API Key: ${newApiKey}`);Payments
Create Payment
const payment = await cryptoPayHub.createPayment({
amount: "100.00",
currency: "USDT", // Optional: USDT, USDC, BUSD
network: "TRON", // Optional: TRON, BSC, POLYGON, auto
reference: "ORDER_12345", // Required: Your unique reference
expiresIn: 3600, // Optional: Expiration in seconds (default: 3600)
metadata: { // Optional: Additional data
orderId: "12345",
customerEmail: "[email protected]",
},
});
// Response includes:
// - paymentId: Internal payment ID
// - address: Cryptocurrency address
// - qrCode: Base64 QR code image
// - instructions: Step-by-step instructions
// - expiresAt: Payment expiration timeGet Payment by ID
const payment = await cryptoPayHub.getPayment(123);
console.log(payment.status); // pending, confirmed, failedGet Payment by Reference
const payment = await cryptoPayHub.getPaymentByReference("ORDER_12345");
console.log(payment.txHash); // Transaction hash (when confirmed)List Payments
const payments = await cryptoPayHub.listPayments({
limit: 20, // Optional: Number of payments (max 100)
status: "pending", // Optional: Filter by status
});Webhooks
Test Webhook Endpoint
const result = await cryptoPayHub.testWebhook();
console.log(result.message); // Success or error messageGet Webhook Logs
const logs = await cryptoPayHub.getWebhookLogs({
limit: 50,
status: "delivered", // Optional: delivered, failed, pending
});Get Webhook Statistics
const stats = await cryptoPayHub.getWebhookStats();
console.log(`Success Rate: ${stats.successRate}%`);Network Information
List Supported Networks
const networks = await cryptoPayHub.getNetworks();
networks.forEach((network) => {
console.log(`${network.name}: ${network.status}`);
console.log(`Confirmations: ${network.confirmations}`);
console.log(`Avg Time: ${network.avgConfirmationTime}`);
});List Supported Coins
const coins = await cryptoPayHub.getCoins();
coins.forEach((coin) => {
console.log(`${coin.name}: ${coin.networks.join(", ")}`);
});Webhook Handling
Verify Webhook Signature
import express from "express";
app.post(
"/webhooks/cryptopayhub",
express.raw({ type: "application/json" }), // IMPORTANT: Use raw body
async (req, res) => {
const signature = req.headers["x-webhook-signature"] as string;
const timestamp = req.headers["x-webhook-timestamp"] as string;
const rawBody = req.body.toString("utf8");
try {
// Parse and verify in one step
const event = cryptoPayHub.parseWebhookEvent(rawBody, signature, timestamp);
// Handle the event
switch (event.event) {
case "payment.confirmed":
console.log(`Payment confirmed: ${event.reference}`);
// Your business logic here
break;
case "payment.failed":
console.log(`Payment failed: ${event.reference}`);
break;
}
res.status(200).json({ received: true });
} catch (error) {
res.status(400).json({ error: "Invalid webhook" });
}
}
);Webhook Events
| Event | Description |
|-------|-------------|
| payment.created | Payment request created |
| payment.confirmed | Payment received and confirmed |
| payment.failed | Payment failed or invalid |
| payment.expired | Payment window expired |
| webhook.test | Test webhook (from test endpoint) |
Webhook Payload
interface WebhookEvent {
event: string; // Event type
paymentId: number; // Payment ID
reference: string; // Your reference
status: string; // Payment status
amount?: string; // Payment amount
currency?: string; // Currency (USDT, USDC, etc.)
network?: string; // Network (TRON, BSC, POLYGON)
txHash?: string; // Transaction hash
confirmations?: number; // Number of confirmations
timestamp: string; // Event timestamp
}Helper Functions
Check Payment Status
const payment = await cryptoPayHub.getPayment(123);
// Check if completed
if (CryptoPayHubSDK.isPaymentCompleted(payment)) {
console.log("Payment completed!");
}
// Check if pending
if (CryptoPayHubSDK.isPaymentPending(payment)) {
console.log("Waiting for payment...");
}
// Check if expired
if (CryptoPayHubSDK.isPaymentExpired(payment)) {
console.log("Payment expired");
}Format Amount
const formatted = CryptoPayHubSDK.formatAmount("50.123456", "USDT");
console.log(formatted); // "50.12 USDT"Get Status Display
const display = CryptoPayHubSDK.getPaymentStatusDisplay(payment);
console.log(display); // "✅ Payment confirmed" or "⏳ Waiting for payment..."Get Explorer URL
const url = CryptoPayHubSDK.getExplorerUrl("TRON", "abc123...");
console.log(url); // "https://tronscan.org/#/transaction/abc123..."Error Handling
try {
const payment = await cryptoPayHub.createPayment({...});
} catch (error) {
console.error("Payment creation failed:", error.message);
// Error messages are descriptive:
// - "Invalid API key"
// - "Network not available"
// - "Insufficient funds"
// - etc.
}TypeScript Support
Full TypeScript definitions are included:
import CryptoPayHubSDK, {
Payment,
ProjectInfo,
Network,
Coin,
WebhookEvent,
CreatePaymentRequest,
} from "cryptopayhub-sdk";Examples
See the /examples directory for complete examples:
basic-usage.ts- Basic SDK usagewebhook-handler.ts- Complete webhook serverexpress-integration.ts- Express.js integrationnextjs-integration.ts- Next.js API route
Best Practices
1. Store Credentials Securely
// Use environment variables
const cryptoPayHub = new CryptoPayHubSDK({
apiKey: process.env.CRYPTOPAYHUB_API_KEY!,
webhookSecret: process.env.CRYPTOPAYHUB_WEBHOOK_SECRET!,
});2. Always Verify Webhooks
// NEVER trust webhooks without signature verification
const event = cryptoPayHub.parseWebhookEvent(body, signature, timestamp);3. Handle Webhook Retries Gracefully
// CryptoPayHub will retry failed webhooks up to 5 times
// Make your webhook handler idempotent (safe to call multiple times)
const processedPayments = new Set<number>();
if (!processedPayments.has(event.paymentId)) {
await processPayment(event);
processedPayments.add(event.paymentId);
}4. Monitor Webhook Delivery
// Regularly check webhook stats
const stats = await cryptoPayHub.getWebhookStats();
if (stats.successRate < 95) {
console.warn("Low webhook success rate!");
}Support
- Documentation: https://docs.cryptopayhub.com
- API Reference: https://api.cryptopayhub.com/docs
- Support: [email protected]
- GitHub: https://github.com/cryptopayhub/sdk
License
MIT License - See LICENSE file for details
Changelog
v1.0.0 (2025-10-26)
- Initial release
- Full API coverage
- Multi-network support (TRON, BSC, Polygon)
- Webhook verification
- TypeScript support
- Helper functions
