kidapay-checkout-sdk
v1.4.1
Published
Official Kidapay SDK for collecting crypto payments on your website
Downloads
65
Maintainers
Readme
Kidapay Checkout SDK
Official JavaScript/TypeScript SDK for integrating Kidapay cryptocurrency payments into your website or application.
Features
- ✨ Universal: Works in both browser and Node.js environments
- 🔐 Secure: Built-in webhook signature verification
- 💰 Multi-crypto: Support for Bitcoin, Ethereum, USDC, Dogecoin, and more
- 🎨 Customizable: Popup, iframe, or redirect payment flows
- 📱 Responsive: Mobile-optimized payment interface
- 🚀 TypeScript: Full TypeScript support with type definitions
- ⚡ Fast: Lightweight with minimal dependencies
Installation
NPM
npm install kidapay-checkout-sdkYarn
yarn add kidapay-checkout-sdkCDN (Browser)
<!-- Load axios first (required dependency) -->
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<!-- Then load Kidapay SDK -->
<script src="https://unpkg.com/kidapay-checkout-sdk@latest/dist/index.umd.js"></script>Note: When using the CDN version, you must load axios before the Kidapay SDK since it's a required dependency.
Quick Start
Frontend Usage (Browser)
<!DOCTYPE html>
<html>
<head>
<title>Crypto Payment Example</title>
</head>
<body>
<button id="pay-button">Pay with Crypto</button>
<!-- Load axios first -->
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<!-- Then load Kidapay SDK -->
<script src="https://unpkg.com/kidapay-checkout-sdk@latest/dist/index.umd.js"></script>
<script>
const kidapay = new Kidapay({
apiKey: 'pk_test_your_public_key_here',
environment: 'sandbox'
});
document.getElementById('pay-button').onclick = async () => {
try {
await kidapay.checkout({
amount: 10.00,
currency: 'USD',
customer_email: '[email protected]',
description: 'Test payment',
displayMode: 'popup',
onSuccess: (data) => {
console.log('Payment successful!', data);
alert(`Payment successful! Transaction: ${data.transactionHash}`);
},
onError: (error) => {
console.error('Payment failed:', error);
alert(`Payment failed: ${error.message}`);
}
});
} catch (error) {
console.error('Checkout error:', error);
}
};
</script>
</body>
</html>Backend Usage (Node.js)
const { Kidapay, KidapayWebhook } = require('kidapay-checkout-sdk');
// Initialize SDK
const kidapay = new Kidapay({
apiKey: process.env.KIDAPAY_SECRET_KEY,
environment: 'sandbox'
});
// Create a checkout
async function createCheckout() {
try {
const checkout = await kidapay.createCheckout({
merchant_order_id: 'order_123',
customer_email: '[email protected]', // Optional
amount: 25.00,
currency: 'USD',
title: 'Product purchase',
description: 'High quality product',
pay_currency: 'BTC' // Optional: preferred crypto
});
console.log('Checkout created:', checkout);
return checkout.payment_link;
} catch (error) {
console.error('Error creating checkout:', error);
}
}
// Handle webhooks - uses API key for verification
const webhook = new KidapayWebhook({
apiKey: process.env.KIDAPAY_API_KEY // Same key used for checkout creation
});
// Listen to payment status changes
webhook.on('SUCCESSFUL', (event) => {
console.log('Payment successful:', {
orderId: event.order_id,
merchantOrderId: event.merchant_order_id,
amount: event.amount,
currency: event.currency
});
// Update your database, send confirmation email, etc.
});
webhook.on('FAILED', (event) => {
console.log('Payment failed:', event);
// Handle failed payment
});
// Express.js webhook endpoint
app.post('/webhook', webhook.middleware());API Reference
Kidapay Class
Constructor
new Kidapay(config: KidapayConfig)Config Options:
apiKey(string, required): Your Kidapay API keyenvironment(string, optional): 'sandbox' or 'live' (default: 'sandbox')timeout(number, optional): Request timeout in milliseconds (default: 30000)
Static Factory Methods
// Create sandbox instance
Kidapay.sandbox(apiKey: string): Kidapay
// Create live instance
Kidapay.live(apiKey: string): Kidapay
// Create with custom config
Kidapay.create(config: KidapayConfig): KidapayMethods
checkout(options: CheckoutOptions)
Creates and opens a checkout session (browser only).
Options:
amount(number, required): Payment amountcurrency(SupportedFiatCurrencies, required): Currency code (USD, EUR, KES, etc.)customer_email(string, optional): Customer email addressdescription(string, optional): Payment descriptiondisplayMode(string, optional): 'popup', 'iframe', or 'redirect' (default: 'popup')onSuccess(function, optional): Success callback with PaymentSuccessDataonError(function, optional): Error callback with PaymentErroronCancel(function, optional): Cancel callbackonPending(function, optional): Pending payment callback with PaymentPendingDataonPartiallyPaid(function, optional): Partial payment callback with PaymentPartialData
Callback Data Structures:
interface PaymentSuccessData {
id: string; // checkout id
order_id: string; // order id
pay_amount: string;
pay_currency: string;
pay_network: string;
receieve_currency: string | null;
receieve_amount: string | null;
address: string;
status: PaymentStatus;
}
interface PaymentError {
code: string;
message: string;
checkoutId?: string;
details?: any;
}
interface PaymentPendingData {
id: string; // checkout id
order_id: string; // order id
pay_amount: string;
pay_currency: string;
pay_network: string;
receieve_currency: string | null;
receieve_amount: string | null;
address: string;
status: PaymentStatus;
}
interface PaymentPartialData {
id: string; // checkout id
order_id: string; // order id
pay_amount: string;
pay_currency: string;
pay_network: string;
receieve_currency: string | null;
receieve_amount: string | null;
address: string;
status: PaymentStatus;
}createCheckout(request: CreateCheckoutRequest)
Creates a checkout session (backend).
Request Interface:
interface CreateCheckoutRequest {
merchant_order_id: string; // Required: Your unique order identifier
customer_email?: string; // Optional: Customer email address
amount: number; // Required: Order amount in the specified currency
currency: SupportedFiatCurrencies; // Required: Fiat currency for the order
title: string; // Required: Order title displayed to customers
pay_currency?: SupportedCryptoCurrencies; // Optional: Preferred cryptocurrency
description?: string; // Optional: Detailed order description
callback_url?: string; // Optional: Webhook callback URL
cancel_url?: string; // Optional: Cancel redirect URL
success_url?: string; // Optional: Success redirect URL
}Response Interface:
interface CreateCheckoutResponse {
order: {
id: string;
amount: number;
status: PaymentStatus;
};
payment_link: string;
}getCheckout(checkoutId: string)
Retrieves checkout details.
Response Interface:
interface CheckoutDetails {
order: {
id: string;
merchant_order_id: string;
amount: number;
pay_amount: number;
currency: SupportedFiatCurrencies;
pay_currency: SupportedCryptoCurrencies;
title: string;
description: string;
callback_url: string;
cancel_url: string;
success_url: string;
is_paid: boolean;
created_at: string;
updated_at: string;
status: PaymentStatus;
};
payment_link: string;
}ping()
Health check method.
Response:
{ status: string; timestamp: string }getConfig()
Returns a read-only copy of the current configuration.
Response:
Readonly<KidapayConfig>KidapayWebhook Class
Constructor
new KidapayWebhook(config: WebhookConfig)Config Options:
apiKey(string, required): Your Kidapay API key (same as used for checkout creation)tolerance(number, optional): Timestamp tolerance in seconds (default: 1500)
Methods
on(status: PaymentStatus | '*', handler: function)
Registers an event handler for payment status changes.
Payment Statuses:
NEW- New order createdSUCCESSFUL- Payment completed successfullyFAILED- Payment failedEXPIRED- Payment session expiredCANCELLED- Payment cancelled by userREFUNDED- Payment refundedPARTIALLY_PAID- Partial payment received*- All events (wildcard)
off(status: PaymentStatus | '*', handler: function)
Removes an event handler.
handle(payload: string | Buffer, signature: string, timestamp?: string)
Processes a webhook payload.
verifyAndParse(payload: string | Buffer, signature: string, timestamp?: string)
Verifies and parses webhook payload.
Response:
interface WebhookReqBody {
order_id: string; // Unique order identifier from Kidapay
merchant_order_id: string; // Merchant's internal order identifier
status: PaymentStatus; // Current payment status of the order
amount: number; // Order amount in fiat currency
currency: SupportedFiatCurrencies; // Fiat currency code
pay_currency: SupportedCryptoCurrencies; // Cryptocurrency used for payment
title: string; // Order title/name
description: string; // Order description
callback_url: string; // Webhook callback URL for status updates
cancel_url: string; // URL to redirect on payment cancellation
success_url: string; // URL to redirect on successful payment
}middleware()
Returns Express.js middleware for handling webhooks.
nextHandler()
Returns Next.js API route handler for webhooks.
fastifyPlugin()
Returns Fastify plugin for handling webhooks.
processEvent(event: WebhookReqBody)
Processes a verified webhook event.
Supported Currencies
Fiat Currencies
- KES (Kenyan Shilling)
- NGN (Nigerian Naira)
- ZAR (South African Rand)
- GHS (Ghanaian Cedi)
- LRD (Liberian Dollar)
- EUR (Euro)
- USD (US Dollar)
Cryptocurrencies
- BTC (Bitcoin)
- LTC (Litecoin)
- ETH (Ethereum)
- SOL (Solana)
- USDC (USD Coin)
- USDT (USDT Coin)
- TRON (Tron)
- ALGO (Algo)
- And more...
Display Modes
Popup (Default)
Opens the payment interface in a popup window.
await kidapay.checkout({
amount: 10.00,
currency: 'USD',
displayMode: 'popup'
// ... other options
});Iframe
Embeds the payment interface in an overlay iframe.
await kidapay.checkout({
amount: 10.00,
currency: 'USD',
displayMode: 'iframe'
// ... other options
});Redirect
Redirects the user to the payment page.
await kidapay.checkout({
amount: 10.00,
currency: 'USD',
displayMode: 'redirect'
// ... other options
});Error Handling
The SDK provides comprehensive error handling with specific error types:
try {
await kidapay.checkout({ /* options */ });
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
} else if (error instanceof ApiError) {
console.error('API error:', error.message, error.code);
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message);
} else {
console.error('Unknown error:', error);
}
}Error Types
ValidationError: Invalid input parametersApiError: API request failuresNetworkError: Network connectivity issuesKidapayError: Base error class
Webhook Integration
Express.js
const express = require('express');
const { KidapayWebhook } = require('kidapay-checkout-sdk');
const app = express();
const webhook = new KidapayWebhook({
apiKey: process.env.KIDAPAY_API_KEY
});
// Register event handlers
webhook.on('SUCCESSFUL', (event) => {
console.log('Payment successful:', event);
// Update database, send confirmation email, etc.
});
webhook.on('FAILED', (event) => {
console.log('Payment failed:', event);
// Handle failed payment
});
webhook.on('*', (event) => {
console.log('Webhook received:', event);
});
// Use middleware
app.post('/webhook', express.raw({ type: 'application/json' }), webhook.middleware());Next.js
// pages/api/webhook.js
import { KidapayWebhook } from 'kidapay-checkout-sdk';
const webhook = new KidapayWebhook({
apiKey: process.env.KIDAPAY_API_KEY
});
webhook.on('SUCCESSFUL', (event) => {
console.log('Payment successful:', event);
});
export default webhook.nextHandler();Fastify
const fastify = require('fastify');
const { KidapayWebhook } = require('kidapay-checkout-sdk');
const app = fastify();
const webhook = new KidapayWebhook({
apiKey: process.env.KIDAPAY_API_KEY
});
webhook.on('SUCCESSFUL', (event) => {
console.log('Payment successful:', event);
});
app.register(webhook.fastifyPlugin());Environment Variables
For backend usage, set these environment variables:
KIDAPAY_SECRET_KEY=sk_test_your_secret_key_here
KIDAPAY_API_KEY=pk_test_your_public_key_hereTesting
The SDK includes comprehensive test coverage:
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchDevelopment
Local Development Server
# Start backend development server
npm run dev:backend
# Start frontend development server
npm run dev:serverBuilding
# Build the SDK
npm run build
# Build in watch mode
npm run build:watchTypeScript Support
The SDK is written in TypeScript and includes full type definitions:
import { Kidapay, CheckoutOptions, PaymentSuccessData } from 'kidapay-checkout-sdk';
const kidapay = new Kidapay({
apiKey: 'your-api-key',
environment: 'sandbox'
});
const options: CheckoutOptions = {
amount: 10.00,
currency: 'USD',
onSuccess: (data: PaymentSuccessData) => {
console.log('Payment successful:', data.transactionHash);
}
};Contributing
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 📧 Email: [email protected]
- 📚 Documentation: https://docs.kidapay.com
- 🐛 Issues: https://github.com/kidapay/kidapay-checkout-sdk/issues
- 💬 Discord: https://discord.gg/kidapay
Changelog
See CHANGELOG.md for a list of changes and version history.
Made with ❤️ by the Kidapay team
