Session API Reference
Complete reference for creating and managing payment sessions with Altruon.
Overview
Before you can use Altruon JS to render payment components, you must create a payment session from your backend. The session encapsulates all the payment details, billing information, and styling preferences for a checkout flow.
Create Session
Creates a new payment session that can be used with Altruon JS.
Endpoints
- Sandbox:
https://{your-domain}.api.sandbox.altruon.io/api/session/v1/create - Production:
https://{your-domain}.api.altruon.io/api/session/v1/create
Replace {your-domain} with your actual Altruon domain (e.g., mycompany).
Authentication
Requests must be authenticated using your secret API key:
headers: {
'Content-Type': 'application/json',
'x-secret-key': 'sk_sandbox_test_XXXXXX...'
}
Security Note: Never expose your secret key in client-side code. Always call this endpoint from your backend.
Request Body
Complete Example
{
"paymentData": {
"currency": "USD",
"paymentMethod": "card"
},
"redirectUrl": "https://yourdomain.com/success",
"billingData": {
"planId": "price_1SMtJj4hYau76GhIakR22BKu",
"billingPlatformId": "3287b8c7-ce43-41fd-9d58-f510e610b8f3"
},
"styleCustomization": {
"backgroundColor": "#3a3a3a",
"primaryColor": "#4B5563",
"secondaryColor": "#3a3a3a",
"accentColor": "#5B7FFF",
"borderRadius": "5px",
"headerTextColor": "#ffffff",
"fontFamily": "Verdana, cursive",
"textColor": "#ffffff",
"dropShadow": false
}
}
Request Parameters
Important: The fields
currency,planId, andbillingPlatformIdare required and must be set via the backend Create Session API. They cannot be modified from the frontend. OnlybillingAddress.countrycan be set from the frontend using the Altruon JS SDK.
paymentData (required)
Payment-related information for the transaction.
| Field | Type | Required | Description |
|---|---|---|---|
currency | string | Yes | Three-letter ISO currency code (e.g., "USD", "EUR", "BRL"). Must be set via backend Create Session API. |
paymentMethod | string | No | Payment method type: "card", "upi", "pix", etc. |
Note: If no
paymentMethodis provided, the component rendering will be driven by the routing entries defined in your Altruon backoffice (Settings > Payment gateways > Routing Entry):
- Multiple routing entries match the currency: The component will render a drawer UI allowing the customer to select between available payment methods (e.g., Card and UPI for INR currency)
- Single routing entry matches the currency: The component will render only the required payment fields for that specific payment method (e.g., for EUR with only card routing, it will render card number, expiry date, CVV, and optionally cardholder name for some gateways) without the drawer UI
Example:
{
"paymentData": {
"currency": "USD",
"paymentMethod": "card"
}
}
redirectUrl (required)
The URL to redirect users to after successful payment completion.
| Field | Type | Required | Description |
|---|---|---|---|
redirectUrl | string | Yes | Full URL including protocol (e.g., "https://yourdomain.com/success") |
Example:
{
"redirectUrl": "https://yourdomain.com/success"
}
billingData (required)
Billing platform and subscription plan information.
| Field | Type | Required | Description |
|---|---|---|---|
planId | string | Yes | The subscription plan ID from your billing provider (Stripe, Chargebee, etc.). Must be set via backend Create Session API. |
billingPlatformId | string | Yes | Your Altruon billing platform connection ID. Must be set via backend Create Session API. |
frequency | string | No | Billing frequency: "monthly", "yearly", "weekly", etc. |
Example:
{
"billingData": {
"planId": "price_1SMtJj4hYau76GhIakR22BKu",
"billingPlatformId": "3287b8c7-ce43-41fd-9d58-f510e610b8f3",
"frequency": "monthly"
}
}
Note: You can find your
billingPlatformIdin the Altruon Dashboard under Integrations > Billing Providers.
styleCustomization (optional)
Customize the appearance of the payment component to match your brand.
| Field | Type | Default | Description |
|---|---|---|---|
backgroundColor | string | #ffffff | Background color (hex, rgb, or named color) |
primaryColor | string | #4B5563 | Primary color for buttons and interactive elements |
secondaryColor | string | #9CA3AF | Secondary color for supporting elements |
accentColor | string | #3B82F6 | Accent color for highlights and focus states |
borderRadius | string | 8px | Border radius for rounded corners |
headerTextColor | string | #1F2937 | Header text color |
textColor | string | #1F2937 | Body text color |
fontFamily | string | system-ui, sans-serif | Font family for all text |
dropShadow | boolean | true | Whether to show drop shadows on elements |
Example:
{
"styleCustomization": {
"backgroundColor": "#ffffff",
"primaryColor": "#0066FF",
"secondaryColor": "#6B7280",
"accentColor": "#0066FF",
"borderRadius": "12px",
"headerTextColor": "#000000",
"fontFamily": "Inter, system-ui, sans-serif",
"textColor": "#1F2937",
"dropShadow": true
}
}
Response
Success Response (200 OK)
{
"session_id": "sess_1234567890abcdef",
"status": "created",
"expires_at": "2024-11-01T18:30:00Z"
}
| Field | Type | Description |
|---|---|---|
session_id | string | Unique session identifier to pass to Altruon JS |
status | string | Session status: "created", "active", "expired" |
expires_at | string | ISO 8601 timestamp when the session expires |
Error Response (4xx/5xx)
{
"error": {
"code": "invalid_request",
"message": "Missing required field: paymentData.currency",
"details": {}
}
}
Implementation Examples
Node.js / Express
const express = require('express');
const app = express();
app.post('/create-checkout-session', async (req, res) => {
const { planId, billingPlatformId, currency } = req.body;
try {
const response = await fetch(
'https://mycompany.api.sandbox.altruon.io/api/session/v1/create',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-secret-key': process.env.ALTRUON_SECRET_KEY
},
body: JSON.stringify({
paymentData: {
currency: currency || 'USD',
paymentMethod: 'card'
},
redirectUrl: 'https://mycompany.com/success',
billingData: {
planId: planId,
billingPlatformId: billingPlatformId
},
styleCustomization: {
backgroundColor: '#ffffff',
primaryColor: '#0066FF',
accentColor: '#0066FF',
borderRadius: '8px',
fontFamily: 'Inter, sans-serif'
}
})
}
);
const data = await response.json();
if (!response.ok) {
throw new Error(data.error.message);
}
res.json({ sessionId: data.session_id });
} catch (error) {
console.error('Error creating session:', error);
res.status(500).json({ error: error.message });
}
});
Python / Flask
from flask import Flask, request, jsonify
import requests
import os
app = Flask(__name__)
@app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
data = request.get_json()
plan_id = data.get('planId')
billing_platform_id = data.get('billingPlatformId')
currency = data.get('currency', 'USD')
try:
response = requests.post(
'https://mycompany.api.sandbox.altruon.io/api/session/v1/create',
headers={
'Content-Type': 'application/json',
'x-secret-key': os.environ.get('ALTRUON_SECRET_KEY')
},
json={
'paymentData': {
'currency': currency,
'paymentMethod': 'card'
},
'redirectUrl': 'https://mycompany.com/success',
'billingData': {
'planId': plan_id,
'billingPlatformId': billing_platform_id
},
'styleCustomization': {
'backgroundColor': '#ffffff',
'primaryColor': '#0066FF',
'accentColor': '#0066FF',
'borderRadius': '8px',
'fontFamily': 'Inter, sans-serif'
}
}
)
response.raise_for_status()
result = response.json()
return jsonify({'sessionId': result['session_id']})
except requests.exceptions.RequestException as e:
return jsonify({'error': str(e)}), 500
Ruby / Rails
# app/controllers/checkout_controller.rb
class CheckoutController < ApplicationController
def create_session
plan_id = params[:planId]
billing_platform_id = params[:billingPlatformId]
currency = params[:currency] || 'USD'
response = HTTParty.post(
'https://mycompany.api.sandbox.altruon.io/api/session/v1/create',
headers: {
'Content-Type' => 'application/json',
'x-secret-key' => ENV['ALTRUON_SECRET_KEY']
},
body: {
paymentData: {
currency: currency,
paymentMethod: 'card'
},
redirectUrl: 'https://mycompany.com/success',
billingData: {
planId: plan_id,
billingPlatformId: billing_platform_id
},
styleCustomization: {
backgroundColor: '#ffffff',
primaryColor: '#0066FF',
accentColor: '#0066FF',
borderRadius: '8px',
fontFamily: 'Inter, sans-serif'
}
}.to_json
)
if response.success?
render json: { sessionId: response['session_id'] }
else
render json: { error: response['error']['message'] }, status: :internal_server_error
end
end
end
PHP / Laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class CheckoutController extends Controller
{
public function createSession(Request $request)
{
$planId = $request->input('planId');
$billingPlatformId = $request->input('billingPlatformId');
$currency = $request->input('currency', 'USD');
try {
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'x-secret-key' => env('ALTRUON_SECRET_KEY')
])->post(
'https://mycompany.api.sandbox.altruon.io/api/session/v1/create',
[
'paymentData' => [
'currency' => $currency,
'paymentMethod' => 'card'
],
'redirectUrl' => 'https://mycompany.com/success',
'billingData' => [
'planId' => $planId,
'billingPlatformId' => $billingPlatformId
],
'styleCustomization' => [
'backgroundColor' => '#ffffff',
'primaryColor' => '#0066FF',
'accentColor' => '#0066FF',
'borderRadius' => '8px',
'fontFamily' => 'Inter, sans-serif'
]
]
);
if ($response->successful()) {
return response()->json([
'sessionId' => $response->json()['session_id']
]);
} else {
throw new \Exception($response->json()['error']['message']);
}
} catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage()
], 500);
}
}
}
Best Practices
1. Session Expiration
Sessions expire after 24 hours by default. Create a new session if the previous one expires.
2. Security
- Never store or log secret keys
- Always create sessions on your backend
- Validate all input parameters before creating a session
- Use environment variables for API keys
3. Error Handling
Always handle errors gracefully and provide meaningful messages to users:
try {
const response = await createSession(planId);
// Success
} catch (error) {
if (error.code === 'invalid_plan_id') {
// Handle invalid plan
} else if (error.code === 'unauthorized') {
// Handle authentication error
} else {
// Handle generic error
}
}
4. Testing
Use sandbox mode during development and testing:
- Sandbox endpoint:
https://{your-domain}.api.sandbox.altruon.io/api/session/v1/create - Sandbox keys:
sk_sandbox_test_...
Common Error Codes
| Code | Description | Resolution |
|---|---|---|
invalid_request | Missing or invalid request parameters | Check request body structure |
unauthorized | Invalid or missing API key | Verify your secret key |
invalid_plan_id | Plan ID not found or invalid | Check your billing provider |
invalid_billing_platform | Billing platform not configured | Configure billing platform in dashboard |
rate_limit_exceeded | Too many requests | Implement retry logic with backoff |
Transaction Details API
After a successful payment, you'll receive a transactionId in the onSuccess callback. To get complete details about the transaction, subscription, customer, and invoice, call the Transaction Details endpoint from your backend.
Endpoint
Get Transaction Details:
- Sandbox:
GET https://{your-domain}.api.sandbox.altruon.io/api/v1/transaction/{transactionId}/details - Production:
GET https://{your-domain}.api.altruon.io/api/v1/transaction/{transactionId}/details
Authentication:
headers: {
'Content-Type': 'application/json',
'x-secret-key': 'sk_sandbox_test_XXXXXX...'
}
Response:
{
"transaction": {
"id": "66a22937-a351-417e-81c1-9ac5164be9ab",
"idAtGateway": "pay_wthwuqodnobedlulbexcjfylma",
"urlAtGateway": "https://dashboard.sandbox.checkout.com/payments/all-payments/payment/pay_wthwuqodnobedlulbexcjfylma",
"type": "initialPayment",
"amount": "12300",
"currency": "EUR",
"status": "success",
"gateway": "checkoutcom",
"errorMessage": null
},
"customer": {
"idAtBillingPlatform": "cus_TM8zJeFCKE15oB",
"urlAtBilling": "https://dashboard.stripe.com/customers/cus_TM8zJeFCKE15oB",
"billingPlatform": "stripe"
},
"invoice": {
"idAtBillingPlatform": "in_1SPQhq4hYau76GhIbWx8zT8H",
"urlAtBilling": "https://dashboard.stripe.com/invoices/in_1SPQhq4hYau76GhIbWx8zT8H",
"amount": "12300",
"currency": "EUR",
"billingPlatform": "stripe"
},
"subscription": {
"idAtBillingPlatform": "sub_1SPQhq4hYau76GhIFvpT8HSx",
"urlAtBilling": "https://dashboard.stripe.com/subscriptions/sub_1SPQhq4hYau76GhIFvpT8HSx",
"nextBillingDate": "2025-12-03T16:34:10Z",
"billingPlatform": "stripe"
}
}
New Feature: The response now includes direct URLs (
urlAtGatewayandurlAtBilling) that link to the respective entity pages in your payment gateway and billing provider dashboards. These URLs allow your team to quickly access detailed information in Stripe, Checkout.com, or other provider dashboards for support and reconciliation purposes.
For detailed implementation examples and use cases, see the Callbacks documentation.
Next Steps
- Quick Start Guide - Integrate Altruon JS with your session
- Callbacks - Handle payment events and get transaction details
- Configuration - Configure the payment component
- Style Customization - Advanced styling options
- Examples - Real-world implementations