Running a growing e-commerce brand on Shopify while managing inventory, fulfillment, and accounting in Odoo ERP is a very common architecture. However, many teams start by manually exporting CSVs from Shopify and importing them into Odoo at the end of every business day.
As order volume scales, manual entry creates bottlenecks: delayed fulfillment, stockouts due to delayed inventory updates, human entry errors, and missing customer data.
In this guide, I will walk you through how to build a clean, event-driven integration middleware in Python. When an order is placed on Shopify, a webhook triggers a lightweight Python service that verifies the payload, maps the data, and automatically creates a confirmed Sales Order in Odoo via XML-RPC.
System Architecture
Instead of polling Shopify APIs periodically, an event-driven architecture processes orders in near real-time.
+------------------+ +-------------------------------+ +---------------------+
| Shopify Store | ------> | Python Middleware (FastAPI) | ------> | Odoo ERP |
| (orders/create) | POST | 1. Verify HMAC Signature | XML-RPC | - res.partner |
+------------------+ | 2. Transform & Map Data | | - product.product |
| 3. Push to Odoo XML-RPC API | | - sale.order |
+-------------------------------+ +---------------------+
Key Workflow Steps:
-
Shopify Webhook: Shopify sends a
JSONpayload to your endpoint wheneverorders/createfires. - HMAC Verification: The middleware verifies the payload signature to ensure requests originate from Shopify.
- Data Transformation: Customer information, shipping details, and line items are extracted and formatted.
-
Odoo XML-RPC Operations:
- Look up or create the customer (
res.partner). - Match line items against Odoo product SKUs (
product.product). - Construct and create the Sales Order (
sale.order).
- Look up or create the customer (
Step 1: Receiving & Verifying Shopify Webhooks
Security is paramount when exposing a public endpoint for webhooks. Shopify includes an X-Shopify-Hmac-SHA256 header with every request, calculated using your app's Webhook Secret Key.
Here is how to set up a FastAPI endpoint that verifies this signature before processing any data:
import base64
import hashlib
import hmac
import os
from fastapi import FastAPI, Header, HTTPException, Request, Response
app = FastAPI()
SHOPIFY_WEBHOOK_SECRET = os.getenv("SHOPIFY_WEBHOOK_SECRET", "YOUR_SHOPIFY_SECRET")
def verify_shopify_webhook(data: bytes, hmac_header: str) -> bool:
"""Verifies that the incoming request came from Shopify."""
digest = hmac.new(
SHOPIFY_WEBHOOK_SECRET.encode('utf-8'),
data,
hashlib.sha256
).digest()
computed_hmac = base64.b64encode(digest).decode('utf-8')
return hmac.compare_digest(computed_hmac, hmac_header)
@app.post("/webhooks/shopify/order-created")
async def handle_order_created(
request: Request,
x_shopify_hmac_sha256: str = Header(None)
):
if not x_shopify_hmac_sha256:
raise HTTPException(status_code=400, detail="Missing HMAC header")
body = await request.body()
if not verify_shopify_webhook(body, x_shopify_hmac_sha256):
raise HTTPException(status_code=401, detail="Invalid HMAC signature")
order_data = await request.json()
# Process order in Odoo
sync_order_to_odoo(order_data)
return Response(status_code=200)
Step 2: Interacting with Odoo via XML-RPC
Odoo provides native XML-RPC web services for authentication and database operations (res.partner, product.product, sale.order, sale.order.line).
Below is a Python wrapper class to handle Odoo authentication and CRUD operations cleanly:
import xmlrpc.client
class OdooConnector:
def __init__(self, url, db, username, password):
self.url = url.rstrip('/')
self.db = db
self.username = username
self.password = password
self.uid = None
# Connect to common endpoint for authentication
self.common = xmlrpc.client.ServerProxy(f"{self.url}/xmlrpc/2/common")
self.models = xmlrpc.client.ServerProxy(f"{self.url}/xmlrpc/2/object")
self.authenticate()
def authenticate(self):
self.uid = self.common.authenticate(self.db, self.username, self.password, {})
if not self.uid:
raise Exception("Failed to authenticate with Odoo")
def execute(self, model, method, *args, **kwargs):
"""Helper to execute methods on Odoo models."""
return self.models.execute_kw(
self.db, self.uid, self.password, model, method, list(args), kwargs
)
Step 3: Mapping Shopify Payload to Odoo Records
Now, let's assemble the logic to search or create records inside Odoo.
1. Customer Lookup or Creation (res.partner)
Check if a customer with the Shopify customer email exists in Odoo. If not, create a new contact.
def get_or_create_partner(odoo: OdooConnector, shopify_customer: dict) -> int:
email = shopify_customer.get("email")
first_name = shopify_customer.get("first_name", "")
last_name = shopify_customer.get("last_name", "")
name = f"{first_name} {last_name}".strip() or email
# Search for existing partner by email
partner_ids = odoo.execute('res.partner', 'search', [('email', '=', email)])
if partner_ids:
return partner_ids[0]
# Create new partner if not found
partner_data = {
'name': name,
'email': email,
'phone': shopify_customer.get("phone", ""),
'customer_rank': 1,
}
return odoo.execute('res.partner', 'create', partner_data)
2. Matching Products by SKU (product.product)
Ensure product SKUs in Shopify correspond to default_code in Odoo.
def get_product_by_sku(odoo: OdooConnector, sku: str) -> int:
product_ids = odoo.execute('product.product', 'search', [('default_code', '=', sku)])
if product_ids:
return product_ids[0]
raise Exception(f"Product SKU '{sku}' not found in Odoo")
3. Constructing the Sales Order (sale.order)
Map line items into Odoo's One2many field format (0, 0, values_dict).
def sync_order_to_odoo(odoo: OdooConnector, order_data: dict):
# 1. Partner
customer_info = order_data.get("customer", {})
partner_id = get_or_create_partner(odoo, customer_info)
# 2. Prepare Order Lines
order_lines = []
for line in order_data.get("line_items", []):
sku = line.get("sku")
if not sku:
continue
product_id = get_product_by_sku(odoo, sku)
price_unit = float(line.get("price", 0.0))
quantity = line.get("quantity", 1)
order_lines.append((0, 0, {
'product_id': product_id,
'product_uom_qty': quantity,
'price_unit': price_unit,
'name': line.get("name", "Shopify Line Item")
}))
# 3. Create Sale Order
shopify_order_number = str(order_data.get("order_number"))
sale_order_data = {
'partner_id': partner_id,
'client_order_ref': f"Shopify #{shopify_order_number}",
'order_line': order_lines,
}
order_id = odoo.execute('sale.order', 'create', sale_order_data)
print(f"Successfully synced Shopify Order #{shopify_order_number} -> Odoo Order ID {order_id}")
return order_id
Edge Cases & Production Pitfalls
When deploying this in production, keep the following considerations in mind:
-
Idempotency & Duplicate Webhooks: Shopify may re-try webhooks if your endpoint responds slowly. Always store the Shopify Order ID or log it against
client_order_refin Odoo to check if the order has already been processed. - Asynchronous Execution: Shopify requires a 200 OK HTTP response within 5 seconds. For high-volume stores, do not run XML-RPC directly inside the HTTP request loop. Use a task queue like Celery, RQ, or FastAPI BackgroundTasks to acknowledge the webhook immediately and process the Odoo payload asynchronously.
- Missing SKUs or Unmapped Products: If a product exists on Shopify but has no matching SKU in Odoo, order creation will fail. Implement a fallback rule, such as routing the order to a generic "Unmapped Item" product or sending an alert for administrative review.
- Shipping & Tax Mapping: Remember to account for shipping lines, discounts, and taxes by configuring matching fiscal positions and delivery methods in Odoo.
Implementation Checklist
- [ ] Webhook URL registered in Shopify Admin (
Settings > Notifications > Webhooks). - [ ] HMAC SHA256 signature verification implemented and tested.
- [ ] Odoo XML-RPC credentials configured using environment variables.
- [ ] SKUs synchronized between Shopify variants and Odoo
default_code. - [ ] Idempotency check added using Shopify Order ID.
- [ ] Background queue added to ensure < 5s response time back to Shopify.
I'm Nandan Singh — I build AI and automation systems (Odoo, Zoho, chatbots, voice agents) at NMT Solutions. Questions? Drop a comment or WhatsApp +91 92260 02903.
Top comments (0)