Magento Integration
Integrate Torque's multi-product checkout with your Magento store to provide seamless checkout experiences for your customers.
๐ Quick Startโ
1. Install Torque Moduleโ
- Download Module: Get the Torque Checkout module
- Upload to Magento: Install via Composer or manual upload
- Enable Module: Enable in Magento admin
- Configure Settings: Enter your Torque API credentials
2. Configure Settingsโ
- API Credentials: Enter your Torque Business ID and API Key
- Checkout Options: Configure checkout appearance and behavior
- Webhook Setup: Enable real-time order updates
- Test Mode: Verify integration in sandbox environment
3. Go Liveโ
- Production Mode: Switch from test to live mode
- Monitor Orders: Track checkout performance
- Customer Support: Provide seamless customer experience
๐ง Manual Integrationโ
Module Developmentโ
If you prefer to build a custom integration:
Step 1: Create Torque Business Accountโ
- Sign Up: Visit torque.fi/business
- Complete Profile: Fill out business information
- Get Credentials: Note your Business ID and API Key
Step 2: Install Torque Packageโ
composer require torque/checkout
# or
npm install torque-checkout
Step 3: Create Magento Moduleโ
Create the module structure:
app/code/Torque/Checkout/
โโโ etc/
โ โโโ module.xml
โ โโโ di.xml
โ โโโ adminhtml/
โ โโโ system.xml
โโโ Model/
โ โโโ Config.php
โ โโโ Api.php
โโโ Controller/
โ โโโ Checkout/
โ โโโ Generate.php
โโโ view/
โ โโโ frontend/
โ โโโ web/
โ โ โโโ js/
โ โ โโโ css/
โ โโโ templates/
โโโ registration.php
Module Configurationโ
<!-- app/code/Torque/Checkout/etc/module.xml -->
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Torque_Checkout" setup_version="1.0.0">
<sequence>
<module name="Magento_Checkout"/>
</sequence>
</module>
</config>
Configuration Modelโ
<?php
// app/code/Torque/Checkout/Model/Config.php
namespace Torque\Checkout\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
const XML_PATH_API_KEY = 'torque_checkout/general/api_key';
const XML_PATH_BUSINESS_ID = 'torque_checkout/general/business_id';
const XML_PATH_ENABLED = 'torque_checkout/general/enabled';
private $scopeConfig;
public function __construct(ScopeConfigInterface $scopeConfig)
{
$this->scopeConfig = $scopeConfig;
}
public function getApiKey($storeId = null)
{
return $this->scopeConfig->getValue(
self::XML_PATH_API_KEY,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function getBusinessId($storeId = null)
{
return $this->scopeConfig->getValue(
self::XML_PATH_BUSINESS_ID,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function isEnabled($storeId = null)
{
return $this->scopeConfig->isSetFlag(
self::XML_PATH_ENABLED,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
}
API Integrationโ
<?php
// app/code/Torque/Checkout/Model/Api.php
namespace Torque\Checkout\Model;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Serialize\Serializer\Json;
class Api
{
private $curl;
private $json;
private $config;
public function __construct(
Curl $curl,
Json $json,
Config $config
) {
$this->curl = $curl;
$this->json = $json;
$this->config = $config;
}
public function generateCheckoutLink($cartData, $customerData)
{
$url = 'https://api.torque.fi/v1/checkout/generate-link';
$this->curl->addHeader('Authorization', 'Bearer ' . $this->config->getApiKey());
$this->curl->addHeader('Content-Type', 'application/json');
$postData = [
'businessId' => $this->config->getBusinessId(),
'cart' => $cartData,
'customerData' => $customerData
];
$this->curl->post($url, $this->json->serialize($postData));
$response = $this->curl->getBody();
$data = $this->json->unserialize($response);
return $data['checkoutUrl'] ?? null;
}
}
Checkout Controllerโ
<?php
// app/code/Torque/Checkout/Controller/Checkout/Generate.php
namespace Torque\Checkout\Controller\Checkout;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Torque\Checkout\Model\Api;
use Magento\Checkout\Model\Cart;
class Generate extends Action
{
private $jsonFactory;
private $api;
private $cart;
public function __construct(
Context $context,
JsonFactory $jsonFactory,
Api $api,
Cart $cart
) {
parent::__construct($context);
$this->jsonFactory = $jsonFactory;
$this->api = $api;
$this->cart = $cart;
}
public function execute()
{
$result = $this->jsonFactory->create();
try {
$cartData = $this->convertCartToTorque();
$customerData = $this->getCustomerData();
$checkoutUrl = $this->api->generateCheckoutLink($cartData, $customerData);
if ($checkoutUrl) {
$result->setData(['success' => true, 'checkout_url' => $checkoutUrl]);
} else {
$result->setData(['success' => false, 'error' => 'Failed to generate checkout link']);
}
} catch (\Exception $e) {
$result->setData(['success' => false, 'error' => $e->getMessage()]);
}
return $result;
}
private function convertCartToTorque()
{
$items = [];
$cartItems = $this->cart->getItems();
foreach ($cartItems as $item) {
$items[] = [
'productId' => $item->getProductId(),
'quantity' => $item->getQty(),
'price' => $item->getPrice(),
'variant' => $item->getProduct()->getTypeId() === 'configurable' ? $item->getProduct()->getName() : null,
'metadata' => [
'sku' => $item->getProduct()->getSku(),
'name' => $item->getProduct()->getName()
]
];
}
return [
'items' => $items,
'currency' => $this->cart->getQuote()->getQuoteCurrencyCode()
];
}
private function getCustomerData()
{
$customer = [];
$customerSession = $this->_objectManager->get(\Magento\Customer\Model\Session::class);
if ($customerSession->isLoggedIn()) {
$customerData = $customerSession->getCustomer();
$customer['email'] = $customerData->getEmail();
$customer['firstName'] = $customerData->getFirstname();
$customer['lastName'] = $customerData->getLastname();
}
return $customer;
}
}
๐จ Frontend Integrationโ
Add Checkout Buttonโ
Template Integrationโ
<!-- app/code/Torque/Checkout/view/frontend/templates/cart/torque-checkout.phtml -->
<?php if ($block->isEnabled()): ?>
<div class="torque-checkout-section">
<button id="torque-checkout-btn" class="action primary checkout">
<span><?= $block->escapeHtml(__('Checkout with Torque')) ?></span>
</button>
</div>
<script type="text/x-magento-init">
{
"#torque-checkout-btn": {
"Torque_Checkout/js/checkout": {
"ajaxUrl": "<?= $block->escapeUrl($block->getAjaxUrl()) ?>"
}
}
}
</script>
<?php endif; ?>
JavaScript Implementationโ
// app/code/Torque/Checkout/view/frontend/web/js/checkout.js
define([
'jquery',
'mage/url'
], function ($, urlBuilder) {
'use strict';
return function (config) {
$('#torque-checkout-btn').on('click', function (e) {
e.preventDefault();
var $button = $(this);
$button.prop('disabled', true);
$button.find('span').text('Generating Checkout...');
$.ajax({
url: config.ajaxUrl,
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.success && response.checkout_url) {
window.location.href = response.checkout_url;
} else {
alert('Failed to generate checkout link: ' + (response.error || 'Unknown error'));
$button.prop('disabled', false);
$button.find('span').text('Checkout with Torque');
}
},
error: function () {
alert('Failed to generate checkout link. Please try again.');
$button.prop('disabled', false);
$button.find('span').text('Checkout with Torque');
}
});
});
};
});
๐ Webhook Integrationโ
Handle Order Updatesโ
<?php
// app/code/Torque/Checkout/Controller/Webhook/OrderUpdate.php
namespace Torque\Checkout\Controller\Webhook;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Sales\Model\OrderFactory;
use Magento\Framework\App\RequestInterface;
class OrderUpdate extends Action
{
private $jsonFactory;
private $orderFactory;
public function __construct(
Context $context,
JsonFactory $jsonFactory,
OrderFactory $orderFactory
) {
parent::__construct($context);
$this->jsonFactory = $jsonFactory;
$this->orderFactory = $orderFactory;
}
public function execute()
{
$result = $this->jsonFactory->create();
try {
$request = $this->getRequest();
$event = $request->getParam('event');
$data = $request->getParam('data');
switch ($event) {
case 'order.paid':
$this->handleOrderPaid($data);
break;
case 'order.completed':
$this->handleOrderCompleted($data);
break;
case 'order.cancelled':
$this->handleOrderCancelled($data);
break;
}
$result->setData(['success' => true]);
} catch (\Exception $e) {
$result->setData(['success' => false, 'error' => $e->getMessage()]);
}
return $result;
}
private function handleOrderPaid($data)
{
// Update Magento order status
$orderId = $this->getMagentoOrderId($data['orderId']);
if ($orderId) {
$order = $this->orderFactory->create()->load($orderId);
$order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING);
$order->setStatus(\Magento\Sales\Model\Order::STATE_PROCESSING);
$order->save();
}
}
private function getMagentoOrderId($torqueOrderId)
{
// Implement logic to find Magento order by Torque order ID
// This would typically involve a custom table or attribute
return null;
}
}
๐งช Testingโ
Test Modeโ
- Enable Test Mode: Use test API keys and sandbox environment
- Create Test Orders: Generate test checkout links
- Verify Webhooks: Test webhook delivery and processing
- Check Integration: Ensure data flows correctly between systems
Test Scenariosโ
- Cart Conversion: Verify Magento cart converts to Torque format
- Checkout Flow: Test complete checkout process
- Order Sync: Confirm orders sync between platforms
- Webhook Delivery: Test real-time updates
- Error Handling: Test various error scenarios
๐จ Troubleshootingโ
Common Issuesโ
Checkout Link Generation Failsโ
Problem: API returns error when generating checkout link
Solutions:
- Verify API credentials are correct
- Check cart data format
- Ensure all required fields are present
- Review API error logs
Orders Not Syncingโ
Problem: Orders created in Torque don't appear in Magento
Solutions:
- Verify webhook endpoints are accessible
- Check webhook signature verification
- Review webhook processing logs
- Ensure proper error handling
Cart Data Mismatchโ
Problem: Cart items don't match between platforms
Solutions:
- Verify cart conversion logic
- Check product ID mapping
- Ensure price and quantity accuracy
- Test with simple cart items first
Debug Toolsโ
Loggingโ
// Enable detailed logging
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/torque.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Torque API call: ' . json_encode($postData));
Webhook Testingโ
# Test webhook endpoint
curl -X POST https://yourdomain.com/torque/webhook/orderUpdate \
-H "Content-Type: application/json" \
-d '{
"event": "order.created",
"data": {"orderId": "test_123"}
}'
๐ Next Stepsโ
- Shopify Integration: Ecommerce platform integration
- WooCommerce Integration: WordPress integration
- Business Dashboard: Manage your integration
- API Reference: Complete API documentation
Need help with Magento integration? Contact our support team at hello@torque.fi or check our integration troubleshooting guide.