Skip to main content

Data Types

This guide covers all data types, schemas, and field definitions used throughout the Torque API. Understanding these structures is essential for building robust integrations.

🚀 Quick Start

Basic Data Structure

// Example checkout request with all data types
const checkoutRequest = {
businessId: "business_123", // string
cart: { // Cart object
items: [ // CartItem array
{
productId: "prod_1", // string
quantity: 2, // number
price: 29.99, // number
variant: "large", // string (optional)
metadata: { // object (optional)
color: "blue",
size: "L"
}
}
],
currency: "USD", // string
discounts: [ // Discount array (optional)
{
code: "SAVE20", // string
amount: 20, // number
type: "percentage" // string enum
}
]
},
customerData: { // CustomerData object
email: "customer@example.com", // string
firstName: "John", // string
lastName: "Doe", // string
phone: "+1234567890", // string (optional)
address: { // Address object (optional)
street: "123 Main St", // string
city: "New York", // string
state: "NY", // string
postalCode: "10001", // string
country: "US" // string
}
},
options: { // CheckoutOptions object (optional)
expiresIn: 3600, // number (seconds)
allowGuest: true, // boolean
requireShipping: false, // boolean
customFields: { // object (optional)
company: "Acme Corp",
notes: "Special instructions"
}
}
};

Core Data Types

String Types

BusinessId

Unique identifier for a business account.

Format: business_ followed by alphanumeric characters Example: business_123abc Validation: Must start with business_, 8-32 characters

// Valid business IDs
const validIds = [
"business_123",
"business_abc123",
"business_mybusiness_2024"
];

// Invalid business IDs
const invalidIds = [
"123", // Missing prefix
"business", // Missing suffix
"business_", // Empty suffix
"business_very_long_id_that_exceeds_maximum_length"
];

ProductId

Unique identifier for a product.

Format: prod_ followed by alphanumeric characters Example: prod_456def Validation: Must start with prod_, 6-24 characters

// Valid product IDs
const validIds = [
"prod_1",
"prod_abc123",
"prod_product_name"
];

// Invalid product IDs
const invalidIds = [
"1", // Missing prefix
"product", // Missing prefix
"prod_", // Empty suffix
"prod_very_long_product_id_exceeding_limit"
];

OrderId

Unique identifier for an order.

Format: order_ followed by alphanumeric characters Example: order_789ghi Validation: Must start with order_, 8-32 characters

// Valid order IDs
const validIds = [
"order_123",
"order_abc123",
"order_2024_001"
];

// Invalid order IDs
const invalidIds = [
"123", // Missing prefix
"order", // Missing suffix
"order_", // Empty suffix
"order_very_long_order_id_exceeding_maximum_length"
];

SessionId

Unique identifier for a checkout session.

Format: session_ followed by alphanumeric characters Example: session_jkl012 Validation: Must start with session_, 10-36 characters

// Valid session IDs
const validIds = [
"session_123",
"session_abc123",
"session_checkout_2024_001"
];

// Invalid session IDs
const invalidIds = [
"123", // Missing prefix
"session", // Missing suffix
"session_", // Empty suffix
"session_very_long_session_id_exceeding_maximum_length"
];

Numeric Types

Price

Monetary amount in smallest currency unit.

Type: number Precision: Up to 2 decimal places Range: 0.01 to 999,999.99 Example: 29.99 (represents $29.99)

// Valid prices
const validPrices = [
0.01, // Minimum price
29.99, // Standard price
999999.99, // Maximum price
100 // Whole number
];

// Invalid prices
const invalidPrices = [
0, // Zero not allowed
-10, // Negative not allowed
1000000, // Exceeds maximum
29.999 // Too many decimal places
];

Quantity

Number of items in an order.

Type: number Range: 1 to 999,999 Example: 2

// Valid quantities
const validQuantities = [
1, // Minimum quantity
10, // Standard quantity
999999 // Maximum quantity
];

// Invalid quantities
const invalidQuantities = [
0, // Zero not allowed
-1, // Negative not allowed
1000000, // Exceeds maximum
1.5 // Decimal not allowed
];

Percentage

Percentage value for discounts and rates.

Type: number Range: 0 to 100 Precision: Up to 2 decimal places Example: 20.5 (represents 20.5%)

// Valid percentages
const validPercentages = [
0, // 0%
20.5, // 20.5%
100 // 100%
];

// Invalid percentages
const invalidPercentages = [
-5, // Negative not allowed
150, // Exceeds 100%
20.555 // Too many decimal places
];

Boolean Types

Active

Boolean flag for active/inactive status.

Type: boolean Values: true or false Example: true

// Valid boolean values
const validBooleans = [
true,
false
];

// Invalid boolean values
const invalidBooleans = [
"true", // String
1, // Number
"yes", // String
null // Null
];

🛒 Cart Data Types

Cart

Complete shopping cart information.

interface Cart {
items: CartItem[]; // Required: Array of cart items
currency?: string; // Optional: Currency code (default: USD)
discounts?: Discount[]; // Optional: Applied discounts
shipping?: ShippingInfo; // Optional: Shipping information
metadata?: object; // Optional: Additional cart data
}

Example:

{
"items": [
{
"productId": "prod_1",
"quantity": 2,
"price": 29.99,
"variant": "large",
"metadata": {
"color": "blue",
"size": "L"
}
}
],
"currency": "USD",
"discounts": [
{
"code": "SAVE20",
"amount": 20,
"type": "percentage"
}
],
"shipping": {
"method": "standard",
"cost": 5.99
}
}

CartItem

Individual item in the shopping cart.

interface CartItem {
productId: string; // Required: Unique product identifier
quantity: number; // Required: Item quantity
price: number; // Required: Unit price
variant?: string; // Optional: Product variant
metadata?: object; // Optional: Additional item data
}

Validation Rules:

  • productId must be valid ProductId format
  • quantity must be positive integer
  • price must be valid Price format
  • variant must be string if provided
  • metadata must be object if provided

Example:

{
"productId": "prod_1",
"quantity": 2,
"price": 29.99,
"variant": "large",
"metadata": {
"color": "blue",
"size": "L",
"sku": "BLUE-L-001"
}
}

Discount

Discount applied to the cart.

interface Discount {
code: string; // Required: Discount code
amount: number; // Required: Discount amount
type: "percentage" | "fixed"; // Required: Discount type
description?: string; // Optional: Discount description
}

Validation Rules:

  • code must be non-empty string
  • amount must be positive number
  • type must be either "percentage" or "fixed"
  • amount must not exceed 100 if type is "percentage"

Example:

{
"code": "SAVE20",
"amount": 20,
"type": "percentage",
"description": "20% off your order"
}

ShippingInfo

Shipping method and cost information.

interface ShippingInfo {
method: string; // Required: Shipping method name
cost: number; // Required: Shipping cost
estimatedDays?: number; // Optional: Estimated delivery days
description?: string; // Optional: Shipping description
}

Example:

{
"method": "standard",
"cost": 5.99,
"estimatedDays": 3,
"description": "Standard shipping (3-5 business days)"
}

👤 Customer Data Types

CustomerData

Complete customer information.

interface CustomerData {
email: string; // Required: Customer email
firstName: string; // Required: First name
lastName: string; // Required: Last name
phone?: string; // Optional: Phone number
address?: Address; // Optional: Shipping address
preferences?: CustomerPreferences; // Optional: Customer preferences
}

Validation Rules:

  • email must be valid email format
  • firstName and lastName must be non-empty strings
  • phone must be valid phone format if provided
  • address must be valid Address object if provided

Example:

{
"email": "customer@example.com",
"firstName": "John",
"lastName": "Doe",
"phone": "+1234567890",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US"
},
"preferences": {
"newsletter": true,
"marketing": false,
"language": "en"
}
}

Address

Customer shipping address.

interface Address {
street: string; // Required: Street address
city: string; // Required: City
state: string; // Required: State/province
postalCode: string; // Required: Postal/ZIP code
country: string; // Required: Country code
apartment?: string; // Optional: Apartment/suite number
}

Validation Rules:

  • All required fields must be non-empty strings
  • country must be valid ISO 3166-1 alpha-2 country code
  • postalCode format varies by country

Example:

{
"street": "123 Main St",
"city": "New York",
"state": "NY",
"postalCode": "10001",
"country": "US",
"apartment": "Apt 4B"
}

CustomerPreferences

Customer preferences and settings.

interface CustomerPreferences {
newsletter?: boolean; // Optional: Newsletter subscription
marketing?: boolean; // Optional: Marketing communications
language?: string; // Optional: Preferred language
currency?: string; // Optional: Preferred currency
timezone?: string; // Optional: Timezone
}

Example:

{
"newsletter": true,
"marketing": false,
"language": "en",
"currency": "USD",
"timezone": "America/New_York"
}

⚙️ Checkout Options Types

CheckoutOptions

Configuration options for checkout sessions.

interface CheckoutOptions {
expiresIn?: number; // Optional: Session expiry in seconds
allowGuest?: boolean; // Optional: Allow guest checkout
requireShipping?: boolean; // Optional: Require shipping address
customFields?: object; // Optional: Custom form fields
redirectUrl?: string; // Optional: Post-completion redirect
webhookUrl?: string; // Optional: Webhook endpoint
theme?: CheckoutTheme; // Optional: UI theme customization
}

Validation Rules:

  • expiresIn must be positive number (default: 3600 seconds)
  • allowGuest must be boolean (default: true)
  • requireShipping must be boolean (default: false)
  • redirectUrl must be valid URL if provided
  • webhookUrl must be valid URL if provided

Example:

{
"expiresIn": 7200,
"allowGuest": true,
"requireShipping": false,
"customFields": {
"company": "string",
"notes": "string",
"referral": "string"
},
"redirectUrl": "https://example.com/thank-you",
"webhookUrl": "https://example.com/webhooks/torque",
"theme": {
"primaryColor": "#3B82F6",
"secondaryColor": "#1F2937"
}
}

CheckoutTheme

UI theme customization options.

interface CheckoutTheme {
primaryColor?: string; // Optional: Primary brand color
secondaryColor?: string; // Optional: Secondary brand color
logo?: string; // Optional: Custom logo URL
customCSS?: string; // Optional: Custom CSS rules
}

Validation Rules:

  • Colors must be valid hex color codes
  • Logo must be valid URL if provided
  • Custom CSS must be valid CSS if provided

📊 Order Data Types

Order

Complete order information.

interface Order {
id: string; // Required: Unique order identifier
sessionId: string; // Required: Associated session ID
businessId: string; // Required: Business identifier
status: OrderStatus; // Required: Current order status
customerData: CustomerData; // Required: Customer information
cart: Cart; // Required: Order cart data
payment: PaymentInfo; // Required: Payment information
createdAt: string; // Required: Order creation timestamp
updatedAt: string; // Required: Last update timestamp
completedAt?: string; // Optional: Completion timestamp
cancelledAt?: string; // Optional: Cancellation timestamp
metadata?: object; // Optional: Additional order data
}

Example:

{
"id": "order_abc123",
"sessionId": "session_abc123",
"businessId": "business_123",
"status": "completed",
"customerData": {
"email": "customer@example.com",
"firstName": "John",
"lastName": "Doe"
},
"cart": {
"items": [
{
"productId": "prod_1",
"quantity": 2,
"price": 29.99
}
],
"total": 59.98,
"currency": "USD"
},
"payment": {
"method": "crypto",
"transactionId": "tx_123",
"amount": 59.98,
"status": "confirmed"
},
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:05:00Z",
"completedAt": "2024-01-15T10:05:00Z"
}

OrderStatus

Order status enumeration.

type OrderStatus = 
| "pending" // Order created, awaiting payment
| "processing" // Payment received, processing
| "completed" // Order successfully completed
| "cancelled" // Order cancelled
| "refunded"; // Order refunded

Status Flow:

pending → processing → completed

cancelled

refunded

PaymentInfo

Payment method and status information.

interface PaymentInfo {
method: string; // Required: Payment method
transactionId: string; // Required: Transaction identifier
amount: number; // Required: Payment amount
status: PaymentStatus; // Required: Payment status
currency: string; // Required: Payment currency
processedAt?: string; // Optional: Processing timestamp
failureReason?: string; // Optional: Failure reason
}

Example:

{
"method": "crypto",
"transactionId": "tx_123",
"amount": 59.98,
"status": "confirmed",
"currency": "USD",
"processedAt": "2024-01-15T10:05:00Z"
}

PaymentStatus

Payment status enumeration.

type PaymentStatus = 
| "pending" // Payment initiated
| "processing" // Payment being processed
| "confirmed" // Payment confirmed
| "failed" // Payment failed
| "refunded"; // Payment refunded

Webhook Data Types

WebhookEvent

Webhook event structure.

interface WebhookEvent {
event: string; // Required: Event type
timestamp: string; // Required: Event timestamp
data: object; // Required: Event data
deliveryId: string; // Required: Delivery identifier
}

Example:

{
"event": "order.created",
"timestamp": "2024-01-15T10:00:00Z",
"data": {
"orderId": "order_abc123",
"status": "pending"
},
"deliveryId": "delivery_abc123"
}

WebhookDelivery

Webhook delivery information.

interface WebhookDelivery {
id: string; // Required: Delivery identifier
webhookId: string; // Required: Webhook identifier
event: string; // Required: Event type
status: "pending" | "delivered" | "failed"; // Required: Delivery status
attempts: number; // Required: Delivery attempts
lastAttempt?: string; // Optional: Last attempt timestamp
nextRetry?: string; // Optional: Next retry timestamp
responseCode?: number; // Optional: HTTP response code
responseBody?: string; // Optional: Response body
}

📈 Analytics Data Types

AnalyticsPeriod

Time period for analytics queries.

interface AnalyticsPeriod {
start: string; // Required: Start date (ISO 8601)
end: string; // Required: End date (ISO 8601)
type?: "day" | "week" | "month" | "quarter" | "year"; // Optional: Period type
}

Example:

{
"start": "2024-01-01T00:00:00Z",
"end": "2024-01-31T23:59:59Z",
"type": "month"
}

AnalyticsFilter

Filter options for analytics queries.

interface AnalyticsFilter {
status?: string[]; // Optional: Filter by status
minAmount?: number; // Optional: Minimum amount
maxAmount?: number; // Optional: Maximum amount
countries?: string[]; // Optional: Filter by countries
devices?: string[]; // Optional: Filter by devices
dateRange?: AnalyticsPeriod; // Optional: Date range filter
}

Example:

{
"status": ["completed", "processing"],
"minAmount": 25.00,
"maxAmount": 100.00,
"countries": ["US", "CA"],
"devices": ["desktop", "mobile"]
}

Validation Functions

JavaScript Validation

class TorqueDataValidator {
static validateBusinessId(id) {
const pattern = /^business_[a-zA-Z0-9]{3,24}$/;
return pattern.test(id);
}

static validateProductId(id) {
const pattern = /^prod_[a-zA-Z0-9]{2,18}$/;
return pattern.test(id);
}

static validateEmail(email) {
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}

static validatePrice(price) {
return typeof price === 'number' &&
price >= 0.01 &&
price <= 999999.99 &&
Number.isFinite(price);
}

static validateQuantity(quantity) {
return Number.isInteger(quantity) &&
quantity >= 1 &&
quantity <= 999999;
}

static validateCart(cart) {
if (!cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {
return { valid: false, error: 'Cart must contain at least one item' };
}

for (const item of cart.items) {
if (!this.validateProductId(item.productId)) {
return { valid: false, error: `Invalid product ID: ${item.productId}` };
}
if (!this.validateQuantity(item.quantity)) {
return { valid: false, error: `Invalid quantity: ${item.quantity}` };
}
if (!this.validatePrice(item.price)) {
return { valid: false, error: `Invalid price: ${item.price}` };
}
}

return { valid: true };
}

static validateCustomerData(customerData) {
if (!this.validateEmail(customerData.email)) {
return { valid: false, error: 'Invalid email address' };
}
if (!customerData.firstName || !customerData.lastName) {
return { valid: false, error: 'First and last name are required' };
}
return { valid: true };
}
}

// Usage
const cart = {
items: [
{ productId: 'prod_1', quantity: 2, price: 29.99 }
]
};

const cartValidation = TorqueDataValidator.validateCart(cart);
if (!cartValidation.valid) {
console.error('Cart validation failed:', cartValidation.error);
}

TypeScript Types

// Type definitions for validation
interface ValidationResult {
valid: boolean;
error?: string;
details?: object;
}

interface CartValidationResult extends ValidationResult {
details?: {
itemIndex?: number;
field?: string;
value?: any;
};
}

// Generic validation function
function validateRequired<T>(value: T, fieldName: string): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
valid: false,
error: `${fieldName} is required`
};
}
return { valid: true };
}

// Specific validation functions
function validateEmail(email: string): ValidationResult {
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!pattern.test(email)) {
return {
valid: false,
error: 'Invalid email format'
};
}
return { valid: true };
}

function validatePrice(price: number): ValidationResult {
if (!Number.isFinite(price) || price < 0.01 || price > 999999.99) {
return {
valid: false,
error: 'Price must be between 0.01 and 999,999.99'
};
}
return { valid: true };
}

Next Steps


Need help with data validation? Check our validation examples or contact our developer support team.