OpenCart 4.0 API Integration - Developer Guide

Published on July 23, 2025
OpenCart 4.0 API Integration - Developer Guide - Featured image for this article

OpenCart 4.0 API Integration

OpenCart 4.0 brings powerful API capabilities that allow integration with external services and creating custom solutions. This guide will show the complete process.

API Fundamentals:

1. Authentication Setup

// API Token generation
$username = "api_user";
$password = "secure_password";
$api_token = hash("sha256", $username . $password . date("Y-m-d H:i:s"));

// Headers configuration
$headers = [
    "Content-Type: application/json",
    "Authorization: Bearer " . $api_token,
    "Accept: application/json"
];

2. Main endpoints:

  • /api/customers - customer management
  • /api/products - product management
  • /api/orders - order management
  • /api/categories - category management
  • /api/manufacturers - manufacturer management

Practical Examples:

1. Adding new product:

function addProduct($product_data, $headers) {
    $url = "https://yourstore.com/api/products";

    $data = [
        "name" => $product_data["name"],
        "description" => $product_data["description"],
        "price" => $product_data["price"],
        "sku" => $product_data["sku"],
        "quantity" => $product_data["quantity"],
        "status" => 1,
        "category_id" => $product_data["category_id"],
        "image" => $product_data["image_url"]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code === 201) {
        return json_decode($response, true);
    } else {
        throw new Exception("API Error: " . $response);
    }
}

2. Getting order data:

function getOrder($order_id, $headers) {
    $url = "https://yourstore.com/api/orders/" . $order_id;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code === 200) {
        return json_decode($response, true);
    } else {
        return false;
    }
}

Advanced Functionality:

1. Webhook setup:

// Webhook endpoint handler
function handleOpenCartWebhook() {
    $payload = file_get_contents("php://input");
    $data = json_decode($payload, true);

    // Verify webhook signature
    $signature = $_SERVER["HTTP_X_OPENCART_SIGNATURE"] ?? "";
    if (!verifyWebhookSignature($payload, $signature)) {
        http_response_code(401);
        exit("Unauthorized");
    }

    $event_type = $data["event"] ?? "";

    switch ($event_type) {
        case "order.created":
            processNewOrder($data["order"]);
            break;
        case "order.updated":
            updateOrderStatus($data["order"]);
            break;
        case "product.updated":
            syncProductToWarehouse($data["product"]);
            break;
        case "customer.registered":
            sendWelcomeEmail($data["customer"]);
            break;
        default:
            error_log("Unknown webhook event: " . $event_type);
    }

    http_response_code(200);
    echo "OK";
}

2. Bulk inventory sync:

class InventorySync {
    private $api_url;
    private $headers;

    public function __construct($api_url, $headers) {
        $this->api_url = $api_url;
        $this->headers = $headers;
    }

    public function syncBulkInventory($products) {
        $batch_size = 50;
        $batches = array_chunk($products, $batch_size);

        foreach ($batches as $batch) {
            $this->processBatch($batch);
            sleep(1); // Rate limiting
        }
    }
}

Security Considerations:

βœ… Best Practices:

  • Use HTTPS only
  • Store API keys in environment variables
  • Input validation for all data
  • SQL injection protection
  • Implement rate limiting
  • Add comprehensive logging
  • Error handling for all requests

Error Handling:

function handleApiError($response_code, $response_body) {
    switch ($response_code) {
        case 401:
            throw new UnauthorizedException("Invalid API credentials");
        case 403:
            throw new ForbiddenException("Access denied");
        case 404:
            throw new NotFoundException("Resource not found");
        case 429:
            throw new RateLimitException("Rate limit exceeded");
        case 500:
            throw new ServerException("Internal server error: " . $response_body);
        default:
            if ($response_code >= 400) {
                throw new ApiException("API Error ($response_code): " . $response_body);
            }
            return json_decode($response_body, true);
    }
}

Testing and Debugging:

πŸ”§ Testing Tools:

  • Use Postman/Insomnia for testing API calls
  • Write unit tests for all API functions
  • Create integration tests for end-to-end scenarios
  • Set up log monitoring in production environment
  • Collect performance metrics for API response times

Conclusion: Proper API usage and quality integration can significantly improve your OpenCart store functionality and create valuable business solutions.

Stay Updated with OpenCart Armenia

Get the latest OpenCart extensions, themes, and development tips delivered to your inbox.

Join 2,500+ developers and store owners. No spam, unsubscribe anytime