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

如何集成Magento电商与Openbravo?Magento2与Openbravo ERP数据同步方法

Hey there! Let's walk through how to integrate your Magento 2 store with your existing Openbravo ERP, focusing specifically on syncing orders and inventory data to Openbravo via APIs—since that's exactly what you're asking for. I've done this a few times, so here's a practical, step-by-step breakdown:

Magento 2 ↔ Openbravo ERP: Order & Inventory Sync via APIs

1. Syncing Magento Orders to Openbravo

The goal here is to push new, paid orders from Magento to Openbravo so your ERP can handle fulfillment, invoicing, etc. Here's how to build this:

Step 1: Capture Order Events in Magento

First, set up an observer in Magento to trigger sync when an order moves to a "processing" state (since that's usually when payment is confirmed). This ensures you only sync valid orders.

Create an observer class (example below) that listens to the sales_order_save_after event:

// app/code/YourVendor/Integration/Observer/SyncOrderToOpenbravo.php
namespace YourVendor\Integration\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use YourVendor\Integration\Helper\OpenbravoApi;
use Psr\Log\LoggerInterface;

class SyncOrderToOpenbravo implements ObserverInterface
{
    protected $openbravoApi;
    protected $logger;

    public function __construct(OpenbravoApi $openbravoApi, LoggerInterface $logger)
    {
        $this->openbravoApi = $openbravoApi;
        $this->logger = $logger;
    }

    public function execute(Observer $observer)
    {
        $order = $observer->getEvent()->getOrder();
        // Skip if order isn't in processing state or already synced
        if ($order->getState() !== \Magento\Sales\Model\Order::STATE_PROCESSING || $order->getData('openbravo_synced')) {
            return;
        }

        // Map Magento order data to Openbravo's expected format
        $orderData = [
            'documentNo' => $order->getIncrementId(),
            'businessPartner' => [
                'searchKey' => $order->getCustomerEmail(),
                'name' => $order->getCustomerName(),
                'address' => [
                    'street' => $order->getShippingAddress()->getStreetLine(1),
                    'city' => $order->getShippingAddress()->getCity(),
                    'postalCode' => $order->getShippingAddress()->getPostcode()
                ]
            ],
            'orderLines' => []
        ];

        // Add order items
        foreach ($order->getAllVisibleItems() as $item) {
            $orderData['orderLines'][] = [
                'product' => ['searchKey' => $item->getSku()],
                'quantity' => $item->getQtyOrdered(),
                'price' => $item->getPrice(),
                'taxRate' => $item->getTaxPercent()
            ];
        }

        // Send to Openbravo API
        try {
            $this->openbravoApi->createOrder($orderData);
            // Mark order as synced in Magento (add a custom 'openbravo_synced' attribute first!)
            $order->setData('openbravo_synced', 1)->save();
            $this->logger->info('Successfully synced order ' . $order->getIncrementId() . ' to Openbravo');
        } catch (\Exception $e) {
            $this->logger->error('Failed to sync order ' . $order->getIncrementId() . ': ' . $e->getMessage());
        }
    }
}

Step 2: Call Openbravo's REST API to Create Orders

Openbravo uses REST APIs for data operations. First, you'll need to authenticate to get a bearer token:

# Get Openbravo authentication token
curl -X POST https://your-openbravo-url.com/api/v2/authenticate \
  -H "Content-Type: application/json" \
  -d '{"username":"your-api-user","password":"your-api-password"}'

Use this token to send the mapped order data to Openbravo's order creation endpoint:

# Create order in Openbravo
curl -X POST https://your-openbravo-url.com/api/v2/order \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_AUTH_TOKEN" \
  -d '{"documentNo":"MAG20240001","businessPartner":{"searchKey":"customer@example.com","name":"John Doe"},"orderLines":[{"product":{"searchKey":"SKU-123"},"quantity":2,"price":49.99}]}'

Step 3: Handle Retries & Logging

Add a cron job in Magento to periodically check for orders that failed to sync (where openbravo_synced is 0) and retry the API call. This prevents data loss if the Openbravo API is temporarily down.

2. Syncing Magento Inventory to Openbravo

If you need to push Magento's stock levels to Openbravo (for centralized inventory tracking), follow these steps:

Step 1: Capture Inventory Changes in Magento

Set up another observer to listen for stock updates using the cataloginventory_stock_item_save_after event:

// app/code/YourVendor/Integration/Observer/SyncInventoryToOpenbravo.php
namespace YourVendor\Integration\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use YourVendor\Integration\Helper\OpenbravoApi;
use Psr\Log\LoggerInterface;

class SyncInventoryToOpenbravo implements ObserverInterface
{
    protected $openbravoApi;
    protected $logger;

    public function __construct(OpenbravoApi $openbravoApi, LoggerInterface $logger)
    {
        $this->openbravoApi = $openbravoApi;
        $this->logger = $logger;
    }

    public function execute(Observer $observer)
    {
        $stockItem = $observer->getEvent()->getItem();
        $product = $stockItem->getProduct();
        $sku = $product->getSku();
        $newQty = $stockItem->getQty();

        // Map to Openbravo stock data format
        $stockData = [
            'product' => ['searchKey' => $sku],
            'warehouse' => ['searchKey' => 'MAIN_WH'], // Match your Openbravo warehouse key
            'quantityOnHand' => $newQty
        ];

        try {
            $this->openbravoApi->updateStock($stockData);
            $this->logger->info('Successfully updated stock for SKU ' . $sku . ' in Openbravo');
        } catch (\Exception $e) {
            $this->logger->error('Failed to update stock for SKU ' . $sku . ': ' . $e->getMessage());
        }
    }
}

Step 2: Update Stock in Openbravo via API

Use the same authentication token from earlier to call Openbravo's stock update endpoint:

# Update inventory in Openbravo
curl -X PUT https://your-openbravo-url.com/api/v2/product/SKU-123/stock \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_AUTH_TOKEN" \
  -d '{"warehouse":{"searchKey":"MAIN_WH"},"quantityOnHand":15}'

Key Things to Remember

  • Authentication & Permissions: Create dedicated API users in both systems. For Openbravo, ensure the user has permissions to create orders and modify inventory. In Magento, assign the integration user roles for Sales and Catalog access.
  • Field Mapping: Double-check that critical fields (like currency, tax codes, and payment methods) align between the two systems. Mismatches here will cause data errors.
  • Test First: Always test syncs in a staging environment with sample orders and inventory changes. Verify data appears correctly in Openbravo before going live.
  • Error Handling: Log every sync attempt (success or failure) so you can troubleshoot issues quickly. Use cron jobs to retry failed syncs automatically.

内容的提问来源于stack exchange,提问作者Nakib Rubeen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:39:41