Skip to main content

JavaScript SDK

The Torque JavaScript SDK provides a simple way to integrate Torque's multi-product checkout into your Node.js applications and frontend projects.

Installationโ€‹

npm install torque-checkout

๐Ÿ“ฆ Official Package: torque-checkout on npmjs.com

import { TorqueCheckout } from 'torque-checkout';

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

๐Ÿ“š API Methodsโ€‹

Checkout Managementโ€‹

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

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

Retrieve Orderโ€‹

// Get order by ID
const order = await torque.getOrder('order_123');

// Get order with specific fields
const order = await torque.getOrder('order_123', {
fields: ['id', 'status', 'amount', 'customer']
});

List Ordersโ€‹

// Get all orders
const orders = await torque.listOrders();

// Get orders with filters
const orders = await torque.listOrders({
status: 'paid',
startDate: '2024-01-01',
endDate: '2024-12-31',
limit: 50,
offset: 0
});

Cancel Orderโ€‹

// Cancel an order
const result = await torque.cancelOrder('order_123', {
reason: 'Customer requested cancellation'
});

Webhook Managementโ€‹

Create Webhookโ€‹

// Create a new webhook
const webhook = await torque.createWebhook({
url: 'https://yourdomain.com/webhooks/torque',
events: ['order.created', 'order.paid', 'order.completed'],
secret: 'your_webhook_secret'
});

List Webhooksโ€‹

// Get all webhooks
const webhooks = await torque.listWebhooks();

// Get webhooks by event type
const webhooks = await torque.listWebhooks({
event: 'order.paid'
});

Update Webhookโ€‹

// Update webhook configuration
const webhook = await torque.updateWebhook('webhook_123', {
url: 'https://newdomain.com/webhooks/torque',
events: ['order.created', 'order.paid', 'order.completed', 'order.cancelled']
});

Delete Webhookโ€‹

// Delete a webhook
await torque.deleteWebhook('webhook_123');

Analyticsโ€‹

Business Overviewโ€‹

// Get business overview
const overview = await torque.getBusinessOverview({
period: 'month', // 'day', 'week', 'month', 'year'
startDate: '2024-01-01',
endDate: '2024-12-31'
});

Revenue Analyticsโ€‹

// Get revenue analytics
const revenue = await torque.getRevenueAnalytics({
period: 'month',
startDate: '2024-01-01',
endDate: '2024-12-31',
groupBy: 'day' // 'day', 'week', 'month'
});

Order Analyticsโ€‹

// Get order analytics
const orders = await torque.getOrderAnalytics({
period: 'month',
startDate: '2024-01-01',
endDate: '2024-12-31',
metrics: ['count', 'value', 'conversion_rate']
});

๐ŸŽจ Frontend Integrationโ€‹

React Componentโ€‹

import React, { useState } from 'react';
import { TorqueCheckout } from 'torque-checkout';

export function TorqueCheckoutButton({ cart, customerData }) {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

const handleCheckout = async () => {
setIsLoading(true);
setError(null);

try {
const torque = new TorqueCheckout({
businessId: process.env.REACT_APP_TORQUE_BUSINESS_ID,
apiKey: process.env.REACT_APP_TORQUE_API_KEY
});

const { checkoutUrl } = await torque.generateCheckoutLink(cart, customerData);
window.location.href = checkoutUrl;
} catch (err) {
setError(err.message);
} finally {
setIsLoading(false);
}
};

return (
<div>
<button
onClick={handleCheckout}
disabled={isLoading}
className="torque-checkout-btn"
>
{isLoading ? 'Generating Checkout...' : 'Checkout with Torque'}
</button>
{error && <div className="error">{error}</div>}
</div>
);
}

Vue.js Componentโ€‹

<template>
<div>
<button
@click="handleCheckout"
:disabled="isLoading"
class="torque-checkout-btn"
>
{{ isLoading ? 'Generating Checkout...' : 'Checkout with Torque' }}
</button>
<div v-if="error" class="error">{{ error }}</div>
</div>
</template>

<script>
import { TorqueCheckout } from 'torque-checkout';

export default {
name: 'TorqueCheckoutButton',
props: {
cart: {
type: Object,
required: true
},
customerData: {
type: Object,
required: true
}
},
data() {
return {
isLoading: false,
error: null
};
},
methods: {
async handleCheckout() {
this.isLoading = true;
this.error = null;

try {
const torque = new TorqueCheckout({
businessId: process.env.VUE_APP_TORQUE_BUSINESS_ID,
apiKey: process.env.VUE_APP_TORQUE_API_KEY
});

const { checkoutUrl } = await torque.generateCheckoutLink(this.cart, this.customerData);
window.location.href = checkoutUrl;
} catch (err) {
this.error = err.message;
} finally {
this.isLoading = false;
}
}
}
};
</script>

๐Ÿ”— Webhook Handlingโ€‹

Express.js Webhook Handlerโ€‹

import express from 'express';
import { TorqueCheckout } from 'torque-checkout';

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

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

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

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 error:', error);
res.status(500).json({ error: 'Processing failed' });
}
});

async function handleOrderPaid(data) {
const { orderId } = data;
console.log(`Order ${orderId} has been paid`);

// Update your system with the order status
// Send confirmation emails, update inventory, etc.
}

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

Next.js API Routeโ€‹

// pages/api/webhooks/torque.js
import { TorqueCheckout } from 'torque-checkout';

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

export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}

try {
// Verify webhook signature
const signature = req.headers['x-torque-signature'];
if (!torque.verifyWebhookSignature(req.body, signature)) {
return res.status(401).json({ error: 'Invalid signature' });
}

const { event, data } = req.body;

// Process webhook event
await processWebhookEvent(event, data);

res.json({ success: true });
} catch (error) {
console.error('Webhook error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}

async function processWebhookEvent(event, data) {
switch (event) {
case 'order.paid':
await handleOrderPaid(data);
break;
case 'order.completed':
await handleOrderCompleted(data);
break;
// Handle other events...
}
}

๐Ÿงช Testingโ€‹

Test Environmentโ€‹

// Use sandbox environment for testing
const torque = new TorqueCheckout({
businessId: 'test_business_123',
apiKey: 'test_api_key_456',
environment: 'sandbox'
});

// Test checkout generation
const { checkoutUrl } = await torque.generateCheckoutLink({
items: [
{
productId: 'test_prod_1',
quantity: 1,
price: 9.99
}
]
}, {
email: 'test@example.com',
firstName: 'Test',
lastName: 'User'
});

Mock Dataโ€‹

// Sample cart data for testing
const testCart = {
items: [
{
productId: 'prod_1',
quantity: 2,
price: 29.99,
variant: 'Blue - Large',
metadata: {
sku: 'BLUE-L-001',
name: 'Premium T-Shirt'
}
},
{
productId: 'prod_2',
quantity: 1,
price: 19.99,
variant: 'Red - Medium',
metadata: {
sku: 'RED-M-002',
name: 'Casual Shirt'
}
}
],
currency: 'USD',
discounts: [
{
code: 'SAVE10',
amount: 5.00,
type: 'fixed'
}
]
};

// Sample customer data
const testCustomer = {
email: 'customer@example.com',
firstName: 'John',
lastName: 'Doe',
phone: '+1234567890',
address: {
street: '123 Main St',
city: 'New York',
state: 'NY',
postalCode: '10001',
country: 'US'
}
};

๐Ÿšจ Error Handlingโ€‹

Try-Catch with Retry Logicโ€‹

async function generateCheckoutWithRetry(cart, customerData, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const { checkoutUrl } = await torque.generateCheckoutLink(cart, customerData);
return { checkoutUrl };
} catch (error) {
if (attempt === maxRetries) {
throw error;
}

// Wait before retrying (exponential backoff)
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));

console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
}
}
}

Error Typesโ€‹

import { TorqueError } from 'torque-checkout';

try {
const result = await torque.generateCheckoutLink(cart, customerData);
} catch (error) {
if (error instanceof TorqueError) {
switch (error.code) {
case 'INVALID_CART':
console.error('Cart data is invalid:', error.details);
break;
case 'INSUFFICIENT_FUNDS':
console.error('Insufficient funds for transaction');
break;
case 'RATE_LIMIT_EXCEEDED':
console.error('Rate limit exceeded, please wait');
break;
default:
console.error('Torque error:', error.message);
}
} else {
console.error('Unexpected error:', error);
}
}

๐Ÿ”— Next Stepsโ€‹


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