@cosmic-payment/gateway-sdk
v0.1.1
Published
Cosmic Gateway — official Node.js client SDK for payment processing
Maintainers
Readme
Cosmic Gateway SDK
Official Node.js client SDK for the Cosmic Gateway payment processing API.
Features
- Complete payment lifecycle — charge, capture, refund, and query payments
- Customer management — create, retrieve, and list customers
- Transaction history — paginated transaction listing with filters
- Webhook verification — HMAC-SHA256 signature verification for incoming webhooks
- Idempotency — automatic idempotency key generation to safely retry requests
- Retry with backoff — automatic retry on 5xx errors and rate limits (429)
- Request timeout — configurable timeout per request
- Environment switching — built-in sandbox and production endpoints
- Input validation — pre-flight validation of amounts, currencies, emails, and more
- Strong typing — full TypeScript declarations for all requests and responses
- Sensitive data masking — automatic masking of PAN, CVC, and secrets in logs
Installation
npm install @cosmic-payment/gateway-sdkRequires Node.js 18+ (for native fetch and crypto.randomUUID).
Quick Start
import { CosmicGateway } from '@cosmic-payment/gateway-sdk';
const client = new CosmicGateway({
merchantId: process.env.COSMIC_MERCHANT_ID!,
environment: 'sandbox', // or 'production'
});
async function run() {
const result = await client.payments.charge({
amount: 1999, // $19.99 in cents
currency: 'usd',
source: 'tok_visa_4242', // payment token
description: 'Test payment',
metadata: { orderId: 'ORD-12345' },
});
if (result.success) {
console.log('Payment ID:', result.transactionId);
console.log('New balance:', result.newBalance);
} else {
console.error('Payment failed:', result.status);
}
}
run().catch(console.error);Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| merchantId | string | required | Your merchant identifier |
| environment | 'sandbox' \| 'production' | 'production' | API environment preset |
| baseUrl | string | environment default | Custom API base URL (overrides environment) |
| timeout | number | 30000 | Request timeout in milliseconds |
| retry.maxRetries | number | 3 | Maximum retry attempts on 5xx/429 |
| retry.baseDelayMs | number | 200 | Initial backoff delay |
| retry.maxDelayMs | number | 5000 | Maximum backoff delay |
| logger.level | string | 'info' | Log level: 'debug', 'info', 'warn', 'error', 'silent' |
Environment URLs
| Environment | URL |
|-------------|-----|
| sandbox | https://api.sandbox.cosmicgateway.com |
| production | https://api.cosmicgateway.com |
API Reference
Payments
client.payments.charge(request)
Process a payment charge.
const result = await client.payments.charge({
amount: 1999,
currency: 'usd',
source: 'tok_abc123',
description: 'Order #1234',
metadata: { orderId: 'ORD-12345' },
idempotencyKey: 'uuid-v4', // optional — auto-generated if omitted
});Success response:
{
success: true,
transactionId: string;
referenceId: string;
processor: string;
region: string;
amount: number;
currency: string;
settlement?: { from, to, originalAmount, convertedAmount, rate };
newBalance: number;
fraudScore: number;
kycVerified: string;
}Failed response:
{
success: false,
transactionId: string;
referenceId: null;
processor: string;
region: string;
status: 'failed';
}client.payments.retrieve(paymentId)
Retrieve payment details by ID.
client.payments.list(params?)
List payments with optional filtering.
const result = await client.payments.list({
page: 1,
limit: 20,
status: 'SUCCESS',
startDate: '2026-01-01T00:00:00Z',
endDate: '2026-12-31T23:59:59Z',
});Refunds
client.refunds.create(request)
Create a refund for a payment.
const result = await client.refunds.create({
paymentId: 'pay_abc123',
amount: 500, // partial refund (optional, defaults to full)
reason: 'Customer requested refund',
metadata: { ticketId: 'TKT-999' },
});client.refunds.retrieve(refundId)
client.refunds.list(params?)
Customers
client.customers.create(request)
client.customers.retrieve(customerId)
client.customers.list(params?)
Transactions
client.transactions.list(params?)
client.transactions.retrieve(transactionId)
Webhook Verification
import { verifyWebhookSignature } from '@cosmic-payment/gateway-sdk';
const event = verifyWebhookSignature(rawBody, signatureHeader, webhookSecret);
// { event: 'payment.succeeded', transactionId: 'txn_1', ... }The SDK verifies the sha256= HMAC signature using timing-safe comparison.
Health Check
const health = await client.health();
// { status: 'ok' }Error Handling
The SDK throws typed errors for all failure modes:
| Error Class | HTTP Status | When |
|-------------|-------------|------|
| ValidationError | 400 | Invalid input |
| AuthenticationError | 401 | Missing or invalid credentials |
| PaymentFailedError | 402 | Payment was declined |
| NotFoundError | 404 | Resource not found |
| RateLimitError | 429 | Too many requests |
| ServerError | 500 | Gateway internal error |
| ServiceUnavailableError | 503 | Service temporarily down |
| WebhookVerificationError | — | Webhook signature invalid |
import { PaymentFailedError, ValidationError } from '@cosmic-payment/gateway-sdk';
try {
await client.payments.charge({ amount: -1, currency: 'usd', source: 'tok_abc' });
} catch (err) {
if (err instanceof ValidationError) {
console.error('Bad input:', err.message);
} else if (err instanceof PaymentFailedError) {
console.error('Payment declined:', err.transactionId);
}
}Retry Behavior
- 5xx errors — retried with exponential backoff (base delay doubles each attempt)
- 429 rate limits — respects
Retry-Afterheader - Network errors — retried as transient failures
- 4xx errors (except 429) — not retried (these are client errors)
- Configurable via
retry.maxRetries,retry.baseDelayMs,retry.maxDelayMs
Idempotency
All mutation endpoints (charge, create, etc.) accept an optional idempotencyKey. If omitted, a UUID v4 is generated automatically. The gateway uses the merchantId + idempotencyKey pair to detect duplicate requests and return the cached response.
Sensitive Data Masking
The logger automatically masks sensitive fields (PAN, CVC, API keys, auth tokens) in logs. Use the debug log level to inspect request/response shapes without exposing secrets.
Development
npm install
npm run build
npm test
npm run test:coverageLicense
ISC
