ProBuy Logo
PB

ProBuy Docs

Version 1.0

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.

Installation

Install the SDK using npm or yarn. View the package on npm registry.

npm install @probuy/backend-sdk
# or
yarn add @probuy/backend-sdk
# or
pnpm add @probuy/backend-sdk

Quick Start

Get started with the ProBuy Backend SDK in just a few lines of code:

Quick Integration

1

Import and Initialize

import { ProBuyBackendSDK } from '@probuy/backend-sdk';
// Initialize SDK
const probuy = new ProBuyBackendSDK({
apiToken: process.env.PROBUY_API_TOKEN,
environment: 'prod'
debug: true
});
2

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'
}
};
3

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
apiToken
Type
string
Required
Yes
Description
Your ProBuy API authentication token
Option
environment
Type
string
Required
No
Description
'sandbox', or 'prod' (default: 'sandbox')
Option
timeout
Type
number
Required
No
Description
Request timeout in milliseconds
Option
retryCount
Type
number
Required
No
Description
Number of retry attempts for failed requests
Option
debug
Type
boolean
Required
No
Description
Enable debug logging (default: false)

API 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"
}

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
new
Description
Checkout created, awaiting customer action
Recommended Action
Wait for customer to complete payment
Status
approved
Description
Payment approved by payment provider
Recommended Action
Proceed with order processing
Status
authorized
Description
Payment authorized and funds reserved
Recommended Action
Capture payment and fulfill order
Status
declined
Description
Payment declined by payment provider
Recommended Action
Notify customer, offer alternative payment
Status
expired
Description
Checkout session expired (30 minutes)
Recommended Action
Create new checkout session
Status
cancelled
Description
Customer cancelled the payment
Recommended Action
Allow customer to retry
Status
completed
Description
Order completed and finalized
Recommended Action
No action required

Error 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
ProBuyValidationError
Status Code
400
When It Occurs
Missing or invalid order data fields
Error Type
ProBuyAuthenticationError
Status Code
401
When It Occurs
Invalid or expired API token
Error Type
ProBuyNetworkError
Status Code
โ€”
When It Occurs
Network connectivity issues or timeouts
Error Type
ProBuyApiError
Status Code
4xx/5xx
When It Occurs
API server errors or rate limits

TypeScript 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 configuration
const config: ProBuyConfig = {
apiToken: process.env.PROBUY_API_TOKEN!,
environment: 'sandbox' as ProBuyEnvironment,
debug: true
};
const probuy = new ProBuyBackendSDK(config);
// Type-safe order data
const orderData: CheckoutOrderData = {
order_reference_id: 'ref-123',
order_number: 'ORD-123',
currency: 'SAR',
total_amount: 1000,
// ... TypeScript will validate all fields
};
// Type-safe responses
const 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 SDK
const probuy = new ProBuyBackendSDK({
apiToken: process.env.PROBUY_API_TOKEN,
environment: process.env.PROBUY_ENVIRONMENT || 'sandbox',
debug: process.env.NODE_ENV !== 'production'
});
// Create checkout endpoint
app.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 status
app.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

Environment Variables Setup

Recommended .env file configuration:

# ProBuy Configuration
PROBUY_API_TOKEN=your_api_token_here
PROBUY_ENVIRONMENT=sandbox
PROBUY_DEBUG=true
# Server Configuration
NODE_ENV=development
PORT=3000

Testing Your Integration

Next Steps

Need Help?