@corenect/sdk
v1.1.0
Published
Official Corenect Technologies SDK for subscription and payment management
Downloads
256
Maintainers
Readme
@corenect/sdk
Official Corenect Technologies SDK for subscription and payment management.
Installation
npm install @corenect/sdk
# or
yarn add @corenect/sdk
# or
pnpm add @corenect/sdkQuick Start
import { Corenect } from '@corenect/sdk';
const corenect = new Corenect({
apiKey: 'sk_live_your_secret_key',
});
// List all plans
const plans = await corenect.listPlans();
// Subscribe a user to a plan
const subscription = await corenect.subscribe({
userEmail: '[email protected]',
userName: 'John Doe',
planId: 'plan_123',
});
// Check subscription status
const status = await corenect.getSubscriptionStatus(subscription.id);
console.log(`Active: ${status.subscription.isActive}`);API Reference
Plans
// List all plans
const plans = await corenect.listPlans();
// Get a specific plan
const plan = await corenect.getPlan('plan_123');
// Create a plan
const newPlan = await corenect.createPlan({
name: 'Pro Plan',
price: 2999,
currency: 'ZAR',
interval: 'monthly',
features: ['Unlimited users', 'Priority support'],
});
// Update a plan
const updated = await corenect.updatePlan('plan_123', {
price: 3999,
});
// Delete a plan
await corenect.deletePlan('plan_123');Users
// List all users
const users = await corenect.listUsers();
// Get user by ID
const user = await corenect.getUser('user_123');
// Get user by email
const user = await corenect.getUserByEmail('[email protected]');
// Create a user
const newUser = await corenect.createUser({
email: '[email protected]',
name: 'John Doe',
phone: '+27123456789',
});
// Check user's subscription
const subscription = await corenect.getUserSubscription('[email protected]');Subscriptions
// Subscribe a user to a plan
const subscription = await corenect.subscribe({
userEmail: '[email protected]',
userName: 'John Doe',
planId: 'plan_123',
});
// Get subscription status
const status = await corenect.getSubscriptionStatus('sub_123');
console.log(`Days until billing: ${status.subscription.daysUntilBilling}`);
// Cancel a subscription
await corenect.cancelSubscription('sub_123', {
reason: 'Switching to competitor',
cancelImmediately: false, // Cancel at end of billing period
});
// Reactivate a cancelled subscription
await corenect.reactivateSubscription('sub_123');
// Change plan (upgrade/downgrade)
await corenect.changePlan('sub_123', {
newPlanId: 'plan_456',
applyImmediately: true,
});
// Send payment reminder
await corenect.sendPaymentReminder('sub_123');Invoices
// List all invoices
const invoices = await corenect.listInvoices();
// Get an invoice
const invoice = await corenect.getInvoice('inv_123');
// Create an invoice
const newInvoice = await corenect.createInvoice({
userEmail: '[email protected]',
userName: 'John Doe',
items: [
{ description: 'Pro Plan - Monthly', quantity: 1, unitPrice: 2999, total: 2999 },
],
dueDate: '2026-02-28',
});
// Mark invoice as paid
await corenect.markInvoicePaid('inv_123');
// Send invoice email
await corenect.sendInvoiceEmail('inv_123');Payments
// Initiate a payment (returns Paystack checkout URL)
const result = await corenect.initiatePayment({
invoiceId: 'inv_123',
returnUrl: 'https://yoursite.com/payment/success',
cancelUrl: 'https://yoursite.com/payment/cancelled',
});
if (result.paymentUrl) {
// Redirect user to Paystack checkout
window.location.href = result.paymentUrl;
}
// Verify payment after redirect
const verification = await corenect.verifyPayment('EFT-ABCD-XYZ123-001');
console.log(`Verified: ${verification.verified}, Status: ${verification.status}`);
// Check payment status
const payment = await corenect.getPaymentStatus('pay_123');
// Refund a payment
await corenect.refundPayment('pay_123', 1500); // Partial refund
await corenect.refundPayment('pay_123'); // Full refundRecurring Billing
Charge customers automatically using saved card details from their first Paystack payment.
Prerequisites
- Configure the Paystack webhook URL in your Paystack Dashboard → Settings → API Keys & Webhooks
- Customer completes an initial payment via Paystack checkout
- The webhook saves the
authorization_codeto the subscription document automatically
Charge a Single Subscription
// By subscriptionId (recommended) — auto-looks up email, amount, and saved card
const result = await corenect.chargeRecurring({
subscriptionId: 'sub_xyz789',
});
console.log(result);
// {
// success: true,
// message: 'Charge attempted',
// data: {
// reference: 'REC-ABC123-XY4Z',
// status: 'success',
// amount: 699,
// currency: 'ZAR',
// gateway_response: 'Approved'
// }
// }
// With manual parameters
const result = await corenect.chargeRecurring({
email: '[email protected]',
amount: 699,
authorization_code: 'AUTH_xxxxxxxxx',
currency: 'ZAR',
metadata: {
tenantId: 'your_tenant_id',
userId: 'user_123',
subscriptionId: 'sub_xyz789',
planName: 'Professional',
},
});
// Skip auto-invoice creation (if you manage invoicing yourself)
const result = await corenect.chargeRecurring({
subscriptionId: 'sub_xyz789',
createInvoice: false,
});Run Full Billing Cycle
Charges all active subscriptions where nextBillingDate has passed. This runs automatically every day at 6 AM UTC via cron, but you can trigger it manually:
const result = await corenect.runBillingCycle();
console.log(result);
// {
// success: true,
// message: 'Processed 12 subscriptions: 10 charged, 1 failed, 1 skipped',
// summary: { total: 12, charged: 10, failed: 1, skipped: 1 },
// results: [
// { subscriptionId: 'sub_abc', userEmail: '[email protected]', status: 'charged', reference: 'REC-...' },
// { subscriptionId: 'sub_def', userEmail: '[email protected]', status: 'failed', error: 'Insufficient Funds' },
// { subscriptionId: 'sub_ghi', userEmail: '[email protected]', status: 'skipped', error: 'No authorization_code saved' },
// ]
// }Cancel Recurring Billing
await corenect.cancelRecurringSubscription('sub_xyz789', {
reason: 'Customer requested cancellation',
});Complete Recurring Billing Flow
import { Corenect } from '@corenect/sdk';
const corenect = new Corenect({ apiKey: 'sk_live_xxx' });
// Step 1: Create user with plan — returns Paystack checkout URL
const user = await corenect.createUser({
email: '[email protected]',
name: 'Jane Smith',
planId: 'plan_pro',
returnUrl: 'https://yourapp.com/payment-success',
});
// Redirect to user.paymentUrl for initial payment
// Step 2: After payment, verify it
const verification = await corenect.verifyPayment(reference);
// authorization_code is now saved via webhook
// Step 3: Charge recurring (e.g., from a monthly cron job)
const charge = await corenect.chargeRecurring({
subscriptionId: user.subscriptionId!,
});
// Step 4: Or run billing cycle for all due subscriptions
const cycle = await corenect.runBillingCycle();
console.log(`Charged ${cycle.summary.charged} of ${cycle.summary.total} subscriptions`);Error Handling
import { Corenect, CorenectError } from '@corenect/sdk';
try {
const subscription = await corenect.getSubscription('invalid_id');
} catch (error) {
if (error instanceof CorenectError) {
console.log('Error code:', error.code);
console.log('Status:', error.statusCode);
console.log('Message:', error.message);
}
}TypeScript Support
This SDK is written in TypeScript and provides full type definitions:
import type {
Plan,
User,
Subscription,
Invoice,
Payment,
CreateSubscriptionInput,
PaymentResult,
PaymentVerification,
ChargeRecurringInput,
ChargeRecurringResult,
BillingCycleResult,
CancelRecurringInput,
} from '@corenect/sdk';Configuration
Custom Base URL
For self-hosted or staging environments:
const corenect = new Corenect({
apiKey: 'sk_test_xxx',
baseUrl: 'https://staging-api.corenect.dev/v1',
billingBaseUrl: 'https://your-billing-endpoint.com', // Optional: custom billing endpoint
});Pagination
List methods support pagination:
const firstPage = await corenect.listSubscriptions({
page: 1,
pageSize: 20,
sortBy: 'createdAt',
sortOrder: 'desc',
});License
MIT © Corenect Technologies
