Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): map commerce messages the same way on history sync

Yudhi Armyndharis323225a4855b
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 2fc5dcfc7..0a0f2fb60 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1301,7 +1301,7 @@ Returns a bare array of engine-neutral `IncomingMessage` objects:
]
```
-Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `ephemeralDuration` (the chat's disappearing-messages timer in seconds, present only when one is set), `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, `call { video, missed }` (for `call` messages), `location { latitude, longitude, description?, address?, url? }`, `order { orderId, token? }` (for `order` messages) and `product { productId, title?, description?, businessOwnerJid? }` (for `product` messages). `senderPhone` is **not** among them: this endpoint reads live from the engine and performs no privacy-id resolution, which runs only on the inbound `message.received` path (§6.6). To map an `@lid` sender seen here, call `GET /api/sessions/:sessionId/contacts/:contactId/phone`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|poll|call|revoked|order|product|masked|unknown`. An `order` is a cart the customer placed from the business catalog and a `product` is a single catalog product shared into the chat. Both engines populate the ids. The message carries no line items and this API exposes no order lookup, so `orderId` plus the single-order `token` are a correlation handle you redeem elsewhere rather than something the catalog routes resolve; `productId` resolves through `GET /api/sessions/:sessionId/catalog/products/:productId` only when the product came from the session's own catalog (`businessOwnerJid` says whose it is). Sharing a whole catalog rather than one product carries no product id and stays `unknown`. A `masked` message is one WhatsApp deliberately withholds from linked/companion devices — e.g. a high-security business OTP — so its `body` is empty by design (the content is only available on the primary phone) rather than a parsing failure; this occurs on the Baileys engine. `kind` is the user-facing chat discriminator of `chatId` — one of `individual|group|channel|status|broadcast|unknown`; it supersedes `isStatusBroadcast` (equivalent to `kind === 'status'`), which is retained for back-compat.
+Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `ephemeralDuration` (the chat's disappearing-messages timer in seconds, present only when one is set), `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, `call { video, missed }` (for `call` messages), `location { latitude, longitude, description?, address?, url? }`, `order { orderId, token? }` (for `order` messages) and `product { productId, title?, description?, businessOwnerJid? }` (for `product` messages). `senderPhone` is **not** among them: this endpoint reads live from the engine and performs no privacy-id resolution, which runs only on the inbound `message.received` path (§6.6). To map an `@lid` sender seen here, call `GET /api/sessions/:sessionId/contacts/:contactId/phone`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|poll|call|revoked|order|product|masked|unknown`. An `order` is a cart the customer placed from the business catalog and a `product` is a single catalog product shared into the chat. Only whatsapp-web.js serves this route (Baileys answers `501`), so every `order` and `product` block here comes from that engine. The message carries no line items and this API exposes no order lookup, so `orderId` plus the single-order `token` are a correlation handle you redeem elsewhere. The catalog routes answer `501` on whatsapp-web.js, so a `productId` read here does not resolve through them. whatsapp-web.js exposes no catalog field and cannot tell a share of a whole catalog from a product: a `product` message without a product id arrives with no `product` block. On Baileys the blocks arrive on `message.received`, where `GET /api/sessions/:sessionId/catalog/products/:productId` resolves a `productId` only when the product came from the session's own catalog (`businessOwnerJid` says whose it is), and a share of a whole catalog is typed `unknown`, both live and in the rows history sync stores. A `masked` message is one WhatsApp deliberately withholds from linked/companion devices — e.g. a high-security business OTP — so its `body` is empty by design (the content is only available on the primary phone) rather than a parsing failure; this occurs on the Baileys engine. `kind` is the user-facing chat discriminator of `chatId` — one of `individual|group|channel|status|broadcast|unknown`; it supersedes `isStatusBroadcast` (equivalent to `kind === 'status'`), which is retained for back-compat.
**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` the whatsapp-web.js page died mid-read (retryable)
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index 12ac441d3..8b5321ebb 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -1,7 +1,12 @@
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { Chat, Contact as BaileysContact, WAMessage, WASocket } from '@whiskeysockets/baileys';
import { EngineEventCallbacks, IncomingMessage } from '../interfaces/whatsapp-engine.interface';
-import { buildIncomingMessageFromBaileys, extractBaileysBody } from './baileys-message-mapper';
+import {
+ buildIncomingMessageFromBaileys,
+ extractBaileysBody,
+ extractBaileysCommerce,
+ isBaileysCatalogShare,
+} from './baileys-message-mapper';
import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';
import { type createLogger } from '../../common/services/logger.service';
@@ -144,6 +149,7 @@ export class BaileysHistory {
return null;
}
const body = extractBaileysBody(content);
+ const commerce = extractBaileysCommerce(content, contentType);
return buildIncomingMessageFromBaileys(
{
id: msg.key.id,
@@ -156,6 +162,10 @@ export class BaileysHistory {
timestamp: toUnixSeconds(msg.messageTimestamp),
pushName: msg.pushName ?? undefined,
selfJid: this.host.normalizedSelfJid(),
+ // Same commerce mapping as the live path, so a whole-catalog share is `unknown` on both.
+ order: commerce.order,
+ product: commerce.product,
+ isCatalogShare: isBaileysCatalogShare(content),
// Populate the disappearing-messages timer using the same extraction the live path and the
// session-store cache share (`msg.ephemeralDuration` primary, `contextInfo.expiration` fallback),
// so the history sink can apply the STORE_EPHEMERAL_MESSAGES opt-out symmetrically with onMessage.
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index fed98c772..ff1e79882 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -144,6 +144,7 @@ import {
EngineEventCallbacks,
GroupEvent,
IncomingCallEvent,
+ IncomingMessage,
} from '../interfaces/whatsapp-engine.interface';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
@@ -1835,6 +1836,74 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(mapped[0]).toMatchObject({ id: 'H1', type: 'text', body: 'disappearing hello' });
});
+ describe('commerce messages map the same way on the live and history paths', () => {
+ // An order in a disappearing chat, a shared product card, and a share of the whole catalog (the
+ // `catalog` arm of productMessage, with no product id).
+ const commerceMessages = [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'ORDER_MSG' },
+ message: { ephemeralMessage: { message: { orderMessage: { orderId: 'ORDER1', token: 'TOKEN1' } } } },
+ messageTimestamp: 1700000050,
+ },
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'PRODUCT_MSG' },
+ message: {
+ productMessage: {
+ product: { productId: 'PROD1', title: 'Sample' },
+ businessOwnerJid: '[email protected]',
+ },
+ },
+ messageTimestamp: 1700000051,
+ },
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'CATALOG_MSG' },
+ message: { productMessage: { catalog: { title: 'Store' }, businessOwnerJid: '[email protected]' } },
+ messageTimestamp: 1700000052,
+ },
+ ];
+
+ beforeEach(() => {
+ baileys.getContentType.mockImplementation(realGetContentType);
+ // Baileys unwraps ephemeralMessage (among other wrappers) to the inner message.
+ baileys.normalizeMessageContent.mockImplementation(
+ (m?: { ephemeralMessage?: { message?: unknown } }) => m?.ephemeralMessage?.message ?? m,
+ );
+ });
+
+ const expectCommerce = (mapped: IncomingMessage[]): void => {
+ const byId = new Map(mapped.map(m => [m.id, m]));
+ expect(byId.get('ORDER_MSG')).toMatchObject({ type: 'order', order: { orderId: 'ORDER1', token: 'TOKEN1' } });
+ expect(byId.get('PRODUCT_MSG')).toMatchObject({
+ type: 'product',
+ product: { productId: 'PROD1', title: 'Sample', businessOwnerJid: '[email protected]' },
+ });
+ expect(byId.get('CATALOG_MSG')).toMatchObject({ type: 'unknown', body: 'Store' });
+ expect(byId.get('CATALOG_MSG')?.product).toBeUndefined();
+ };
+
+ it('live: carries the order and product ids and types a catalog share as unknown', async () => {
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', { type: 'notify', messages: commerceMessages });
+ await new Promise(r => setImmediate(r));
+ await new Promise(r => setImmediate(r));
+ expect(onMessage).toHaveBeenCalledTimes(3);
+ expectCommerce((onMessage.mock.calls as Array<[IncomingMessage]>).map(([m]) => m));
+ });
+
+ it('history sync: carries the order and product ids and types a catalog share as unknown', async () => {
+ const onHistoryMessages = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onHistoryMessages });
+ fakeSock.fire('messaging-history.set', { contacts: [], chats: [], messages: commerceMessages });
+ await new Promise(r => setImmediate(r));
+ await new Promise(r => setImmediate(r));
+ expect(onHistoryMessages).toHaveBeenCalledTimes(1);
+ expectCommerce((onHistoryMessages.mock.calls as Array<[IncomingMessage[]]>)[0][0]);
+ });
+ });
+
it('surfaces inbound @mentions as neutral mentionedIds (contextInfo.mentionedJid)', async () => {
const onMessage = jest.fn();
const adapter = newAdapter();
diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.ts
index 61e306c62..9d6ffb44e 100644
--- a/src/engine/adapters/message-mapper.spec.ts
+++ b/src/engine/adapters/message-mapper.spec.ts
@@ -157,7 +157,10 @@ describe('buildIncomingMessageBase', () => {
it('yields nothing when the id that makes the message actionable is missing', () => {
expect(buildIncomingMessageBase({ ...base, type: 'order', token: 'tok' }).order).toBeUndefined();
- expect(buildIncomingMessageBase({ ...base, type: 'product', title: 'Sample' }).product).toBeUndefined();
+ // whatsapp-web.js exposes no catalog field, so an id-less product (a whole-catalog share included) keeps its type.
+ const product = buildIncomingMessageBase({ ...base, type: 'product', title: 'Sample' });
+ expect(product.type).toBe('product');
+ expect(product.product).toBeUndefined();
});
it('does not fabricate a product from a title on a non-commerce message', () => {