@cloudbank/nextjs
v0.3.0
Published
CloudBank SDK integration for Next.js applications
Maintainers
Readme
CloudBank Next.js SDK
This package provides Next.js-specific utilities for integrating with CloudBank's payment infrastructure, including checkout sessions and webhook handling.
Installation
npm install @cloudbank/nextjs @cloudbank/sdk
# or
bun add @cloudbank/nextjs @cloudbank/sdkFeatures
- Checkout Sessions: Create and manage checkout sessions for payments
- Webhooks: Handle webhook events with type-safe validation
- Event Handlers: Granular event handling for different webhook types
- TypeScript Support: Full TypeScript support with comprehensive type definitions
Usage
Checkout Sessions
CloudBank Checkout
// app/api/checkout/route.ts
import { Checkout } from '@cloudbank/nextjs';
export const GET = Checkout({
accessToken: process.env.CLOUDBANK_ACCESS_TOKEN!,
provider: 'cloudbank', // Optional, defaults to 'cloudbank'
successUrl: 'https://yourapp.com/success?session_id={session_id}',
cancelUrl: 'https://yourapp.com/cancel',
server: 'staging', // or 'production'
});MagePay Checkout
// app/api/checkout/route.ts
import { Checkout } from '@cloudbank/nextjs';
export const GET = Checkout({
accessToken: process.env.MAGEPAY_ACCESS_TOKEN!,
provider: 'magepay',
successUrl: 'https://yourapp.com/success?session_id={session_id}',
cancelUrl: 'https://yourapp.com/cancel',
server: 'production',
});Webhooks
Basic Webhook Handler
// app/api/webhooks/cloudbank/route.ts
import { Webhooks } from '@cloudbank/nextjs';
export const POST = Webhooks({
webhookSecret: process.env.CLOUDBANK_WEBHOOK_SECRET!,
provider: 'cloudbank', // Optional, defaults to 'cloudbank'
onPayload: async (payload) => {
console.log('Received webhook:', payload.event_type);
// Handle any webhook event
},
});For MagePay webhooks:
// app/api/webhooks/magepay/route.ts
import { Webhooks } from '@cloudbank/nextjs';
export const POST = Webhooks({
webhookSecret: process.env.MAGEPAY_WEBHOOK_SECRET!,
provider: 'magepay',
onPayload: async (payload) => {
console.log('Received MagePay webhook:', payload.event_type);
},
});Granular Event Handlers
// app/api/webhooks/cloudbank/route.ts
import { Webhooks } from '@cloudbank/nextjs';
export const POST = Webhooks({
webhookSecret: process.env.CLOUDBANK_WEBHOOK_SECRET!,
// Checkout Session Events
onCheckoutSessionCreated: async (event) => {
console.log('Checkout session created:', event.data.session_id);
},
onCheckoutSessionPaymentSucceeded: async (event) => {
console.log('Payment succeeded for session:', event.data.session_id);
// Update your database, send confirmation emails, etc.
},
onCheckoutSessionCompleted: async (event) => {
console.log('Checkout session completed:', event.data.session_id);
// Finalize the order
},
// Payment Events
onPaymentCreated: async (event) => {
console.log('Payment created:', event.data.payment_id);
},
onPaymentSucceeded: async (event) => {
console.log('Payment succeeded:', event.data.payment_id);
// Update payment status in your database
},
onPaymentFailed: async (event) => {
console.log('Payment failed:', event.data.payment_id);
console.log('Failure reason:', event.data.failure_message);
},
// Payment Intent Events
onPaymentIntentSucceeded: async (event) => {
console.log('Payment intent succeeded:', event.data.payment_intent_id);
},
onPaymentIntentFailed: async (event) => {
console.log('Payment intent failed:', event.data.payment_intent_id);
},
});Available Event Handlers
Checkout Session Events:
onCheckoutSessionCreatedonCheckoutSessionPaymentFailedonCheckoutSessionPaymentSucceededonCheckoutSessionCompletedonCheckoutSessionCanceled
Payment Events:
onPaymentCreatedonPaymentProcessingonPaymentCanceledonPaymentSucceededonPaymentFailedonPaymentRefunded
Payment Intent Events:
onPaymentIntentCreatedonPaymentIntentRequiresConfirmationonPaymentIntentConfirmedonPaymentIntentCapturedonPaymentIntentProcessingonPaymentIntentSucceededonPaymentIntentCanceledonPaymentIntentFailed
Environment Variables
Make sure to set these environment variables:
# CloudBank API credentials
CLOUDBANK_ACCESS_TOKEN=your_access_token
CLOUDBANK_WEBHOOK_SECRET=your_webhook_secretError Handling
The webhook handler includes comprehensive error handling:
import { Webhooks, WebhookValidationError } from '@cloudbank/nextjs';
export const POST = Webhooks({
webhookSecret: process.env.CLOUDBANK_WEBHOOK_SECRET!,
onPayload: async (payload) => {
try {
// Your webhook handling logic
await processWebhookEvent(payload);
} catch (error) {
if (error instanceof WebhookValidationError) {
console.error('Webhook validation failed:', error.message);
} else {
console.error('Webhook processing failed:', error);
}
throw error; // Re-throw to return appropriate HTTP status
}
},
});TypeScript Support
The package provides full TypeScript support with proper typing for all webhook events:
import type {
WebhookEvent,
CheckoutSessionCreatedHandler,
PaymentSucceededHandler
} from '@cloudbank/nextjs';
const handleCheckoutCreated: CheckoutSessionCreatedHandler = async (event) => {
// event.data is properly typed as CheckoutSessionCreatedEvent
console.log('Session ID:', event.data.session_id);
console.log('Amount:', event.data.amount.value, event.data.amount.currency);
};
const handlePaymentSucceeded: PaymentSucceededHandler = async (event) => {
// event.data is properly typed as PaymentSucceededEvent
console.log('Payment ID:', event.data.payment_id);
console.log('Amount received:', event.data.amount_received.value);
};Webhook Security
The webhook handler automatically validates webhook signatures using HMAC-SHA256:
- Webhooks are validated using the
x-cloudbank-signatureheader - Invalid signatures result in a 401 Unauthorized response
- Missing signatures result in a 401 Unauthorized response
Testing Webhooks Locally
For local development, you can use tools like ngrok to tunnel webhook events:
# Install ngrok
npm install -g ngrok
# Start your Next.js app
npm run dev
# In another terminal, expose your local server
ngrok http 3000
# Use the ngrok URL as your webhook endpoint
# Example: https://abc123.ngrok.io/api/webhooks/cloudbankCheckout Configuration
Required Parameters
amount: Payment amount (numeric value)
Optional Parameters
external_id: Your internal reference ID (auto-generated if not provided)description: Payment descriptioncustomer_email: Customer email addresscustomer_name: Customer namecustomer_id: Existing customer IDmetadata: URL-encoded JSON metadata object
Example Usage
// Redirect user to checkout
const checkoutUrl = new URL('/api/checkout', 'https://yourapp.com');
checkoutUrl.searchParams.set('amount', '100.00');
checkoutUrl.searchParams.set('description', 'Premium subscription');
checkoutUrl.searchParams.set('customer_email', '[email protected]');
checkoutUrl.searchParams.set('external_id', 'order_123');
// Redirect user to checkoutUrl.toString()API Reference
CheckoutConfig
interface CheckoutConfig {
accessToken: string;
provider?: 'cloudbank' | 'magepay'; // Defaults to 'cloudbank'
successUrl: string;
cancelUrl?: string;
failureUrl?: string;
server?: 'staging' | 'production';
mode?: 'payment' | 'subscription';
}WebhookConfig
interface WebhookConfig {
webhookSecret: string;
provider?: 'cloudbank' | 'magepay'; // Defaults to 'cloudbank'
onPayload?: (payload: WebhookEvent) => Promise<void> | void;
// Event handlers for all supported events
onCheckoutSessionCreated?: (event: WebhookEvent<'checkout_session.created'>) => Promise<void> | void;
onCheckoutSessionPaymentFailed?: (event: WebhookEvent<'checkout_session.payment_failed'>) => Promise<void> | void;
onCheckoutSessionPaymentSucceeded?: (event: WebhookEvent<'checkout_session.payment_succeeded'>) => Promise<void> | void;
onCheckoutSessionCompleted?: (event: WebhookEvent<'checkout_session.completed'>) => Promise<void> | void;
onCheckoutSessionCanceled?: (event: WebhookEvent<'checkout_session.canceled'>) => Promise<void> | void;
// ... and more for payment and payment_intent events
}