Checkout API
The Checkout API allows you to create and manage multi-product checkout sessions. Generate checkout links, track order status, and manage customer data seamlessly.
Quick Start
Basic Checkout Link Generation
const response = await fetch('https://api.torque.fi/v1/checkout/generate-link', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
businessId: 'business_123',
cart: {
items: [
{ productId: 'prod_1', quantity: 2, price: 29.99 },
{ productId: 'prod_2', quantity: 1, price: 49.99 }
]
},
customerData: {
email: 'customer@example.com',
firstName: 'John',
lastName: 'Doe'
}
})
});
const { checkoutUrl } = await response.json();
📋 Endpoints
Generate Checkout Link
POST /v1/checkout/generate-link
Create a new checkout session for a shopping cart.
Request Body
{
"businessId": "string",
"cart": {
"items": [
{
"productId": "string",
"quantity": "number",
"price": "number",
"variant": "string",
"metadata": "object"
}
],
"currency": "string",
"discounts": [
{
"code": "string",
"amount": "number",
"type": "percentage|fixed"
}
]
},
"customerData": {
"email": "string",
"firstName": "string",
"lastName": "string",
"phone": "string",
"address": {
"street": "string",
"city": "string",
"state": "string",
"postalCode": "string",
"country": "string"
}
},
"options": {
"expiresIn": "number",
"allowGuest": "boolean",
"requireShipping": "boolean",
"customFields": "object"
}
}
Response
Success (200)
{
"success": true,
"checkoutUrl": "https://checkout.torque.fi/session/abc123",
"sessionId": "session_abc123",
"expiresAt": "2024-01-15T10:30:00Z",
"cartSummary": {
"itemCount": 3,
"productCount": 2,
"subtotal": 109.97,
"total": 109.97,
"currency": "USD"
},
"customerData": {
"email": "customer@example.com",
"firstName": "John",
"lastName": "Doe"
}
}
Error (400)
{
"success": false,
"error": "Invalid cart data",
"code": "CHECKOUT_001",
"details": {
"field": "cart.items",
"message": "At least one item is required"
}
}
Get Order Status
GET /v1/checkout/order-status/{orderId}
Retrieve the current status of an order.
Path Parameters
orderId
(string): The unique identifier of the order
Query Parameters
includeDetails
(boolean): Include full order details (default: false)
Response
Success (200)
{
"success": true,
"order": {
"id": "order_abc123",
"sessionId": "session_abc123",
"status": "completed",
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:05:00Z",
"customerData": {
"email": "customer@example.com",
"firstName": "John",
"lastName": "Doe"
},
"cart": {
"items": [
{
"productId": "prod_1",
"quantity": 2,
"price": 29.99,
"total": 59.98
}
],
"subtotal": 59.98,
"total": 59.98,
"currency": "USD"
},
"payment": {
"method": "crypto",
"transactionId": "tx_123",
"amount": 59.98,
"status": "confirmed"
}
}
}
List Orders
GET /v1/checkout/orders
Retrieve a list of orders for your business.
Query Parameters
limit
(number): Number of orders to return (default: 20, max: 100)offset
(number): Number of orders to skip (default: 0)status
(string): Filter by order statusstartDate
(string): Filter orders created after this date (ISO 8601)endDate
(string): Filter orders created before this date (ISO 8601)customerEmail
(string): Filter by customer email
Response
Success (200)
{
"success": true,
"orders": [
{
"id": "order_abc123",
"status": "completed",
"createdAt": "2024-01-15T10:00:00Z",
"customerData": {
"email": "customer@example.com",
"firstName": "John",
"lastName": "Doe"
},
"cart": {
"itemCount": 2,
"total": 59.98,
"currency": "USD"
}
}
],
"pagination": {
"total": 150,
"limit": 20,
"offset": 0,
"hasMore": true
}
}
Cancel Order
POST /v1/checkout/orders/{orderId}/cancel
Cancel an existing order (only for pending orders).
Path Parameters
orderId
(string): The unique identifier of the order
Request Body
{
"reason": "string",
"refundCustomer": "boolean"
}
Response
Success (200)
{
"success": true,
"message": "Order cancelled successfully",
"order": {
"id": "order_abc123",
"status": "cancelled",
"cancelledAt": "2024-01-15T10:10:00Z",
"cancellationReason": "Customer request"
}
}
🛒 Cart Structure
Cart Items
Each cart item should include:
{
"productId": "string", // Required: Unique product identifier
"quantity": "number", // Required: Quantity of the product
"price": "number", // Required: Unit price in smallest currency unit
"variant": "string", // Optional: Product variant (size, color, etc.)
"metadata": { // Optional: Additional product information
"sku": "string",
"category": "string",
"tags": ["string"]
}
}
Cart Options
{
"currency": "USD", // Default: USD
"discounts": [ // Optional: Applied discounts
{
"code": "SAVE20",
"amount": 20,
"type": "percentage"
}
],
"shipping": { // Optional: Shipping information
"method": "standard",
"cost": 5.99
}
}
👤 Customer Data
Required Fields
email
: Customer's email addressfirstName
: Customer's first namelastName
: Customer's last name
Optional Fields
{
"phone": "+1234567890",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US"
},
"preferences": {
"newsletter": true,
"marketing": false
}
}
⚙️ Checkout Options
Session Configuration
{
"expiresIn": 3600, // Session expiry in seconds (default: 1 hour)
"allowGuest": true, // Allow guest checkout (default: true)
"requireShipping": false, // Require shipping address (default: false)
"customFields": { // Custom form fields
"company": "string",
"notes": "string"
},
"redirectUrl": "string", // URL to redirect after completion
"webhookUrl": "string" // Webhook URL for order updates
}
🔄 Order Statuses
Status Flow
pending → processing → completed
↓
cancelled
↓
refunded
Status Descriptions
pending
: Order created, awaiting paymentprocessing
: Payment received, order being processedcompleted
: Order successfully completedcancelled
: Order cancelled by business or customerrefunded
: Order refunded to customer
📱 Complete Examples
JavaScript/Node.js
class TorqueCheckout {
constructor(apiKey, businessId) {
this.apiKey = apiKey;
this.businessId = businessId;
}
async generateCheckoutLink(cart, customerData, options = {}) {
const response = await fetch(`https://api.torque.fi/v1/checkout/generate-link`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
businessId: this.businessId,
cart,
customerData,
options
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to generate checkout link');
}
return response.json();
}
async getOrderStatus(orderId, includeDetails = false) {
const params = includeDetails ? '?includeDetails=true' : '';
const response = await fetch(`https://api.torque.fi/v1/checkout/order-status/${orderId}${params}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to get order status');
}
return response.json();
}
async listOrders(params = {}) {
const queryString = new URLSearchParams(params).toString();
const response = await fetch(`https://api.torque.fi/v1/checkout/orders?${queryString}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to list orders');
}
return response.json();
}
}
// Usage
const checkout = new TorqueCheckout(apiKey, businessId);
const { checkoutUrl } = await checkout.generateCheckoutLink(
{
items: [
{ productId: 'prod_1', quantity: 2, price: 29.99 }
]
},
{
email: 'customer@example.com',
firstName: 'John',
lastName: 'Doe'
}
);
console.log('Checkout URL:', checkoutUrl);
PHP
<?php
class TorqueCheckout {
private $apiKey;
private $businessId;
public function __construct($apiKey, $businessId) {
$this->apiKey = $apiKey;
$this->businessId = $businessId;
}
public function generateCheckoutLink($cart, $customerData, $options = []) {
$data = [
'businessId' => $this->businessId,
'cart' => $cart,
'customerData' => $customerData,
'options' => $options
];
$response = $this->makeRequest('POST', '/checkout/generate-link', $data);
return $response;
}
public function getOrderStatus($orderId, $includeDetails = false) {
$params = $includeDetails ? '?includeDetails=true' : '';
$response = $this->makeRequest('GET', "/checkout/order-status/{$orderId}{$params}");
return $response;
}
private function makeRequest($method, $endpoint, $data = null) {
$ch = curl_init();
$url = 'https://api.torque.fi/v1' . $endpoint;
$headers = [
'Authorization: Bearer ' . $this->apiKey,
'Content-Type: application/json',
'Accept: application/json'
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if ($data && $method === 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception('API request failed: ' . $response);
}
return json_decode($response, true);
}
}
// Usage
$checkout = new TorqueCheckout($apiKey, $businessId);
$result = $checkout->generateCheckoutLink(
[
'items' => [
['productId' => 'prod_1', 'quantity' => 2, 'price' => 29.99]
]
],
[
'email' => 'customer@example.com',
'firstName' => 'John',
'lastName' => 'Doe'
]
);
echo 'Checkout URL: ' . $result['checkoutUrl'];
?>
Python
import requests
import json
class TorqueCheckout:
def __init__(self, api_key, business_id):
self.api_key = api_key
self.business_id = business_id
self.base_url = 'https://api.torque.fi/v1'
self.headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
def generate_checkout_link(self, cart, customer_data, options=None):
if options is None:
options = {}
data = {
'businessId': self.business_id,
'cart': cart,
'customerData': customer_data,
'options': options
}
response = requests.post(
f'{self.base_url}/checkout/generate-link',
headers=self.headers,
json=data
)
response.raise_for_status()
return response.json()
def get_order_status(self, order_id, include_details=False):
params = {'includeDetails': 'true'} if include_details else {}
response = requests.get(
f'{self.base_url}/checkout/order-status/{order_id}',
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def list_orders(self, **params):
response = requests.get(
f'{self.base_url}/checkout/orders',
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
# Usage
checkout = TorqueCheckout(api_key, business_id)
result = checkout.generate_checkout_link(
cart={
'items': [
{'productId': 'prod_1', 'quantity': 2, 'price': 29.99}
]
},
customer_data={
'email': 'customer@example.com',
'firstName': 'John',
'lastName': 'Doe'
}
)
print(f"Checkout URL: {result['checkoutUrl']}")
Next Steps
- Webhooks: Set up real-time order notifications
- Analytics API: Track business performance
- Error Handling: Handle API errors gracefully
- Data Types: Understand API data structures
Ready to integrate? Check out our platform-specific guides or business onboarding for complete setup instructions.