torque-checkout
v1.1.9
Published
Official Torque checkout SDK for eCommerce integrations
Maintainers
Readme
torque-checkout
Official Torque checkout SDK for seamless eCommerce integrations. Generate multi-product checkout links, track orders, and manage customer data with our powerful API.
Quick Start
Prerequisites
Before installing the package, you must create your Torque business profile:
- Go to Torque Business Dashboard: https://torque.fi/business/settings
- Connect your wallet (MetaMask, WalletConnect, etc.)
- Fill out business information (name, email, website, etc.)
- Set your payment wallet address (where you want to receive payments)
- Save your profile (API key will be generated automatically)
- Get your credentials from the bottom of the business settings page
Installation
npm install torque-checkout
# or
yarn add torque-checkoutBasic Usage
import { TorqueCheckout } from 'torque-checkout'
const torque = new TorqueCheckout({
businessId: 'your_business_id',
apiKey: 'your_api_key'
})
// Generate cart checkout link
const checkoutUrl = await torque.generateCartCheckoutUrl({
items: [
{ productId: 'prod_123', quantity: 2, variant: 'large' },
{ productId: 'prod_456', quantity: 1 }
],
customer: {
email: '[email protected]',
firstName: 'John',
lastName: 'Doe'
}
})
// Redirect customer to checkout
window.location.href = checkoutUrl
// The generated URL will look like:
// https://torque.fi/checkout/{businessId}/cart?items={encoded_cart_data}URL Structure
The SDK generates checkout URLs in this format:
- Single Product:
https://torque.fi/checkout/{businessId}/{productId}?quantity=1 - Multi-Product Cart:
https://torque.fi/checkout/{businessId}/cart?items={encoded_cart_data}
The items parameter contains URL-encoded JSON with your cart data.
API Reference
Constructor
new TorqueCheckout(config: TorqueConfig)Config Options:
businessId(required): Your Torque business ID (get from business dashboard)apiKey(required): Your API authentication key (get from business dashboard)timeout(optional): Request timeout in milliseconds (defaults to 30000)
Important: Your businessId and apiKey are generated when you create your business profile in the Torque dashboard. Make sure you've set your payment wallet address in the business settings before using the SDK.
Methods
generateCartCheckoutUrl(cart: CartData): Promise<string>
Generate a checkout URL for a multi-product cart.
const checkoutUrl = await torque.generateCartCheckoutUrl({
items: [
{ productId: 'prod_123', quantity: 2, variant: 'large' },
{ productId: 'prod_456', quantity: 1 }
],
customer: {
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
shippingAddress: {
street: '123 Main St',
city: 'New York',
state: 'NY',
zipCode: '10001',
country: 'US'
}
},
options: {
metadata: {
orderId: 'order_123',
source: 'shopify'
},
expiresIn: 24 * 60 * 60 * 1000 // 24 hours
}
})generateProductCheckoutUrl(productId: string, quantity?: number, customer?: CustomerData, options?: CartOptions): Promise<string>
Generate a checkout URL for a single product.
const checkoutUrl = await torque.generateProductCheckoutUrl(
'prod_123',
2,
{ email: '[email protected]' }
)validateCart(cart: CartData): Promise<CartValidation>
Validate cart data before generating checkout links.
const validation = await torque.validateCart({
items: [
{ productId: 'prod_123', quantity: 2 },
{ productId: 'prod_456', quantity: 1 }
]
})
if (validation.valid) {
console.log('Cart is valid, estimated total:', validation.estimatedTotal)
} else {
console.log('Cart validation errors:', validation.errors)
}getOrderStatus(orderId: string): Promise<OrderStatus>
Get the current status of an order.
const orderStatus = await torque.getOrderStatus('order_123')
console.log('Order status:', orderStatus.status)
console.log('Total amount:', orderStatus.totals.total)sendWebhookEvent(orderId: string, status: string, customerData?: any, metadata?: Record<string, any>): Promise<void>
Send webhook events to update order status.
await torque.sendWebhookEvent('order_123', 'shipped', {
trackingNumber: '1Z999AA1234567890',
carrier: 'UPS'
})trackCartView(cartId: string, cartData: CartData): Promise<void>
Track cart views for analytics.
await torque.trackCartView('cart_123', {
items: [{ productId: 'prod_123', quantity: 2 }]
})trackCheckoutComplete(orderId: string, checkoutData: any): Promise<void>
Track successful checkout completions.
await torque.trackCheckoutComplete('order_123', {
paymentMethod: 'card',
total: 99.99
})generateCartHash(cart: CartData): string
Generate a unique hash for cart identification and caching.
const cartHash = torque.generateCartHash({
items: [{ productId: 'prod_123', quantity: 2 }]
})Data Types
CartItem
interface CartItem {
productId: string // Required: Torque product ID
quantity: number // Required: Quantity to purchase
variant?: string // Optional: Product variant (size, color, etc.)
price?: number // Optional: Override product price
metadata?: Record<string, any> // Optional: Custom data
}CustomerData
interface CustomerData {
email: string // Required: Customer email
firstName?: string // Optional: First name
lastName?: string // Optional: Last name
phone?: string // Optional: Phone number
shippingAddress?: { // Optional: Pre-fill shipping address
street: string
city: string
state: string
zipCode: string
country: string
}
billingAddress?: { // Optional: Pre-fill billing address
// Same structure as shippingAddress
}
}CartOptions
interface CartOptions {
domain?: string // Optional: Custom domain for checkout
expiresIn?: number // Optional: Link expiration time (ms)
metadata?: Record<string, any> // Optional: Custom metadata
redirectUrl?: string // Optional: Post-checkout redirect URL
}Platform Integrations
Shopify
// Shopify app integration
app.post('/checkout', async (req, res) => {
const { cart, customer } = req.body
try {
const checkoutUrl = await torque.generateCartCheckoutUrl({
items: cart.items.map(item => ({
productId: item.product_id,
quantity: item.quantity,
variant: item.variant_title,
price: item.price
})),
customer: {
email: customer.email,
firstName: customer.first_name,
lastName: customer.last_name,
shippingAddress: customer.shipping_address
},
options: {
metadata: {
orderId: cart.order_id,
source: 'shopify'
}
}
})
res.json({ checkoutUrl })
} catch (error) {
res.status(500).json({ error: error.message })
}
})WooCommerce
// WooCommerce hook integration
add_action('woocommerce_checkout_order_processed', 'redirect_to_torque_checkout', 10, 3);
function redirect_to_torque_checkout($order_id, $posted_data, $order) {
$cart_items = [];
foreach ($order->get_items() as $item) {
$cart_items[] = [
'productId' => $item->get_product_id(),
'quantity' => $item->get_quantity(),
'variant' => $item->get_variation_id() ? $item->get_name() : null,
'price' => $item->get_total() / $item->get_quantity()
];
}
$checkout_data = [
'businessId' => get_option('torque_business_id'),
'cart' => ['items' => $cart_items],
'customerData' => [
'email' => $order->get_billing_email(),
'firstName' => $order->get_billing_first_name(),
'lastName' => $order->get_billing_last_name()
]
];
// Use JavaScript SDK or direct API call
$response = wp_remote_post('https://dashboard.torque.fi/api/checkout/generate-link', [
'body' => json_encode($checkout_data),
'headers' => ['Content-Type' => 'application/json'],
'timeout' => 30
]);
if (!is_wp_error($response)) {
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($body['checkoutUrl']) {
wp_redirect($body['checkoutUrl']);
exit;
}
}
}Testing
Test Environment
Use our sandbox environment for testing:
const torque = new TorqueCheckout({
businessId: 'test_business_123',
apiKey: 'test_api_key'
})Test Data
const testCart = {
items: [
{ productId: 'test_prod_1', quantity: 1, price: 10.00 }
],
customer: {
email: '[email protected]'
}
}
const checkoutUrl = await torque.generateCartCheckoutUrl(testCart)Error Handling
The SDK throws descriptive errors for various failure scenarios:
try {
const checkoutUrl = await torque.generateCartCheckoutUrl(cart)
} catch (error) {
if (error.message.includes('BUSINESS_NOT_FOUND')) {
console.error('Invalid business ID')
} else if (error.message.includes('PRODUCTS_NOT_FOUND')) {
console.error('Some products not found')
} else if (error.message.includes('Request timeout')) {
console.error('API request timed out')
} else {
console.error('Unexpected error:', error.message)
}
}Analytics & Tracking
Track customer behavior and optimize conversions:
// Track cart abandonment
await torque.trackCartView('cart_123', cartData)
// Track successful checkouts
await torque.trackCheckoutComplete('order_123', {
paymentMethod: 'card',
total: 99.99,
items: 3
})Payment Destination
Payments are transferred to the wallet address set in business profile.
- Set once: Configure your payment wallet in business settings
- Automatic transfers: All successful checkouts send funds to your wallet
- Secure: No need to handle payment addresses in your code
- Update anytime: Change your payment wallet in business settings
Performance
- Built-in request caching with cart hashing
- Configurable timeouts
- Efficient error handling
- Minimal bundle size
Support
- Documentation: https://docs.torque.fi
- API Reference: https://docs.torque.fi/api
- Integration Guide: https://docs.torque.fi/integrations
- NPM Package: https://www.npmjs.com/package/torque-checkout
- Support: [email protected]
