sunny-payments
v1.0.0
Published
Official Sunny Payments Node.js SDK - Payment processing made simple
Maintainers
Readme
Sunny Payments Node.js SDK
The official Node.js SDK for Sunny Payments - Payment processing made simple.
Installation
npm install sunny-payments
# or
yarn add sunny-payments
# or
pnpm add sunny-paymentsQuick Start
import Sunny from 'sunny-payments';
// Initialize the client with your API key
const sunny = new Sunny('sk_live_your_api_key');
// Create a payment
const payment = await sunny.payments.create({
amount: 1000,
currency: 'KES',
source: 'mpesa',
description: 'Order #12345'
});
console.log(payment.id); // pay_xxxxxFeatures
- ✅ Payments - Create, capture, refund, and manage payments
- ✅ Customers - Create and manage customer profiles
- ✅ Refunds - Process full and partial refunds
- ✅ Webhooks - Register endpoints and verify signatures
- ✅ Bills - Airtime, data, electricity, and utility payments
- ✅ TypeScript - Full type definitions included
- ✅ Error Handling - Detailed error classes
Usage Examples
Payments
// Create a payment
const payment = await sunny.payments.create({
amount: 5000,
currency: 'KES',
source: 'mpesa',
metadata: { orderId: '12345' }
});
// Retrieve a payment
const retrieved = await sunny.payments.retrieve('pay_123');
// List payments
const { data, has_more } = await sunny.payments.list({ limit: 10 });
// Refund a payment
const refunded = await sunny.payments.refund('pay_123', {
amount: 2500,
reason: 'Customer request'
});Customers
// Create a customer
const customer = await sunny.customers.create({
email: '[email protected]',
name: 'John Doe',
phone: '+254712345678'
});
// Update a customer
await sunny.customers.update('cus_123', {
name: 'Jane Doe'
});
// List customers
const customers = await sunny.customers.list({ limit: 20 });Bill Payments
// Purchase airtime
const airtime = await sunny.bills.purchaseAirtime({
phoneNumber: '+254712345678',
amount: 100,
network: 'safaricom'
});
// Buy data bundle
const bundles = await sunny.bills.getDataBundles('safaricom');
const data = await sunny.bills.purchaseData({
phoneNumber: '+254712345678',
bundleId: bundles[0].id,
network: 'safaricom'
});
// Buy electricity tokens
const electricity = await sunny.bills.purchaseElectricity({
meterNumber: '12345678',
amount: 500,
phoneNumber: '+254712345678'
});
console.log(electricity.token); // KPLC tokenWebhooks
// Register a webhook
const webhook = await sunny.webhooks.create({
url: 'https://example.com/webhooks/sunny',
events: ['payment.succeeded', 'payment.failed']
});
// Verify webhook signature (in your webhook handler)
app.post('/webhooks/sunny', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-sunny-signature'] as string;
if (!sunny.webhooks.verifySignature(req.body, signature, WEBHOOK_SECRET)) {
return res.status(400).send('Invalid signature');
}
const event = JSON.parse(req.body.toString());
switch (event.type) {
case 'payment.succeeded':
// Handle successful payment
break;
case 'payment.failed':
// Handle failed payment
break;
}
res.status(200).send('OK');
});Error Handling
import Sunny, {
AuthenticationError,
ValidationError,
APIError,
NotFoundError,
RateLimitError
} from 'sunny-payments';
try {
const payment = await sunny.payments.create({ ... });
} catch (error) {
if (error instanceof AuthenticationError) {
// Invalid API key
} else if (error instanceof ValidationError) {
// Invalid request parameters
console.log(error.field); // The field that caused the error
} else if (error instanceof NotFoundError) {
// Resource not found
console.log(error.resource, error.resourceId);
} else if (error instanceof RateLimitError) {
// Too many requests
console.log(`Retry after ${error.retryAfter} seconds`);
} else if (error instanceof APIError) {
// Other API error
console.log(error.statusCode, error.code);
}
}Configuration
const sunny = new Sunny('sk_live_xxx', {
baseUrl: 'https://api.sunnypayments.com/v1', // Custom API URL
timeout: 30000, // Request timeout in ms
maxRetries: 3 // Max retry attempts
});Environment Variables
Store your API key securely:
# .env
SUNNY_API_KEY=sk_live_your_api_key
SUNNY_WEBHOOK_SECRET=whsec_your_webhook_secretconst sunny = new Sunny(process.env.SUNNY_API_KEY!);TypeScript
This SDK includes full TypeScript definitions. All methods are fully typed:
import Sunny, { Payment, Customer, PaymentCreateParams } from 'sunny-payments';
const params: PaymentCreateParams = {
amount: 1000,
currency: 'KES',
source: 'mpesa'
};
const payment: Payment = await sunny.payments.create(params);Support
License
MIT License - see LICENSE for details.
