You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PrestaShop创建订单时触发代码:第三方订单通知实现咨询

Hey Traian, great question—let’s walk through the cleanest, PrestaShop-compliant way to implement this without touching any core code. Here’s exactly what you need to do:

Best Approach: Use a Lightweight Module with the Right Hook

Step 1: Choose the Perfect Hook

Since you need to trigger your code as soon as the order is saved to the system (regardless of payment status or order state, whether created via the backoffice "Complete Sale" button or frontend checkout), the ideal hook is actionObjectOrderAddAfter.

This hook fires immediately after an Order object is successfully inserted into the database—exactly the moment you want to send your notification. It’s fully compatible with all recent PrestaShop versions (1.7+) and doesn’t require any core modifications.

Step 2: Build the Lightweight Module

You don’t need a complex module—just a single file to handle the hook and send the notification. Here’s a complete, ready-to-use implementation:

<?php
if (!defined('_PS_VERSION_')) {
    exit;
}

class CustomOrderNotifier extends Module
{
    public function __construct()
    {
        $this->name = 'custom_order_notifier';
        $this->tab = 'administration';
        $this->version = '1.0.0';
        $this->author = 'Your Name';
        $this->need_instance = 0; // No need to load module in backoffice except for install
        $this->bootstrap = true;

        parent::__construct();

        // Translatable strings (works with Romanian backoffice language)
        $this->displayName = $this->l('Custom Order Notifier');
        $this->description = $this->l('Trimite detalii despre comandă către sistemul extern atunci când o comandă este creată.'); // Romanian description
    }

    public function install()
    {
        // Register the hook during installation
        return parent::install() && $this->registerHook('actionObjectOrderAddAfter');
    }

    public function hookActionObjectOrderAddAfter($params)
    {
        // Get the newly created order object
        /** @var Order $order */
        $order = $params['object'];

        // Compile all order details you need for the external system
        $orderPayload = [
            'order_id' => $order->id,
            'reference' => $order->reference,
            'total_amount' => $order->total_paid,
            'currency_code' => Currency::getCurrencyInstance($order->id_currency)->iso_code,
            'customer' => [
                'id' => $order->id_customer,
                'email' => $order->customer->email,
                'full_name' => $order->customer->firstname . ' ' . $order->customer->lastname
            ],
            'products' => []
        ];

        // Fetch order products and add to payload
        foreach ($order->getProducts() as $product) {
            $orderPayload['products'][] = [
                'product_id' => $product['product_id'],
                'product_name' => $product['product_name'],
                'quantity' => $product['product_quantity'],
                'unit_price' => $product['product_price'],
                'total_price' => $product['total_price']
            ];
        }

        // Send the payload to your external system
        $this->sendNotificationToExternalSystem($orderPayload);
    }

    private function sendNotificationToExternalSystem($payload)
    {
        // Replace with your external system's API endpoint
        $externalApiUrl = 'https://your-external-system.com/api/new-order';

        // Use PrestaShop's built-in HttpClient (1.7.7+) to avoid external dependencies
        try {
            $client = new HttpClient();
            $response = $client->post($externalApiUrl, [
                'headers' => ['Content-Type' => 'application/json'],
                'json' => $payload
            ]);

            // Log success for debugging (check in Backoffice > Advanced Parameters > Logs)
            Logger::addLog(
                "Notificare comandă trimisă cu succes pentru comandă #{$payload['order_id']}",
                1, // Info level
                null,
                'CustomOrderNotifier',
                null,
                true
            );
        } catch (Exception $e) {
            // Log errors for troubleshooting
            Logger::addLog(
                "Eroare la trimiterea notificării pentru comandă #{$payload['order_id']}: {$e->getMessage()}",
                3, // Error level
                null,
                'CustomOrderNotifier',
                null,
                true
            );
        }
    }
}

Step 3: Key Details & Adjustments

  • Romanian Language Support: The module uses $this->l() for all visible strings, so PrestaShop will automatically display them in Romanian if your backoffice is set to that language. I’ve even added a Romanian description for you!
  • Payload Customization: Modify the $orderPayload array to include any additional fields your external system needs (like shipping address, tax details, etc.). You can access all Order object properties and related data (e.g., $order->getAddresses() for customer addresses).
  • Legacy PrestaShop Compatibility: For versions older than 1.7.7 (where HttpClient isn’t available), replace the HttpClient code with a standard cURL request. Here’s a quick alternative for the sendNotificationToExternalSystem method:
    private function sendNotificationToExternalSystem($payload)
    {
        $externalApiUrl = 'https://your-external-system.com/api/new-order';
        $ch = curl_init($externalApiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
    
        if ($error) {
            Logger::addLog("Eroare cURL: {$error}", 3, null, 'CustomOrderNotifier', null, true);
        } else {
            Logger::addLog("Notificare trimisă cu succes", 1, null, 'CustomOrderNotifier', null, true);
        }
    }
    
  • Testing: After installing the module, create a test order via the backoffice (click "Complete Sale") and check the PrestaShop logs (Backoffice > Advanced Parameters > Logs) to confirm the notification was sent. You can also verify with your external system’s API logs.

Why This Works

  • No Core Modifications: Everything is contained within a module, so you won’t break future PrestaShop updates.
  • Lightweight: Only one file, no unnecessary dependencies or complex setup.
  • Precise Trigger: The hook fires exactly when the order is saved to the database, matching your requirement of "when the order is entered into the system".

内容的提问来源于stack exchange,提问作者Traian GEICU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:52:43