ProBuy Backend SDK for Node.js
The ProBuy Backend SDK is a server-side only payment integration solution for Node.js applications. Built with TypeScript, it provides type-safe, secure, and production-ready APIs for creating checkout sessions and managing payments from your backend.
SDK Features
- Server-side only - Your API token never exposed to clients
- TypeScript support - Full type definitions included
- Simple API - Easy to integrate and understand
- Environment support - production
- Comprehensive error handling - Specific error types for better debugging
- Production ready - Battle-tested in live environments
Installation
Install the SDK using npm or yarn. View the package on npm registry.
npm install @probuy/backend-sdk# oryarn add @probuy/backend-sdk# orpnpm add @probuy/backend-sdkRequirements
Node.js version: 18.0.0 or higher
The SDK uses ES modules and requires Node.js 18+ for optimal performance and security features.
Quick Start
Get started with the ProBuy Backend SDK in just a few lines of code:
Quick Integration
Import and Initialize
import { ProBuyBackendSDK } from '@probuy/backend-sdk';
// Initialize SDKconst probuy = new ProBuyBackendSDK({ apiToken: process.env.PROBUY_API_TOKEN, environment: 'prod' debug: true});Prepare Order Data
const orderData = { order_reference_id: 'ref-' + Date.now(), order_number: 'ORD-12345', currency: 'SAR', total_amount: 1000, shipping_amount: 0, tax_amount: 150,
item: { name: 'MacBook Pro 16-inch', description: 'Apple M2 Pro chip with powerful performance', type: 'Physical', reference_id: 'prod-123', sku: 'MBPRO-16-M2', quantity: 1, discount_amount: 0, tax_amount: 150, unit_price: 1000, total_amount: 1000 },
consumer: { first_name: 'Ahmed', last_name: 'Ali', phone_number: '+966501234567' },
country_code: 'SA',
merchant_url: { success: 'https://yoursite.com/payment/success', failure: 'https://yoursite.com/payment/failed', cancel: 'https://yoursite.com/payment/cancelled' },
billing_address: { city: 'Riyadh', country_code: 'SA', first_name: 'Ahmed', last_name: 'Ali', line1: '123 King Fahd Road', line2: 'Apt 456', phone_number: '+966501234567', region: 'Riyadh' },
shipping_address: { city: 'Riyadh', country_code: 'SA', first_name: 'Ahmed', last_name: 'Ali', line1: '123 King Fahd Road', line2: 'Apt 456', phone_number: '+966501234567', region: 'Riyadh' }};Create Checkout Session
try { // Method 1: Create session and get redirect URL const result = await probuy.createCheckoutWithRedirectUrl(orderData);
console.log('Checkout ID:', result.checkout_id); console.log('Redirect customer to:', result.redirect_url);
// Method 2: Create session only const session = await probuy.createCheckoutSession(orderData); const checkoutUrl = probuy.getCheckoutUrl(session.checkout_id);
// Return to frontend for redirection return { success: true, redirect_url: checkoutUrl };
} catch (error) { console.error('Checkout error:', error.message); return { success: false, error: error.message };}SDK Configuration
Configure the SDK with the following options:
| Option | Type | Required | Description |
|---|---|---|---|
apiToken | string | Yes | Your ProBuy API authentication token |
environment | string | No | 'sandbox', or 'prod' (default: 'sandbox') |
timeout | number | No | Request timeout in milliseconds |
retryCount | number | No | Number of retry attempts for failed requests |
debug | boolean | No | Enable debug logging (default: false) |
apiTokenenvironmenttimeoutretryCountdebugAPI Methods
createCheckoutSession()
Creates a new checkout session and returns session details.
const session = await probuy.createCheckoutSession(orderData);
// Success Response:{ checkout_id: "38a41884-4828-4e1f-a9d6-a472c5c56ec5", order_reference_id: "ref-1729425600", checkout_url: "https://company.probuy.me/checkout/38a41884-4828-4e1f-a9d6-a472c5c56ec5", status: "new", expires_at: "2025-10-20T12:00:00Z", created_at: "2025-10-20T11:00:00Z"}Success Response Details
- checkout_id: Unique identifier for the checkout session (UUID)
- checkout_url: URL to redirect customer for payment
- status: Initial status is always "new"
- expires_at: Session expires 30 minutes after creation
getCheckoutUrl()
Gets the full checkout URL for redirecting customers to the payment page.
const checkoutUrl = probuy.getCheckoutUrl(checkoutId);// Returns: https://company.probuy.me/checkout/{checkout_id}
// For development environment:// Returns: https://probuycompanyportaldev.z1.web.core.windows.net/checkout/{checkout_id}createCheckoutWithRedirectUrl()
Convenience method that creates a session and returns the redirect URL in one call.
const result = await probuy.createCheckoutWithRedirectUrl(orderData);
// Response includes all session data plus redirect_url:{ checkout_id: string; order_reference_id: string; checkout_url: string; status: string; expires_at: string; created_at: string; redirect_url: string; // Full URL for customer redirection}getCheckoutDetails()
Retrieves detailed information about an existing checkout session.
const details = await probuy.getCheckoutDetails(checkoutId);
// Success Response:{ checkout_id: "38a41884-4828-4e1f-a9d6-a472c5c56ec5", order_reference_id: "ref-1729425600", order_number: "ORD-12345", currency: "SAR", total_amount: 1000.00, tax_amount: 150.00, status: "approved", // new, approved, authorized, declined, expired, cancelled, completed consumer: { first_name: "Ahmed", last_name: "Ali", phone_number: "+966501234567" }, created_at: "2025-10-20T11:00:00Z", updated_at: "2025-10-20T11:15:00Z", expires_at: "2025-10-20T12:00:00Z", merchant_url: { success: "https://yoursite.com/payment/success", failure: "https://yoursite.com/payment/failed", cancel: "https://yoursite.com/payment/cancelled" }}Possible Status Values
| Status | Description | Recommended Action |
|---|---|---|
new | Checkout created, awaiting customer action | Wait for customer to complete payment |
approved | Payment approved by payment provider | Proceed with order processing |
authorized | Payment authorized and funds reserved | Capture payment and fulfill order |
declined | Payment declined by payment provider | Notify customer, offer alternative payment |
expired | Checkout session expired (30 minutes) | Create new checkout session |
cancelled | Customer cancelled the payment | Allow customer to retry |
completed | Order completed and finalized | No action required |
newapprovedauthorizeddeclinedexpiredcancelledcompletedError Handling
The SDK provides comprehensive error types for better error handling:
import { ProBuyError, ProBuyValidationError, ProBuyAuthenticationError, ProBuyNetworkError, ProBuyApiError} from '@probuy/backend-sdk';
try { const session = await probuy.createCheckoutSession(orderData);} catch (error) { if (error instanceof ProBuyValidationError) { // Invalid order data - Error Response Example: // { // error: "ValidationError", // message: "Invalid request data", // details: { // total_amount: "Must be greater than 100", // consumer.email: "Invalid email format" // } // } console.error('Validation error:', error.message, error.details); return { error: 'Invalid order data', details: error.details }; } else if (error instanceof ProBuyAuthenticationError) { // Invalid or expired API token - Error Response Example: // { // error: "AuthenticationError", // message: "Invalid or expired API token" // } console.error('Authentication error:', error.message); return { error: 'Authentication failed' }; } else if (error instanceof ProBuyNetworkError) { // Network connectivity issues console.error('Network error:', error.message); return { error: 'Connection failed, please try again' }; } else if (error instanceof ProBuyApiError) { // API returned an error - Error Response Example: // { // error: "ServerError", // message: "An unexpected error occurred. Please try again later.", // statusCode: 500 // } console.error('API error:', error.statusCode, error.message); return { error: 'Payment service error' }; } else { // Unknown error console.error('Unknown error:', error); return { error: 'An unexpected error occurred' }; }}Common Error Scenarios
Validation Error (400)
Occurs when order data is invalid or missing required fields:
{ "error": "ValidationError", "message": "Invalid request data", "details": { "total_amount": "Must be greater than 100", "consumer.email": "Invalid email format", "currency": "SAR" }}Authentication Error (401)
Occurs when API token is invalid or expired:
{ "error": "AuthenticationError", "message": "Invalid or expired API token"}Server Error (500)
Occurs when ProBuy service encounters an error:
{ "error": "ServerError", "message": "An unexpected error occurred. Please try again later."}Error Types
| Error Type | Status Code | When It Occurs |
|---|---|---|
ProBuyValidationError | 400 | Missing or invalid order data fields |
ProBuyAuthenticationError | 401 | Invalid or expired API token |
ProBuyNetworkError | โ | Network connectivity issues or timeouts |
ProBuyApiError | 4xx/5xx | API server errors or rate limits |
ProBuyValidationErrorProBuyAuthenticationErrorProBuyNetworkErrorProBuyApiErrorTypeScript Support
The SDK is built with TypeScript and includes full type definitions:
import { ProBuyBackendSDK, ProBuyConfig, CheckoutOrderData, CheckoutSessionResponse, CheckoutDetailedResponse, ProBuyEnvironment} from '@probuy/backend-sdk';
// Type-safe configurationconst config: ProBuyConfig = { apiToken: process.env.PROBUY_API_TOKEN!, environment: 'sandbox' as ProBuyEnvironment, debug: true};
const probuy = new ProBuyBackendSDK(config);
// Type-safe order dataconst orderData: CheckoutOrderData = { order_reference_id: 'ref-123', order_number: 'ORD-123', currency: 'SAR', total_amount: 1000, // ... TypeScript will validate all fields};
// Type-safe responsesconst session: CheckoutSessionResponse = await probuy.createCheckoutSession(orderData);
const details: CheckoutDetailedResponse = await probuy.getCheckoutDetails(session.checkout_id);Express.js Integration Example
Complete example of integrating the SDK in an Express.js application:
import express from 'express';import { ProBuyBackendSDK } from '@probuy/backend-sdk';
const app = express();app.use(express.json());
// Initialize SDKconst probuy = new ProBuyBackendSDK({ apiToken: process.env.PROBUY_API_TOKEN, environment: process.env.PROBUY_ENVIRONMENT || 'sandbox', debug: process.env.NODE_ENV !== 'production'});
// Create checkout endpointapp.post('/api/checkout/create', async (req, res) => { try { const session = await probuy.createCheckoutWithRedirectUrl(req.body);
res.json({ success: true, checkout_id: session.checkout_id, redirect_url: session.redirect_url }); } catch (error) { console.error('Checkout error:', error.message);
res.status(error.statusCode || 500).json({ success: false, error: error.message, code: error.code }); }});
// Get checkout statusapp.get('/api/checkout/:id', async (req, res) => { try { const details = await probuy.getCheckoutDetails(req.params.id); res.json({ success: true, data: details }); } catch (error) { res.status(500).json({ success: false, error: error.message }); }});
app.listen(3000, () => { console.log('Server running on port 3000'); console.log('Environment:', probuy.getEnvironment());});Security Best Practices
Important Security Guidelines
DO's:
- โ Store API tokens in environment variables - Never hardcode them
- โ Use server-side only - This SDK is for backend use only
- โ Validate order data - Always validate data before sending
- โ Use HTTPS in production - Secure all API communications
- โ Rotate API tokens regularly - Change tokens periodically
- โ Handle errors appropriately - Never expose internal errors
DON'Ts:
- โ Never commit tokens to Git - Use .env files and .gitignore
- โ Never expose tokens in client code - Backend only!
- โ Never log full API tokens - Mask sensitive data in logs
- โ Don't use dev keys in production - Use proper environment tokens
Environment Variables Setup
Recommended .env file configuration:
# ProBuy ConfigurationPROBUY_API_TOKEN=your_api_token_herePROBUY_ENVIRONMENT=sandboxPROBUY_DEBUG=true
# Server ConfigurationNODE_ENV=developmentPORT=3000Getting Your API Token
To obtain your API token:
- Log in to the Supplier Portal
- Navigate to Integrations โ API Tokens
- Click "Create New Token"
- Copy the token immediately - it will only be shown once!
Testing Your Integration
Testing Checklist
- Set
environment: 'sandbox'in SDK configuration - Use a development API token from Supplier Portal
- Create a test order with valid data
- Verify checkout session is created successfully
- Test the redirect URL in a browser
- Complete the checkout flow in Company Portal
- Verify success/failure redirects work correctly
- Test error scenarios (invalid data, network errors)
- Check error handling works as expected
- Test with different order amounts and currencies
Next Steps
Code Examples
Explore real-world integration examples for Express, NestJS, Fastify, and more.
View Examples โTesting Guide
Learn how to thoroughly test your integration before going live.
Read Testing Guide โNeed Help?
If you encounter any issues or have questions:
- ๐ง Email: [email protected]
- ๐ Review the Testing Guide for common validation steps.
- ๐ฌ Contact your account manager for technical support
- ๐ Report issues on GitHub