prestashop_get_order / prestashop_find_orders
Find a customer's PrestaShop orders by order number or email, with each order's current status.
prestashop_get_order(context: dict, order_number: str) -> dict | None
prestashop_find_orders(context: dict, email: str, limit: int = 10) -> list[dict]Thin helpers for the most common PrestaShop read: finding a customer's order. They let an action answer "where is my order?" from the business's connected store in a few lines. They read the connection with get_integration_credentials, call the PrestaShop webservice through Octocom's proxy and return the orders as PrestaShop returns them. See the PrestaShop API reference for every field. Each order also carries its current state's name under status.
prestashop_get_order matches the internal order ID first, then the printed reference. prestashop_find_orders finds the customer account with that email; guest checkouts have no account and aren't found. Both helpers raise ValueError if PrestaShop isn't connected and requests.HTTPError if PrestaShop rejects the request.
The full source is below. Copy it into your own action when you need something it doesn't do.
prestashop_get_order
| Name | Type | Description |
|---|---|---|
context | dict | The context object passed to your action |
order_number | str | The order ID or printed reference as the customer gave it. Spaces and a leading # are ignored |
Returns the matching order, or None.
prestashop_find_orders
| Name | Type | Description |
|---|---|---|
context | dict | The context object passed to your action |
email | str | The customer's email address |
limit | int | Maximum number of orders, newest first (10) |
Returns a list of orders, newest first. Empty if there are none.
Example
def execute_action(context):
order = prestashop_get_order(context, context["args"]["orderId"])
if order is None:
return {"success": False, "message": "The order could not be found."}
return {"success": True, "orders": [order]}When you first connect PrestaShop to a business, Octocom adds an action like this example as its getOrderDetailsByOrderId action, a getOrderDetailsByEmail action that calls prestashop_find_orders, and an orders panel in the conversation sidebar. It skips this when the business already has its own order actions or sidebar widget. They are ordinary Python actions you can read and change.
Read-only sidebar
prestashop_order_widget(context) renders the saved order ID and customer email lookups as a basic sidebar panel without order buttons. See Order widgets for setup, custom mappings and the shared presentation source.
Source
import re
import requests
# The User-Agent the connection test and the backend's proxy client send
# (OCTOCOM_PROXY.userAgent in lib/clients/octocomProxy.ts). Without it, requests
# go out as "python-requests/x.y", which some stores' Cloudflare rules block with
# a 403 "Request forbidden by administrative rules": the connection test passed
# while every order lookup from the same proxy IP was rejected.
_PRESTASHOP_USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0"
)
def _prestashop_store(context):
"""The current business's PrestaShop connection: {"storeUrl", "apiKey"}."""
business = context.get("business") or {}
slug = business.get("slug") or (context.get("conversation") or {}).get("businessSlug")
if not slug:
raise ValueError("The business is not available in the context")
store = (get_integration_credentials(context).get(slug) or {}).get("prestaShop")
if not store:
raise ValueError("PrestaShop is not connected for this business")
return store
def _prestashop_get(store, resource, params):
# PrestaShop authenticates with ws_key in the query string, so the request
# URL carries the store's API key. Failures name only the resource and
# status: requests' own messages include the URL, and failure text reaches
# the bot model, logs and the dashboard.
try:
# PrestaShop stores allowlist Octocom's proxy IP, like the connector.
response = proxy_request(
"GET",
store["storeUrl"].rstrip("/") + "/api/" + resource,
params={"ws_key": store["apiKey"], "output_format": "JSON", **params},
headers={"User-Agent": _PRESTASHOP_USER_AGENT},
timeout=20,
)
except requests.RequestException as error:
raise requests.ConnectionError(
f"PrestaShop request for {resource} failed ({type(error).__name__})"
) from None
if not response.ok:
raise requests.HTTPError(
f"PrestaShop returned HTTP {response.status_code} for {resource}", response=response
)
body = response.json() if response.content.strip() else {}
# An empty result is "[]" rather than an object.
items = body.get(resource) if isinstance(body, dict) else None
if isinstance(items, dict):
items = [items]
return items or []
def _prestashop_with_status(store, order):
"""The order with its current state's name under "status"."""
states = _prestashop_get(store, "order_states", {"filter[id]": order.get("current_state"), "display": "[name]"})
name = states[0].get("name") if states else None
# Multilingual stores return [{"id": language, "value": name}, ...].
if isinstance(name, list):
name = name[0].get("value") if name else None
elif isinstance(name, dict):
name = name.get("value")
order["status"] = name
return order
def _prestashop_orders(store, field, value, limit):
orders = _prestashop_get(store, "orders", {
f"filter[{field}]": value, "display": "full", "sort": "[id_DESC]", "limit": limit,
})
return [_prestashop_with_status(store, order) for order in orders[:limit]]
def prestashop_get_order(context, order_number):
"""The PrestaShop order with this ID or reference, or None."""
store = _prestashop_store(context)
number = re.sub(r"\s+", "", str(order_number)).lstrip("#")
if not number:
return None
# Customers quote either the internal ID or the printed reference.
orders = _prestashop_orders(store, "id", number, 1) if number.isdigit() else []
orders = orders or _prestashop_orders(store, "reference", number, 1)
return orders[0] if orders else None
def prestashop_find_orders(context, email, limit=10):
"""The customer's PrestaShop orders by account email, newest first."""
store = _prestashop_store(context)
customers = _prestashop_get(store, "customers", {"filter[email]": email.strip(), "display": "[id]"})
if not customers:
return []
return _prestashop_orders(store, "id_customer", customers[0]["id"], limit)
def _prestashop_widget_order(order):
return {
"id": order.get("id"), "number": order.get("reference"), "status": order.get("status"),
"total": order.get("total_paid_tax_incl"), "placed_at": order.get("date_add"),
"products": [{"name": p.get("product_name"), "quantity": p.get("product_quantity"), "sku": p.get("product_reference")}
for p in (order.get("associations") or {}).get("order_rows") or []],
"shipments": [{"tracking_number": order["shipping_number"]}] if order.get("shipping_number") else [],
}
def prestashop_order_widget(context):
"""Read-only sidebar orders from the saved order ID and customer's email.
The raw order has only a currency ID, so no currency code is invented.
"""
return order_widget(context, get_order=prestashop_get_order, find_orders=prestashop_find_orders, map_order=_prestashop_widget_order)