Back to Samples
API Documentation

Payment Gateway SDK

March 25, 2024
20 min read
v2.0
99.99%
API Uptime
<100ms
Avg Response Time
50+
API Endpoints
v2.0
Latest Version

Welcome to the Payment Gateway SDK documentation. Whether you're building a SaaS application, an e-commerce platform, or a marketplace, accepting payments is critical to your business. Our SDK makes it simple to integrate secure, PCI-compliant payment processing into your application with just a few lines of code.

This documentation is designed for developers who want to get up and running quickly while understanding the underlying concepts. We provide code examples in multiple languages (Node.js, Python, Ruby, and cURL), comprehensive API references, and best practices for production deployments. Let's get started!

Quick Start

Get started with the Payment Gateway SDK in minutes. Install the package and start processing payments. Our SDK handles all the complexity of payment processing,tokenization, 3D Secure authentication, webhook management, and more,so you can focus on building your product.

1

Install

Add the SDK to your project

2

Authenticate

Configure with your API key

3

Process

Start accepting payments

Installation

npm install @paymentgateway/sdk

Authentication

All API requests require authentication using your API key. You can find your API key in the dashboard under Settings → API Keys. We use HTTP Basic Authentication where your API key is the username and the password is left empty.

We provide two types of API keys: test keys (starting with sk_test_) for development and live keys (starting with sk_live_) for production. Test keys interact with our sandbox environment where no real money is processed. Live keys process real payments and should be kept secure.

⚠️ Security Note: Never expose your API key in client-side code. Always make API calls from your server.

const PaymentGateway = require('@paymentgateway/sdk');

const client = new PaymentGateway({
  apiKey: 'sk_test_your_api_key',
  environment: 'production' // or 'sandbox'
});

API Reference

Create Payment Intent

Creates a new payment intent to collect payment from a customer.

POST/v1/payment-intents

Parameters

ParameterTypeRequiredDescription
amountintegerYesAmount in cents
currencystringYesThree-letter ISO currency code
customerstringNoCustomer ID
descriptionstringNoDescription of the payment

Example Request

const PaymentGateway = require('@paymentgateway/sdk');

const client = new PaymentGateway({
  apiKey: 'sk_test_your_api_key',
  environment: 'production'
});

const paymentIntent = await client.paymentIntents.create({
  amount: 2000,
  currency: 'usd',
  customer: 'cus_123456',
  description: 'Software subscription'
});

console.log(paymentIntent);

Success Response

200 OK
{
  "id": "pi_1234567890",
  "object": "payment_intent",
  "amount": 2000,
  "amount_received": 0,
  "currency": "usd",
  "status": "requires_payment_method",
  "client_secret": "pi_1234567890_secret_abcdef",
  "customer": "cus_123456",
  "description": "Software subscription",
  "payment_method": null,
  "created": 1234567890,
  "livemode": false,
  "metadata": {},
  "next_action": null,
  "receipt_email": null,
  "setup_future_usage": null
}

Understanding Payment Intent Status

requires_payment_methodPayment intent created, waiting for payment method
requires_confirmationPayment method attached, needs confirmation
processingPayment is being processed
succeededPayment completed successfully
canceledPayment was canceled

Confirm Payment Intent

Confirms a payment intent and attempts to process the payment.

POST/v1/payment-intents/:id/confirm

Example Request

const confirmed = await client.paymentIntents.confirm(
  'pi_1234567890',
  {
    payment_method: 'pm_card_visa'
  }
);

console.log(confirmed);

Create Customer

Creates a new customer object.

POST/v1/customers

Example Request

const customer = await client.customers.create({
  email: '[email protected]',
  name: 'John Doe',
  phone: '+1234567890',
  metadata: {
    user_id: '12345'
  }
});

console.log(customer);

List Payment Intents

Returns a list of payment intents. Results are paginated and can be filtered by customer or status.

GET/v1/payment-intents

Query Parameters

ParameterTypeDescription
limitintegerNumber of results (1-100, default: 10)
starting_afterstringCursor for pagination
customerstringFilter by customer ID
statusstringFilter by status (succeeded, failed, pending)

Example Request

const payments = await client.paymentIntents.list({
  limit: 10,
  customer: 'cus_123456',
  status: 'succeeded'
});

console.log(payments.data);
console.log('Has more:', payments.has_more);

Create Refund

Refunds a payment that has been previously created. Refunds can be partial or full.

POST/v1/refunds
ℹ️
Refund Processing
Refunds typically appear on the customer's statement within 5-10 business days.

Example Request

const refund = await client.refunds.create({
  payment_intent: 'pi_1234567890',
  amount: 1000, // Partial refund of $10.00
  reason: 'requested_by_customer'
});

console.log(refund);

Create Subscription

Creates a subscription for recurring payments. Supports multiple pricing tiers and billing intervals.

POST/v1/subscriptions

Parameters

ParameterTypeRequiredDescription
customerstringYesCustomer ID
pricestringYesPrice ID
trial_daysintegerNoFree trial period in days
payment_methodstringNoPayment method ID

Example Request

const subscription = await client.subscriptions.create({
  customer: 'cus_123456',
  price: 'price_monthly_pro',
  trial_days: 14,
  payment_method: 'pm_card_visa',
  metadata: {
    plan: 'pro',
    source: 'website'
  }
});

console.log(subscription);

Pagination

All list endpoints return paginated results. Use the has_more field and starting_after parameter to iterate through pages.

Response Structure

{
  "object": "list",
  "data": [...],
  "has_more": true,
  "url": "/v1/payment-intents"
}

Iterating Through Pages

let allPayments = [];
let hasMore = true;
let startingAfter = null;

while (hasMore) {
  const response = await client.paymentIntents.list({
    limit: 100,
    starting_after: startingAfter
  });
  
  allPayments = allPayments.concat(response.data);
  hasMore = response.has_more;
  
  if (hasMore) {
    startingAfter = response.data[response.data.length - 1].id;
  }
}

console.log(`Total payments: ${allPayments.length}`);

Complete Payment Flow

Understanding the Payment Process

Processing a payment involves multiple steps to ensure security and reliability. Here's the complete flow:

1

Create Payment Intent

POST /v1/payment-intents

Initialize a payment with amount and currency. This creates a payment intent in 'requires_payment_method' status.

2

Collect Payment Method

Client-side collection

Securely collect card details from the customer using our client-side SDK or hosted payment page.

3

Confirm Payment

POST /v1/payment-intents/:id/confirm

Confirm the payment intent with the payment method. Status changes to 'processing' then 'succeeded' or 'requires_action'.

4

Handle 3D Secure (if required)

next_action.redirect_to_url

If the card requires authentication, redirect customer to complete 3D Secure verification.

5

Receive Webhook

payment_intent.succeeded

Listen for 'payment_intent.succeeded' webhook to confirm payment completion on your server.

6

Fulfill Order

Your business logic

Once payment is confirmed, fulfill the order and send confirmation to customer.

✅ Successful Payment

Scenario
Customer's card is valid, has sufficient funds, and doesn't require 3D Secure.
Flow
Create → Confirm → Processing → Succeeded
Timeline
Typically completes in 2-5 seconds

🔐 3D Secure Required

Scenario
Card requires Strong Customer Authentication (SCA) for regulatory compliance.
Flow
Create → Confirm → Requires Action → Customer Auth → Succeeded
Action Required
Redirect customer to next_action.redirect_to_url

❌ Payment Declined

Scenario
Card declined due to insufficient funds, expired card, or fraud detection.
Flow
Create → Confirm → Failed
Next Steps
Ask customer to try different payment method

⏳ Async Payment

Scenario
Payment methods like bank transfers that take days to complete.
Flow
Create → Confirm → Processing → (Wait) → Succeeded
Important
Must use webhooks to detect completion

Error Responses

All errors return a consistent JSON structure with detailed information to help you debug issues.

Error Response Format

{
  "error": {
    "type": "card_error",
    "code": "card_declined",
    "message": "Your card was declined.",
    "decline_code": "insufficient_funds",
    "param": "payment_method",
    "charge": "ch_1234567890"
  }
}
card_error402

Card was declined

Example Response:
{
  "error": {
    "type": "card_error",
    "code": "card_declined",
    "decline_code": "insufficient_funds",
    "message": "Your card has insufficient funds."
  }
}
Common Causes:
  • Insufficient funds
  • Expired card
  • Incorrect CVC
  • Card reported lost/stolen
invalid_request_error400

Invalid parameters

Example Response:
{
  "error": {
    "type": "invalid_request_error",
    "code": "parameter_invalid_integer",
    "message": "Invalid integer: abc",
    "param": "amount"
  }
}
Common Causes:
  • Missing required parameter
  • Invalid parameter type
  • Parameter out of range
  • Invalid currency code
authentication_error401

Authentication failed

Example Response:
{
  "error": {
    "type": "authentication_error",
    "code": "invalid_api_key",
    "message": "Invalid API Key provided."
  }
}
Common Causes:
  • Invalid API key
  • Expired API key
  • API key for wrong environment
  • Missing API key
rate_limit_error429

Too many requests

Example Response:
{
  "error": {
    "type": "rate_limit_error",
    "message": "Too many requests. Please try again later."
  }
}
Common Causes:
  • Exceeded rate limit
  • Too many concurrent requests
  • Burst limit exceeded

Handling Errors in Your Code

try {
  const payment = await client.paymentIntents.create({
    amount: 2000,
    currency: 'usd'
  });
  console.log('Payment created:', payment.id);
} catch (error) {
  if (error.type === 'card_error') {
    // Card was declined
    console.error('Card declined:', error.decline_code);
    // Show user-friendly message
  } else if (error.type === 'invalid_request_error') {
    // Invalid parameters
    console.error('Invalid request:', error.message);
  } else if (error.type === 'authentication_error') {
    // Authentication failed
    console.error('Auth error:', error.message);
  } else {
    // Other error
    console.error('Unexpected error:', error);
  }
}

Webhooks

Why Use Webhooks?

Webhooks provide real-time notifications about events in your account. Instead of polling our API, we'll push updates to your server immediately when events occur. This is essential for:

Real-time Updates
Get notified instantly when payments complete
🔄
Async Payments
Handle payments that take days to complete
📊
Reliability
Automatic retries ensure delivery
20+
Event Types
3x
Retry Attempts
256-bit
HMAC Signature
30 days
Event History

Setting Up Webhooks

1
Create Endpoint
Set up an HTTPS endpoint on your server to receive webhook events
https://yourdomain.com/webhooks
2
Register in Dashboard
Add your endpoint URL in the API settings and select events to receive
3
Verify Signatures
Implement signature verification to ensure webhooks are from us
4
Test & Deploy
Use test mode to verify your integration before going live

Webhook Event Types

Payment Intents

payment_intent.createdPayment intent created
payment_intent.succeededPayment completed successfully
payment_intent.failedPayment attempt failed
payment_intent.canceledPayment was canceled
payment_intent.processingPayment is processing

Customers

customer.createdNew customer created
customer.updatedCustomer details updated
customer.deletedCustomer was deleted

Subscriptions

subscription.createdNew subscription started
subscription.updatedSubscription modified
subscription.deletedSubscription canceled
subscription.trial_will_endTrial ending in 3 days

Refunds

refund.createdRefund initiated
refund.updatedRefund status changed
refund.failedRefund failed

Webhook Payload Structure

All webhook events follow a consistent structure with the event type, data object, and metadata.

{
  "id": "evt_1234567890",
  "object": "event",
  "type": "payment_intent.succeeded",
  "created": 1234567890,
  "livemode": false,
  "data": {
    "object": {
      "id": "pi_1234567890",
      "object": "payment_intent",
      "amount": 2000,
      "currency": "usd",
      "status": "succeeded",
      "customer": "cus_123456",
      "description": "Software subscription",
      "metadata": {
        "order_id": "12345",
        "user_id": "67890"
      }
    }
  },
  "pending_webhooks": 1,
  "request": {
    "id": "req_1234567890",
    "idempotency_key": "unique-key-123"
  }
}
Event ID
Unique identifier for this webhook event
Event Type
The type of event that occurred
Data Object
The full object that triggered the event
Metadata
Custom data you attached to the object

🔐 Signature Verification

Critical: Always verify webhook signatures to ensure requests are from our servers and haven't been tampered with.

⚠️
Security Warning
Without signature verification, attackers could send fake webhooks to your endpoint. Always verify signatures in production.

Implementation

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}

// Express endpoint
app.post('/webhooks', express.raw({type: 'application/json'}), (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const webhookSecret = process.env.WEBHOOK_SECRET;
  
  if (!verifyWebhookSignature(req.body, signature, webhookSecret)) {
    return res.status(401).send('Invalid signature');
  }
  
  const event = JSON.parse(req.body);
  
  switch (event.type) {
    case 'payment_intent.succeeded':
      console.log('Payment succeeded:', event.data.object.id);
      // Fulfill order
      break;
    case 'payment_intent.failed':
      console.log('Payment failed:', event.data.object.id);
      // Notify customer
      break;
  }
  
  res.json({received: true});
});

Webhook Best Practices

Return 200 Quickly
Respond with 200 OK immediately, process events asynchronously
Handle Duplicates
Use event IDs to prevent processing the same event twice
Verify Signatures
Always verify webhook signatures in production
Use Idempotency
Make your webhook handler idempotent to handle retries
Log Everything
Log all webhook events for debugging and auditing
Monitor Failures
Set up alerts for webhook delivery failures

Rate Limiting

100
Requests per second
Standard tier
1000
Requests per second
Enterprise tier
429
HTTP status code
When limit exceeded

Response Headers

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1234567890

Error Handling

card_error402

Card was declined

invalid_request_error400

Invalid parameters

authentication_error401

Authentication failed

rate_limit_error429

Too many requests

SDK Features

🔒

Type Safety

Full TypeScript support with auto-completion

🔄

Automatic Retries

Built-in retry logic for failed requests

Idempotency

Prevent duplicate operations automatically

🔐

Webhook Verification

Secure webhook signature validation

📄

Pagination

Easy iteration through large result sets

⚠️

Error Handling

Detailed error messages and types

Testing

Test Mode

Use test API keys (starting with sk_test_) to test your integration without processing real payments.

Test Card Numbers
4242 4242 4242 4242 - Success
4000 0000 0000 0002 - Declined
4000 0000 0000 9995 - Insufficient funds

Idempotency

Prevent duplicate operations by including an idempotency key in your requests.

const payment = await client.paymentIntents.create({
  amount: 2000,
  currency: 'usd'
}, {
  idempotencyKey: 'unique-key-123'
});

Best Practices

🔔

Use Webhooks

Don't poll for payment status. Use webhooks for real-time notifications.

⚠️

Handle Errors

Implement proper error handling and retry logic for failed requests.

🔐

Secure API Keys

Never expose API keys in client-side code. Use environment variables.

📝

Log Requests

Log all API requests and responses for debugging and auditing.

🏷️

Use Metadata

Store custom data in metadata fields for easier tracking and reporting.

Test Thoroughly

Test all payment flows in test mode before going live.

Performance Optimization

<100ms
Average API response time
99.99%
API uptime SLA
1000/s
Max requests (Enterprise)

Optimization Tips

Use connection pooling for better performance
Cache frequently accessed data
Batch requests when possible
Use expand parameters to reduce API calls

Note: This is a sample API documentation demonstrating our technical writing capabilities. We can create comprehensive, interactive documentation tailored to your API specifications.

Need Similar Content for Your Company?

We create comprehensive API documentation, developer guides, and technical references tailored to your specific needs.