Skip to main content

Custom Platform Integration

Integrate Torque's multi-product checkout with any ecommerce platform using our platform-agnostic approach and comprehensive API documentation.

๐Ÿš€ Quick Startโ€‹

1. Get API Credentialsโ€‹

  1. Create Account: Visit torque.fi/business
  2. Complete Profile: Fill out business information
  3. Generate API Key: Get your Business ID and API Key
  4. Test Integration: Use sandbox environment first

2. Install Torque Packageโ€‹

# JavaScript/Node.js
npm install torque-checkout

# PHP
composer require torque/checkout

# Python
pip install torque-checkout

3. Basic Integrationโ€‹

import { TorqueCheckout } from 'torque-checkout';

const torque = new TorqueCheckout({
businessId: 'your_business_id',
apiKey: 'your_api_key'
});

// Generate checkout link
const { checkoutUrl } = await torque.generateCheckoutLink(cart, customerData);

๐Ÿ”ง Core Integrationโ€‹

Cart Conversionโ€‹

Convert your platform's cart data to Torque format:

function convertCartToTorque(platformCart) {
return {
items: platformCart.items.map(item => ({
productId: item.id.toString(),
quantity: item.quantity,
price: parseFloat(item.price),
variant: item.variant || null,
metadata: {
sku: item.sku,
name: item.name,
category: item.category
}
})),
currency: platformCart.currency || 'USD',
discounts: platformCart.discounts?.map(discount => ({
code: discount.code,
amount: discount.amount,
type: discount.type // 'percentage' or 'fixed'
})) || []
};
}

Customer Dataโ€‹

Extract customer information from your platform:

function getCustomerData(platformCustomer) {
return {
email: platformCustomer.email,
firstName: platformCustomer.firstName,
lastName: platformCustomer.lastName,
phone: platformCustomer.phone || null,
address: platformCustomer.address ? {
street: platformCustomer.address.street,
city: platformCustomer.address.city,
state: platformCustomer.address.state,
postalCode: platformCustomer.address.postalCode,
country: platformCustomer.address.country
} : null
};
}

Checkout Generationโ€‹

Create checkout links for your customers:

async function generateCheckout(platformCart, platformCustomer) {
try {
const cart = convertCartToTorque(platformCart);
const customerData = getCustomerData(platformCustomer);

const { checkoutUrl } = await torque.generateCheckoutLink(cart, customerData, {
expiresIn: 3600, // 1 hour
redirectUrl: 'https://yourdomain.com/thank-you',
webhookUrl: 'https://yourdomain.com/webhooks/torque'
});

return checkoutUrl;
} catch (error) {
console.error('Failed to generate checkout:', error);
throw error;
}
}

๐ŸŽจ Frontend Integrationโ€‹

Add Checkout Buttonโ€‹

HTML Buttonโ€‹

<button id="torque-checkout-btn" class="torque-checkout-button">
Checkout with Torque
</button>

JavaScript Handlerโ€‹

document.getElementById('torque-checkout-btn').addEventListener('click', async function() {
const button = this;
button.disabled = true;
button.textContent = 'Generating Checkout...';

try {
// Get cart and customer data from your platform
const cart = getPlatformCart();
const customer = getPlatformCustomer();

// Generate checkout link
const checkoutUrl = await generateCheckout(cart, customer);

// Redirect to checkout
window.location.href = checkoutUrl;
} catch (error) {
console.error('Checkout failed:', error);
alert('Failed to generate checkout. Please try again.');

// Reset button
button.disabled = false;
button.textContent = 'Checkout with Torque';
}
});

CSS Stylingโ€‹

.torque-checkout-button {
background-color: #3B82F6;
color: white;
padding: 15px 30px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}

.torque-checkout-button:hover {
background-color: #2563EB;
}

.torque-checkout-button:disabled {
background-color: #9CA3AF;
cursor: not-allowed;
}

๐Ÿ”— Webhook Integrationโ€‹

Webhook Endpointโ€‹

Set up an endpoint to receive real-time updates:

// Express.js example
app.post('/webhooks/torque', async (req, res) => {
try {
// Verify webhook signature
const signature = req.headers['x-torque-signature'];
if (!verifyWebhookSignature(req.body, signature, webhookSecret)) {
return res.status(401).json({ error: 'Invalid signature' });
}

// Process webhook
const { event, data } = req.body;

switch (event) {
case 'order.created':
await handleOrderCreated(data);
break;
case 'order.paid':
await handleOrderPaid(data);
break;
case 'order.completed':
await handleOrderCompleted(data);
break;
case 'order.cancelled':
await handleOrderCancelled(data);
break;
}

res.json({ success: true });
} catch (error) {
console.error('Webhook processing failed:', error);
res.status(500).json({ error: 'Processing failed' });
}
});

Signature Verificationโ€‹

Verify webhooks are from Torque:

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');

return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}

Order Handlingโ€‹

Update your platform's order status:

async function handleOrderPaid(data) {
const { orderId } = data;

// Find order in your platform
const order = await findOrderByTorqueId(orderId);
if (order) {
// Update order status
await updateOrderStatus(order.id, 'paid');

// Send confirmation email
await sendOrderConfirmation(order);

// Update inventory
await updateInventory(order);
}
}

๐Ÿ“ฑ Complete Examplesโ€‹

Node.js/Express Integrationโ€‹

const express = require('express');
const { TorqueCheckout } = require('torque-checkout');
const crypto = require('crypto');

const app = express();
app.use(express.json());

const torque = new TorqueCheckout({
businessId: process.env.TORQUE_BUSINESS_ID,
apiKey: process.env.TORQUE_API_KEY
});

const webhookSecret = process.env.TORQUE_WEBHOOK_SECRET;

// Generate checkout endpoint
app.post('/api/torque/checkout', async (req, res) => {
try {
const { cart, customerData } = req.body;

const { checkoutUrl } = await torque.generateCheckoutLink(cart, customerData, {
expiresIn: 3600,
redirectUrl: `${process.env.BASE_URL}/thank-you`,
webhookUrl: `${process.env.BASE_URL}/webhooks/torque`
});

res.json({ checkoutUrl });
} catch (error) {
console.error('Checkout generation failed:', error);
res.status(500).json({ error: 'Failed to generate checkout link' });
}
});

// Webhook endpoint
app.post('/webhooks/torque', async (req, res) => {
try {
const signature = req.headers['x-torque-signature'];
if (!verifyWebhookSignature(req.body, signature, webhookSecret)) {
return res.status(401).json({ error: 'Invalid signature' });
}

const { event, data } = req.body;

switch (event) {
case 'order.paid':
await handleOrderPaid(data);
break;
case 'order.completed':
await handleOrderCompleted(data);
break;
}

res.json({ success: true });
} catch (error) {
console.error('Webhook processing failed:', error);
res.status(500).json({ error: 'Processing failed' });
}
});

function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(JSON.stringify(payload))
.digest('hex');

return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Torque integration running on port ${PORT}`);
});

PHP Integrationโ€‹

<?php
require_once 'vendor/autoload.php';

use Torque\Checkout\TorqueCheckout;

class TorqueIntegration {
private $torque;
private $webhookSecret;

public function __construct($businessId, $apiKey, $webhookSecret) {
$this->torque = new TorqueCheckout([
'businessId' => $businessId,
'apiKey' => $apiKey
]);
$this->webhookSecret = $webhookSecret;
}

public function generateCheckout($cart, $customerData) {
try {
$result = $this->torque->generateCheckoutLink($cart, $customerData, [
'expiresIn' => 3600,
'redirectUrl' => 'https://yourdomain.com/thank-you',
'webhookUrl' => 'https://yourdomain.com/webhooks/torque'
]);

return $result['checkoutUrl'];
} catch (Exception $e) {
error_log('Checkout generation failed: ' . $e->getMessage());
throw $e;
}
}

public function handleWebhook($payload, $signature) {
if (!$this->verifyWebhookSignature($payload, $signature)) {
throw new Exception('Invalid webhook signature');
}

$data = json_decode($payload, true);
$event = $data['event'] ?? '';
$eventData = $data['data'] ?? [];

switch ($event) {
case 'order.paid':
$this->handleOrderPaid($eventData);
break;
case 'order.completed':
$this->handleOrderCompleted($eventData);
break;
}
}

private function verifyWebhookSignature($payload, $signature) {
$expectedSignature = hash_hmac('sha256', $payload, $this->webhookSecret);
return hash_equals($expectedSignature, $signature);
}

private function handleOrderPaid($data) {
// Update order status in your platform
$orderId = $this->getPlatformOrderId($data['orderId']);
if ($orderId) {
$this->updateOrderStatus($orderId, 'paid');
}
}

private function getPlatformOrderId($torqueOrderId) {
// Implement logic to find order in your platform
return null;
}

private function updateOrderStatus($orderId, $status) {
// Implement order status update logic
}
}

// Usage
$integration = new TorqueIntegration(
$_ENV['TORQUE_BUSINESS_ID'],
$_ENV['TORQUE_API_KEY'],
$_ENV['TORQUE_WEBHOOK_SECRET']
);

// Generate checkout
if ($_POST['action'] === 'generate_checkout') {
try {
$cart = $_POST['cart'];
$customerData = $_POST['customerData'];

$checkoutUrl = $integration->generateCheckout($cart, $customerData);
echo json_encode(['success' => true, 'checkoutUrl' => $checkoutUrl]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
}

// Handle webhook
if ($_POST['action'] === 'webhook') {
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_TORQUE_SIGNATURE'] ?? '';

try {
$integration->handleWebhook($payload, $signature);
http_response_code(200);
echo json_encode(['success' => true]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
}
?>

Python Integrationโ€‹

import requests
import hmac
import hashlib
import json
from typing import Dict, Any

class TorqueIntegration:
def __init__(self, business_id: str, api_key: str, webhook_secret: str):
self.business_id = business_id
self.api_key = api_key
self.webhook_secret = webhook_secret


def generate_checkout_link(self, cart: Dict[str, Any], customer_data: Dict[str, Any]) -> str:
"""Generate a checkout link for the given cart and customer data."""
url = f"{self.base_url}/checkout/generate-link"

payload = {
'businessId': self.business_id,
'cart': cart,
'customerData': customer_data,
'options': {
'expiresIn': 3600,
'redirectUrl': 'https://yourdomain.com/thank-you',
'webhookUrl': 'https://yourdomain.com/webhooks/torque'
}
}

headers = {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}

response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()

data = response.json()
return data['checkoutUrl']

def verify_webhook_signature(self, payload: str, signature: str) -> bool:
"""Verify that the webhook signature is valid."""
expected_signature = hmac.new(
self.webhook_secret.encode('utf-8'),
payload.encode('utf-8'),
hashlib.sha256
).hexdigest()

return hmac.compare_digest(expected_signature, signature)

def handle_webhook(self, payload: str, signature: str) -> None:
"""Process a webhook from Torque."""
if not self.verify_webhook_signature(payload, signature):
raise ValueError('Invalid webhook signature')

data = json.loads(payload)
event = data.get('event')
event_data = data.get('data', {})

if event == 'order.paid':
self.handle_order_paid(event_data)
elif event == 'order.completed':
self.handle_order_completed(event_data)

def handle_order_paid(self, data: Dict[str, Any]) -> None:
"""Handle order paid event."""
order_id = data.get('orderId')
if order_id:
# Update order status in your platform
self.update_order_status(order_id, 'paid')

def handle_order_completed(self, data: Dict[str, Any]) -> None:
"""Handle order completed event."""
order_id = data.get('orderId')
if order_id:
# Update order status in your platform
self.update_order_status(order_id, 'completed')

def update_order_status(self, order_id: str, status: str) -> None:
"""Update order status in your platform."""
# Implement order status update logic
pass

# Usage example
if __name__ == '__main__':
integration = TorqueIntegration(
business_id='your_business_id',
api_key='your_api_key',
webhook_secret='your_webhook_secret'
)

# Generate checkout link
cart = {
'items': [
{
'productId': 'prod_1',
'quantity': 2,
'price': 29.99
}
],
'currency': 'USD'
}

customer_data = {
'email': 'customer@example.com',
'firstName': 'John',
'firstName': 'Doe'
}

try:
checkout_url = integration.generate_checkout_link(cart, customer_data)
print(f'Checkout URL: {checkout_url}')
except Exception as e:
print(f'Error generating checkout: {e}')

๐Ÿงช Testingโ€‹

Test Environmentโ€‹

  1. Use Test Credentials: Use sandbox API keys
  2. Test Endpoints: All endpoints work in test mode
  3. No Real Payments: Test without processing real transactions
  4. Reset Data: Test data can be cleared between sessions

Test Scenariosโ€‹

  • Cart Conversion: Verify cart data converts correctly
  • Checkout Flow: Test complete checkout process
  • Webhook Delivery: Test real-time updates
  • Error Handling: Test various error scenarios
  • Data Validation: Verify all required fields

๐Ÿšจ Troubleshootingโ€‹

Common Issuesโ€‹

API Authentication Failsโ€‹

Problem: Getting 401 Unauthorized errors

Solutions:

  • Verify API key is correct
  • Check API key hasn't expired
  • Ensure proper Authorization header format
  • Verify business account is active

Checkout Generation Failsโ€‹

Problem: API returns error when creating checkout

Solutions:

  • Validate cart data format
  • Check required fields are present
  • Verify product IDs are valid
  • Review API error details

Webhooks Not Receivingโ€‹

Problem: No webhook events received

Solutions:

  • Verify webhook URL is accessible
  • Check webhook secret is correct
  • Ensure HTTPS is enabled
  • Test webhook endpoint manually

Debug Toolsโ€‹

Loggingโ€‹

// Enable detailed logging
const torque = new TorqueCheckout({
businessId: process.env.TORQUE_BUSINESS_ID,
apiKey: process.env.TORQUE_API_KEY,
debug: true // Enable debug logging
});

Webhook Testingโ€‹

# Test webhook endpoint
curl -X POST https://yourdomain.com/webhooks/torque \
-H "Content-Type: application/json" \
-d '{
"event": "order.created",
"data": {"orderId": "test_123"}
}'

๐Ÿ”— Next Stepsโ€‹


Need help with custom integration? Contact our support team at hello@torque.fi or check our integration troubleshooting guide.