Skip to main content

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โ€‹

  1. Download Module: Get the Torque Checkout module
  2. Upload to Magento: Install via Composer or manual upload
  3. Enable Module: Enable in Magento admin
  4. Configure Settings: Enter your Torque API credentials

2. Configure Settingsโ€‹

  1. API Credentials: Enter your Torque Business ID and API Key
  2. Checkout Options: Configure checkout appearance and behavior
  3. Webhook Setup: Enable real-time order updates
  4. Test Mode: Verify integration in sandbox environment

3. Go Liveโ€‹

  1. Production Mode: Switch from test to live mode
  2. Monitor Orders: Track checkout performance
  3. Customer Support: Provide seamless customer experience

๐Ÿ”ง Manual Integrationโ€‹

Module Developmentโ€‹

If you prefer to build a custom integration:

Step 1: Create Torque Business Accountโ€‹

  1. Sign Up: Visit torque.fi/business
  2. Complete Profile: Fill out business information
  3. 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โ€‹

  1. Enable Test Mode: Use test API keys and sandbox environment
  2. Create Test Orders: Generate test checkout links
  3. Verify Webhooks: Test webhook delivery and processing
  4. 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โ€‹

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โ€‹


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