Skip to main content

PHP SDK

The Torque PHP SDK provides a simple and powerful way to integrate Torque's multi-product checkout into your PHP applications. Built with modern PHP practices, our SDK handles API interactions, webhook management, and data validation.

Installation

Composer Package

composer require torque/checkout

Manual Installation

Download the SDK files and include the autoloader:

require_once 'path/to/torque-checkout/autoload.php';

Configuration

Initialize SDK

<?php
use Torque\Checkout\TorqueCheckout;

$torque = new TorqueCheckout([
'businessId' => 'your_business_id',
'apiKey' => 'your_api_key'
]);

Environment Variables

# .env file
TORQUE_BUSINESS_ID=your_business_id
TORQUE_API_KEY=your_api_key
<?php
use Torque\Checkout\TorqueCheckout;

$torque = new TorqueCheckout([
'businessId' => $_ENV['TORQUE_BUSINESS_ID'],
'apiKey' => $_ENV['TORQUE_API_KEY']
]);

API Methods

Checkout Management

<?php
// Basic checkout link generation
$result = $torque->generateCheckoutLink($cart, $customerData);
$checkoutUrl = $result['checkoutUrl'];

// With options
$result = $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

<?php
// Get order by ID
$order = $torque->getOrder('order_123');

// Get order with specific fields
$order = $torque->getOrder('order_123', [
'fields' => ['id', 'status', 'amount', 'customer']
]);

List Orders

<?php
// Get all orders
$orders = $torque->listOrders();

// Get orders with filters
$orders = $torque->listOrders([
'status' => 'paid',
'startDate' => '2024-01-01',
'endDate' => '2024-12-31',
'limit' => 50,
'offset' => 0
]);

Cancel Order

<?php
// Cancel an order
$result = $torque->cancelOrder('order_123', [
'reason' => 'Customer requested cancellation'
]);

Webhook Management

Create Webhook

<?php
// Create a new webhook
$webhook = $torque->createWebhook([
'url' => 'https://yourdomain.com/webhooks/torque',
'events' => ['order.created', 'order.paid', 'order.completed'],
'secret' => 'your_webhook_secret'
]);

List Webhooks

<?php
// Get all webhooks
$webhooks = $torque->listWebhooks();

// Get webhooks by event type
$webhooks = $torque->listWebhooks([
'event' => 'order.paid'
]);

Update Webhook

<?php
// Update webhook configuration
$webhook = $torque->updateWebhook('webhook_123', [
'url' => 'https://newdomain.com/webhooks/torque',
'events' => ['order.created', 'order.paid', 'order.completed', 'order.cancelled']
]);

Delete Webhook

<?php
// Delete a webhook
$torque->deleteWebhook('webhook_123');

Analytics

Business Overview

<?php
// Get business overview
$overview = $torque->getBusinessOverview([
'period' => 'month', // 'day', 'week', 'month', 'year'
'startDate' => '2024-01-01',
'endDate' => '2024-12-31'
]);

Revenue Analytics

<?php
// Get revenue analytics
$revenue = $torque->getRevenueAnalytics([
'period' => 'month',
'startDate' => '2024-01-01',
'endDate' => '2024-12-31',
'groupBy' => 'day' // 'day', 'week', 'month'
]);

Order Analytics

<?php
// Get order analytics
$orders = $torque->getOrderAnalytics([
'period' => 'month',
'startDate' => '2024-01-01',
'endDate' => '2024-12-31',
'metrics' => ['count', 'value', 'conversion_rate']
]);

Framework Integration

Laravel Integration

<?php
// config/torque.php
return [
'business_id' => env('TORQUE_BUSINESS_ID'),
'api_key' => env('TORQUE_API_KEY'),
// No environment configuration needed
];

// app/Services/TorqueService.php
namespace App\Services;

use Torque\Checkout\TorqueCheckout;

class TorqueService
{
private $torque;

public function __construct()
{
$this->torque = new TorqueCheckout([
'businessId' => config('torque.business_id'),
'apiKey' => config('torque.api_key'),
'environment' => config('torque.environment')
]);
}

public function generateCheckout($cart, $customerData)
{
return $this->torque->generateCheckoutLink($cart, $customerData);
}

public function getOrder($orderId)
{
return $this->torque->getOrder($orderId);
}
}

// app/Http/Controllers/CheckoutController.php
namespace App\Http\Controllers;

use App\Services\TorqueService;
use Illuminate\Http\Request;

class CheckoutController extends Controller
{
private $torqueService;

public function __construct(TorqueService $torqueService)
{
$this->torqueService = $torqueService;
}

public function generateCheckout(Request $request)
{
$request->validate([
'cart' => 'required|array',
'customerData' => 'required|array'
]);

try {
$result = $this->torqueService->generateCheckout(
$request->cart,
$request->customerData
);

return response()->json($result);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}

WordPress Integration

<?php
// Plugin file
require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';

use Torque\Checkout\TorqueCheckout;

class TorqueCheckoutPlugin
{
private $torque;

public function __construct()
{
$this->torque = new TorqueCheckout([
'businessId' => get_option('torque_business_id'),
'apiKey' => get_option('torque_api_key'),
// No environment configuration needed
]);

add_action('wp_ajax_generate_torque_checkout', [$this, 'generateCheckout']);
add_action('wp_ajax_nopriv_generate_torque_checkout', [$this, 'generateCheckout']);
}

public function generateCheckout()
{
check_ajax_referer('torque_checkout_nonce', 'nonce');

try {
$cart = $this->getCartData();
$customerData = $this->getCustomerData();

$result = $this->torque->generateCheckoutLink($cart, $customerData);
wp_send_json_success($result);
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
}

private function getCartData()
{
// Convert WooCommerce cart to Torque format
$cart = WC()->cart;
$items = [];

foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
$items[] = [
'productId' => $product->get_id(),
'quantity' => $cart_item['quantity'],
'price' => $product->get_price(),
'variant' => $this->getVariantName($cart_item),
'metadata' => [
'sku' => $product->get_sku(),
'name' => $product->get_name()
]
];
}

return [
'items' => $items,
'currency' => get_woocommerce_currency()
];
}

private function getCustomerData()
{
$customer = [];

if (is_user_logged_in()) {
$user = wp_get_current_user();
$customer['email'] = $user->user_email;
$customer['firstName'] = $user->first_name;
$customer['lastName'] = $user->last_name;
}

return $customer;
}
}

// Initialize plugin
new TorqueCheckoutPlugin();

Webhook Handling

Standalone Webhook Handler

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

use Torque\Checkout\TorqueCheckout;

$torque = new TorqueCheckout([
'businessId' => $_ENV['TORQUE_BUSINESS_ID'],
'apiKey' => $_ENV['TORQUE_API_KEY']
]);

$webhookSecret = $_ENV['TORQUE_WEBHOOK_SECRET'];

// Get webhook data
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_TORQUE_SIGNATURE'] ?? '';

// Verify webhook signature
if (!$torque->verifyWebhookSignature($payload, $signature, $webhookSecret)) {
http_response_code(401);
echo json_encode(['error' => 'Invalid signature']);
exit;
}

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

switch ($event) {
case 'order.paid':
handleOrderPaid($eventData);
break;
case 'order.completed':
handleOrderCompleted($eventData);
break;
case 'order.cancelled':
handleOrderCancelled($eventData);
break;
}

http_response_code(200);
echo json_encode(['success' => true]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}

function handleOrderPaid($data)
{
$orderId = $data['orderId'];
error_log("Order {$orderId} has been paid");

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

function handleOrderCompleted($data)
{
$orderId = $data['orderId'];
error_log("Order {$orderId} has been completed");

// Handle order completion
}

function handleOrderCancelled($data)
{
$orderId = $data['orderId'];
error_log("Order {$orderId} has been cancelled");

// Handle order cancellation
}

Laravel Webhook Controller

<?php
// app/Http/Controllers/WebhookController.php
namespace App\Http\Controllers;

use App\Services\TorqueService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WebhookController extends Controller
{
private $torqueService;

public function __construct(TorqueService $torqueService)
{
$this->torqueService = $torqueService;
}

public function handleTorqueWebhook(Request $request)
{
try {
// Verify webhook signature
$signature = $request->header('X-Torque-Signature');
$payload = $request->getContent();

if (!$this->torqueService->verifyWebhookSignature($payload, $signature)) {
return response()->json(['error' => 'Invalid signature'], 401);
}

$data = $request->all();
$event = $data['event'] ?? '';
$eventData = $data['data'] ?? [];

// Process webhook event
$this->processWebhookEvent($event, $eventData);

return response()->json(['success' => true]);
} catch (\Exception $e) {
Log::error('Webhook processing error: ' . $e->getMessage());
return response()->json(['error' => 'Processing failed'], 500);
}
}

private function processWebhookEvent($event, $eventData)
{
switch ($event) {
case 'order.paid':
$this->handleOrderPaid($eventData);
break;
case 'order.completed':
$this->handleOrderCompleted($eventData);
break;
case 'order.cancelled':
$this->handleOrderCancelled($eventData);
break;
}
}

private function handleOrderPaid($data)
{
$orderId = $data['orderId'];
Log::info("Order {$orderId} has been paid");

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

private function handleOrderCompleted($data)
{
$orderId = $data['orderId'];
Log::info("Order {$orderId} has been completed");

// Handle order completion
}

private function handleOrderCancelled($data)
{
$orderId = $data['orderId'];
Log::info("Order {$orderId} has been cancelled");

// Handle order cancellation
}
}

Testing

Test Environment

<?php
// Use sandbox environment for testing
$torque = new TorqueCheckout([
'businessId' => 'test_business_123',
'apiKey' => 'test_api_key_456',
'environment' => 'sandbox'
]);

// Test checkout generation
$result = $torque->generateCheckoutLink([
'items' => [
[
'productId' => 'test_prod_1',
'quantity' => 1,
'price' => 9.99
]
]
], [
'email' => 'test@example.com',
'firstName' => 'Test',
'lastName' => 'User'
]);

Mock Data

<?php
// Sample cart data for testing
$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
$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

<?php
function generateCheckoutWithRetry($torque, $cart, $customerData, $maxRetries = 3)
{
for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
try {
$result = $torque->generateCheckoutLink($cart, $customerData);
return $result;
} catch (Exception $e) {
if ($attempt === $maxRetries) {
throw $e;
}

// Wait before retrying (exponential backoff)
$delay = pow(2, $attempt) * 1000;
usleep($delay * 1000);

error_log("Attempt {$attempt} failed, retrying in {$delay}ms...");
}
}
}

Error Types

<?php
use Torque\Checkout\Exceptions\TorqueException;

try {
$result = $torque->generateCheckoutLink($cart, $customerData);
} catch (TorqueException $e) {
switch ($e->getCode()) {
case 'INVALID_CART':
error_log('Cart data is invalid: ' . $e->getMessage());
break;
case 'INSUFFICIENT_FUNDS':
error_log('Insufficient funds for transaction');
break;
case 'RATE_LIMIT_EXCEEDED':
error_log('Rate limit exceeded, please wait');
break;
default:
error_log('Torque error: ' . $e->getMessage());
}
} catch (Exception $e) {
error_log('Unexpected error: ' . $e->getMessage());
}

Next Steps


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