Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(whatsapp): 19 new actions, 4 webhook triggers, output schemas and Graph v23.0 (#15585)

Odai Ahmad62497757658d
diff --git a/brain/knowledge/connections-auth/app-connections.md b/brain/knowledge/connections-auth/app-connections.md
index 8c3af0820df..ac051b335e6 100644
--- a/brain/knowledge/connections-auth/app-connections.md
+++ b/brain/knowledge/connections-auth/app-connections.md
@@ -43,3 +43,7 @@ Entry point: `appConnectionService`, exported from the app-connection service an
- `packages/web/src/app/routes/platform/setup/connections/` — platform-wide global connections page
Paths verified 2026-07-17.
+
+## Gotchas
+
+- **`needRefresh` looks the piece up by `connection.pieceVersion`, so a CUSTOM_AUTH connection whose stored version is no longer served fails as `ConnectionNotFound`, not as a version error.** Any 404 from `GET /v1/worker/app-connections/:externalId` is mapped by the engine to "connection not found", which points debugging at credentials. On a dev instance this happens the moment a dev piece's version is bumped; in production it would need a published version to disappear from the registry. The lookup result is cached per piece version in `pieceRefreshSupportCache`.
diff --git a/brain/knowledge/pieces-engine/building-pieces.md b/brain/knowledge/pieces-engine/building-pieces.md
index bf63daa45b0..2a1490a8736 100644
--- a/brain/knowledge/pieces-engine/building-pieces.md
+++ b/brain/knowledge/pieces-engine/building-pieces.md
@@ -45,6 +45,10 @@ Authentication, triggers (polling/webhook), properties + validation, flow contro
- **`formatPieceError` runs *inside* the engine's error handler, so anything it throws replaces a real user error with an engine crash.** Two inputs used to do exactly that, both verified: a **cyclic** error body blew `collectMessage`'s recursion with `RangeError: Maximum call stack size exceeded` (a cycle through any of `message`/`detail`/`description`/`reason`/`error`, or a self-referencing array — and a 100-wide cycle made it exponential), and a cyclic `responseBody`/`requestBody` survived extraction only to die at the `JSON.stringify(formatPieceError(...))` every call site wraps it in, with `TypeError: Converting circular structure to JSON`. The second needs no deep cycle at all — a `self` key the extractor never walks is enough. Where that lands is the nasty part: `operations/index.ts` is the outermost handler, so a throw there escapes with no response and the worker just sees an RPC timeout. Both are now bounded — `collectMessageFrom` and `rebuildSerializable` each carry a depth cap plus a visited `WeakSet`. **Sanitize by probing with `JSON.stringify`, never by hand-rolling a walk over every body.** The first attempt here deep-copied unconditionally and silently downgraded exactly the values `JSON.stringify` gets right: `Date` became `{}` instead of an ISO string, `Buffer` became `{"0":104}` instead of `{type,data}`, a custom `toJSON` was ignored, and an own `function` property was promoted to **its source text** where stringify had correctly dropped it. `toSerializable` now tries `JSON.stringify` first and returns the original reference **untouched** when it succeeds, so the common path is byte-identical and uncopied; only a value that actually throws gets the bounded rebuild (cycles become `[Circular]`), and that rebuild is itself wrapped in a `tryCatchSync` that falls back to `[Unserializable]`, because `Object.entries` runs getters and a body with a throwing getter would otherwise escape the guard entirely. Worth knowing that `formatPieceError` output shares references with the caller's error object, and that `ai-provider-health.ts` reads `responseBody` and stringifies it itself — so a copy there is not free. Two consequences to know: a **shared** (non-cyclic) reference is collected once rather than twice, which is free for `JSON.parse`-derived bodies since they never share refs but is a real fidelity loss for live SDK error objects; and the `isFriendlyPieceError` passthrough is *not* re-sanitized, on the contract that such a payload already came from a JSON string. Rule of thumb: this file may return a worse message, never throw.
+- **A vendor placeholder written as `{{1}}` in any prop never reaches `run()`.** The builder's expression engine evaluates every `{{…}}` in step input first, so WhatsApp-style template variables arrive as empty strings and the vendor rejects the request for a reason that looks unrelated (a body/example mismatch). There is no escape a user can type. Accept an alternate marker (`[[1]]`) in the prop, convert it in `run()` (`whatsappClient.normalizeTemplateComponents`), and say so in the prop description.
+- **`src/i18n/translation.json` is generated, not edited.** After adding actions, triggers or descriptions run `TS_NODE_TRANSPILE_ONLY=true npm run cli -- pieces generate-translation-file <folder>` and commit the result. Without the env var ts-node crashes on a TS2339 inside the CLI itself. It rebuilds the piece's `dist` as a side effect.
+- **Bumping a dev piece's version breaks its existing connections until you re-pin `dist/package.json`.** The server resolves piece metadata by the version stored on the connection, and a dev piece serves only the single version in `dist`, so the old version vanishes and every step reports `connection … not found` with a valid connection. Either pin `dist/package.json` back to the stored version after each rebuild, or recreate the connection.
+- **A provider-side webhook handshake only works against a published flow.** `GET /v1/webhooks/{flowId}` answers `404 {}` while the flow is a draft, and the `/draft` and `/test` variants answer `200 {}` without running `onHandshake`, so a provider that verifies the URL at registration time (Meta's `hub.challenge`) reports failure until the flow is published. Any trigger whose instructions show `{{webhookUrl}}` for manual registration must tell the user to publish first (confirmed 2026-09-16 on the WhatsApp triggers).
- **A piece's `build` compiles its `src/**/*.test.ts`, so a type error in a test breaks the piece build while `vitest` stays green.** `npm run build` is `tsc -p tsconfig.lib.json`, whose `include` is `src/**/*.ts` with no test exclusion, while vitest runs through esbuild and strips types without checking them. So a test that passes locally can still fail CI at `<piece>#build`, and it takes `validate-publishable-packages` down with it. Run the piece's own `npm run build`, not just its tests, after adding one. Two shapes that bite: `ServerContext` (`{apiUrl, publicUrl, token}`) and `AuthValidationServerContext` (the same minus `token`, plus `mintOidcToken`) are not interchangeable, and `StaticPropsValue` requires *every* prop key to be present, including optional ones — pass `sessionToken: undefined` rather than omitting it.
## Sharing & misc
diff --git a/bun.lock b/bun.lock
index 381f07e71f4..3cb5c64a60e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9809,7 +9809,7 @@
},
"packages/pieces/community/whatsapp": {
"name": "@activepieces/piece-whatsapp",
- "version": "0.3.0",
+ "version": "1.0.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -9818,6 +9818,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/whatsscale": {
diff --git a/docs/install/reference/breaking-changes.mdx b/docs/install/reference/breaking-changes.mdx
index 1170d8bb627..976ecd85ce2 100644
--- a/docs/install/reference/breaking-changes.mdx
+++ b/docs/install/reference/breaking-changes.mdx
@@ -89,6 +89,28 @@ Clearing a description from this action is therefore no longer possible; that is
Nothing unless a flow or an agent relied on a blank description to clear a board's description, which previously happened on every run whether or not it was intended. Clear it from Pinterest directly.
+#### WhatsApp Business' Send Message and Send Media return the API response instead of the HTTP envelope
+
+The WhatsApp Business piece returned two different shapes depending on which action you used. `Send Template Message` returned the WhatsApp Cloud API payload directly, while `Send Message` and `Send Media` returned the whole HTTP response, so the same payload sat one level down under `body`, alongside `status` and `headers`.
+
+Both actions now return the API payload directly, matching `Send Template Message` and every other action in the piece. A step that produced
+
+```json
+{ "status": 200, "headers": { }, "body": { "messaging_product": "whatsapp", "messages": [{ "id": "wamid.…" }] } }
+```
+
+now produces
+
+```json
+{ "messaging_product": "whatsapp", "contacts": [{ "input": "…", "wa_id": "…" }], "messages": [{ "id": "wamid.…" }] }
+```
+
+The whole piece also moves to Graph API `v23.0`, via a single `WHATSAPP_API_BASE` constant. It previously split between `v17.0` (expired September 2025) and `v20.0` (expires 24 September 2026).
+
+#### What you need to do
+
+Update any step that reads the output of `Send Message` or `Send Media`. Drop the `body.` prefix: `{{step.body.messages[0].id}}` becomes `{{step.messages[0].id}}`. Steps that only send and ignore the output need no change, and no connection has to be re-authorised.
+
## 0.91.0
### What has changed?
diff --git a/packages/pieces/community/whatsapp/package.json b/packages/pieces/community/whatsapp/package.json
index df9c286165a..6559f71da61 100644
--- a/packages/pieces/community/whatsapp/package.json
+++ b/packages/pieces/community/whatsapp/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-whatsapp",
- "version": "0.3.0",
+ "version": "1.0.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
@@ -15,6 +16,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/whatsapp/src/i18n/translation.json b/packages/pieces/community/whatsapp/src/i18n/translation.json
index babe3debfd8..9ff2439ee32 100644
--- a/packages/pieces/community/whatsapp/src/i18n/translation.json
+++ b/packages/pieces/community/whatsapp/src/i18n/translation.json
@@ -1,31 +1,227 @@
{
- "Manage your WhatsApp business account": "Manage your WhatsApp business account",
+ "Send text, media and template messages from your WhatsApp Business number.": "Send text, media and template messages from your WhatsApp Business number.",
"System User Access Token": "System User Access Token",
"Business Account ID": "Business Account ID",
- "The system user access token of your WhatsApp business account.": "The system user access token of your WhatsApp business account.",
- "The business account ID of your WhatsApp business account.": "The business account ID of your WhatsApp business account.",
- "\nTo Obtain a Phone Number ID and a Permanent System User Access Token, follow these steps:\n\n1. Go to https://developers.facebook.com/\n2. Make a new app, Select Other for usecase.\n3. Choose Business as the type of app.\n4. Add new Product -> WhatsApp.\n5. Navigate to WhatsApp Settings > API Setup.\n6. Copy the Business Account ID.\n7. Login to your [Meta Business Manager](https://business.facebook.com/).\n8. Click on Settings.\n9. Create a new System User with access over the app and copy the access token.\n": "\nTo Obtain a Phone Number ID and a Permanent System User Access Token, follow these steps:\n\n1. Go to https://developers.facebook.com/\n2. Make a new app, Select Other for usecase.\n3. Choose Business as the type of app.\n4. Add new Product -> WhatsApp.\n5. Navigate to WhatsApp Settings > API Setup.\n6. Copy the Business Account ID.\n7. Login to your [Meta Business Manager](https://business.facebook.com/).\n8. Click on Settings.\n9. Create a new System User with access over the app and copy the access token.\n",
+ "App Secret": "App Secret",
+ "Permanent token of a System User with access to the app.": "Permanent token of a System User with access to the app.",
+ "Found under WhatsApp > API Setup in your Meta app.": "Found under WhatsApp > API Setup in your Meta app.",
+ "Optional. Your Meta app secret (App settings > Basic). When set, every webhook delivery must carry a valid X-Hub-Signature-256 or it is ignored.": "Optional. Your Meta app secret (App settings > Basic). When set, every webhook delivery must carry a valid X-Hub-Signature-256 or it is ignored.",
+ "\nYou need the WhatsApp Business Account ID and a permanent System User access token from Meta.\n\n1. Open [Meta for Developers](https://developers.facebook.com/) and create a **Business** app (use case **Other**).\n2. Add the **WhatsApp** product to the app.\n3. Go to **WhatsApp > API Setup** and copy the **WhatsApp Business Account ID**.\n4. In [Meta Business Manager](https://business.facebook.com/) open **Settings > System Users**, add a system user with access to the app, and generate a permanent token with t": "\nYou need the WhatsApp Business Account ID and a permanent System User access token from Meta.\n\n1. Open [Meta for Developers](https://developers.facebook.com/) and create a **Business** app (use case **Other**).\n2. Add the **WhatsApp** product to the app.\n3. Go to **WhatsApp > API Setup** and copy the **WhatsApp Business Account ID**.\n4. In [Meta Business Manager](https://business.facebook.com/) open **Settings > System Users**, add a system user with access to the app, and generate a permanent token with the **whatsapp_business_messaging** and **whatsapp_business_management** permissions.\n\nOptional: to have Activepieces verify that webhook deliveries really come from Meta, also paste your **App Secret** (App settings > Basic > App Secret). Triggers then reject any request that is not signed with it.\n",
"Send Message": "Send Message",
"Send Media": "Send Media",
"Send Template Message": "Send Template Message",
+ "Send Template": "Send Template",
+ "Send Interactive Buttons": "Send Interactive Buttons",
+ "Send Interactive List": "Send Interactive List",
+ "Send Interactive CTA URL": "Send Interactive CTA URL",
+ "Send Location": "Send Location",
+ "Send Contact": "Send Contact",
+ "Send Reaction": "Send Reaction",
+ "Mark Message As Read": "Mark Message As Read",
+ "Upload Media": "Upload Media",
+ "Get Media URL": "Get Media URL",
+ "Download Media": "Download Media",
+ "Delete Media": "Delete Media",
+ "List Message Templates": "List Message Templates",
+ "Create Message Template": "Create Message Template",
+ "Edit Message Template": "Edit Message Template",
+ "Delete Message Template": "Delete Message Template",
+ "List Phone Numbers": "List Phone Numbers",
+ "Get Phone Number": "Get Phone Number",
+ "Get Business Profile": "Get Business Profile",
+ "Update Business Profile": "Update Business Profile",
"Send a text message through WhatsApp": "Send a text message through WhatsApp",
- "Send a media message through WhatsApp": "Send a media message through WhatsApp",
- "Sends a template message.": "Sends a template message.",
- "Phone Number ID": "Phone Number ID",
+ "Send an image, video, audio, document or sticker by URL.": "Send an image, video, audio, document or sticker by URL.",
+ "Send an approved template, filling in its placeholders.": "Send an approved template, filling in its placeholders.",
+ "Sends an approved template by name with positional parameters.": "Sends an approved template by name with positional parameters.",
+ "Sends a message with up to three quick-reply buttons.": "Sends a message with up to three quick-reply buttons.",
+ "Sends a message that opens a menu of up to ten selectable rows.": "Sends a message that opens a menu of up to ten selectable rows.",
+ "Sends a message with a single button that opens a web link.": "Sends a message with a single button that opens a web link.",
+ "Sends a map pin for a latitude and longitude.": "Sends a map pin for a latitude and longitude.",
+ "Sends a contact card the recipient can save.": "Sends a contact card the recipient can save.",
+ "Reacts to a message with an emoji, or removes an existing reaction.": "Reacts to a message with an emoji, or removes an existing reaction.",
+ "Shows the sender blue ticks for a received message, optionally with a typing indicator.": "Shows the sender blue ticks for a received message, optionally with a typing indicator.",
+ "Uploads a file to WhatsApp and returns a media ID you can send.": "Uploads a file to WhatsApp and returns a media ID you can send.",
+ "Looks up a media ID and returns its download URL and metadata.": "Looks up a media ID and returns its download URL and metadata.",
+ "Downloads a received media file so later steps can use it.": "Downloads a received media file so later steps can use it.",
+ "Deletes an uploaded media file from WhatsApp.": "Deletes an uploaded media file from WhatsApp.",
+ "Lists the message templates on the business account, optionally filtered by status.": "Lists the message templates on the business account, optionally filtered by status.",
+ "Submits a new message template for Meta review.": "Submits a new message template for Meta review.",
+ "Replaces the components of an existing template and resubmits it for review.": "Replaces the components of an existing template and resubmits it for review.",
+ "Deletes a message template from the business account.": "Deletes a message template from the business account.",
+ "Lists the phone numbers registered on the business account.": "Lists the phone numbers registered on the business account.",
+ "Returns the details and health of one business phone number.": "Returns the details and health of one business phone number.",
+ "Returns the public business profile shown for a phone number.": "Returns the public business profile shown for a phone number.",
+ "Updates the public business profile for a phone number. Empty fields are left unchanged.": "Updates the public business profile for a phone number. Empty fields are left unchanged.",
+ "From Phone Number": "From Phone Number",
"To": "To",
"Message": "Message",
- "Type": "Type",
+ "Media Type": "Media Type",
"Media URL": "Media URL",
"Caption": "Caption",
"Filename": "Filename",
- "Message Template ID": "Message Template ID",
+ "Template": "Template",
"Template Fields": "Template Fields",
- "Phone number ID that will be used to send the message.": "Phone number ID that will be used to send the message.",
- "The recipient of the message": "The recipient of the message",
- "The message to send": "The message to send",
- "The type of media to send": "The type of media to send",
- "The URL of the media to send": "The URL of the media to send",
- "A caption for the media": "A caption for the media",
- "Filename of the document to send": "Filename of the document to send",
- "Recipient phone number.": "Recipient phone number."
+ "Template Name": "Template Name",
+ "Language Code": "Language Code",
+ "Body Parameters": "Body Parameters",
+ "Header Parameters": "Header Parameters",
+ "Button URL Parameters": "Button URL Parameters",
+ "Reply To Message ID": "Reply To Message ID",
+ "Body": "Body",
+ "Buttons": "Buttons",
+ "Header Type": "Header Type",
+ "Header Text": "Header Text",
+ "Header Media URL": "Header Media URL",
+ "Footer": "Footer",
+ "Button Text": "Button Text",
+ "Section Title": "Section Title",
+ "Rows": "Rows",
+ "Button URL": "Button URL",
+ "Latitude": "Latitude",
+ "Longitude": "Longitude",
+ "Location Name": "Location Name",
+ "Address": "Address",
+ "Full Name": "Full Name",
+ "First Name": "First Name",
+ "Last Name": "Last Name",
+ "Phone Numbers": "Phone Numbers",
+ "Emails": "Emails",
+ "Company": "Company",
+ "Job Title": "Job Title",
+ "Website": "Website",
+ "Message ID": "Message ID",
+ "Emoji": "Emoji",
+ "Show Typing Indicator": "Show Typing Indicator",
+ "File": "File",
+ "File Type": "File Type",
+ "Media ID": "Media ID",
+ "Status": "Status",
+ "Limit": "Limit",
+ "Name": "Name",
+ "Language": "Language",
+ "Category": "Category",
+ "Components": "Components",
+ "About": "About",
+ "Description": "Description",
+ "Email": "Email",
+ "Websites": "Websites",
+ "Vertical": "Vertical",
+ "The business number the message is sent from.": "The business number the message is sent from.",
+ "Recipient's phone number in international format.": "Recipient's phone number in international format.",
+ "Plain text, up to 4096 characters.": "Plain text, up to 4096 characters.",
+ "What kind of file the URL points to.": "What kind of file the URL points to.",
+ "Public link WhatsApp downloads when it sends the message.": "Public link WhatsApp downloads when it sends the message.",
+ "Text shown under the media. Ignored for audio and stickers.": "Text shown under the media. Ignored for audio and stickers.",
+ "Documents only: the file name the recipient sees.": "Documents only: the file name the recipient sees.",
+ "Only templates approved by WhatsApp are delivered.": "Only templates approved by WhatsApp are delivered.",
+ "Fill in each placeholder of the selected template.": "Fill in each placeholder of the selected template.",
+ "Recipient phone number in international format, digits only (for example 962791234567).": "Recipient phone number in international format, digits only (for example 962791234567).",
+ "Exact template name, for example hello_world. Get it from List Message Templates.": "Exact template name, for example hello_world. Get it from List Message Templates.",
+ "Language and locale of the approved template, for example en_US.": "Language and locale of the approved template, for example en_US.",
+ "Values for the body placeholders, in order: the first entry fills {{1}}, the second {{2}}.": "Values for the body placeholders, in order: the first entry fills {{1}}, the second {{2}}.",
+ "Values for text header placeholders, in order.": "Values for text header placeholders, in order.",
+ "Values for the dynamic URL suffix of the first URL button, in order.": "Values for the dynamic URL suffix of the first URL button, in order.",
+ "Optional WhatsApp message ID (wamid) to send this message as a reply to.": "Optional WhatsApp message ID (wamid) to send this message as a reply to.",
+ "Main message text.": "Main message text.",
+ "Between one and three buttons. Titles must be unique and at most 20 characters.": "Between one and three buttons. Titles must be unique and at most 20 characters.",
+ "Optional header shown above the body: a short text line or a media item from a public URL.": "Optional header shown above the body: a short text line or a media item from a public URL.",
+ "Used when Header Type is Text. Max 60 characters.": "Used when Header Type is Text. Max 60 characters.",
+ "Public URL of the header image, video or document. Used when Header Type is a media type.": "Public URL of the header image, video or document. Used when Header Type is a media type.",
+ "Optional footer text, max 60 characters.": "Optional footer text, max 60 characters.",
+ "Label of the button that opens the list. Max 20 characters.": "Label of the button that opens the list. Max 20 characters.",
+ "Title shown above the rows. Max 24 characters.": "Title shown above the rows. Max 24 characters.",
+ "Between one and ten rows. Titles max 24 characters, descriptions max 72.": "Between one and ten rows. Titles max 24 characters, descriptions max 72.",
+ "Label of the button. Max 20 characters.": "Label of the button. Max 20 characters.",
+ "The link the button opens.": "The link the button opens.",
+ "Decimal degrees, for example 31.9539.": "Decimal degrees, for example 31.9539.",
+ "Decimal degrees, for example 35.9106.": "Decimal degrees, for example 35.9106.",
+ "Title shown under the map pin, for example a venue or shop name.": "Title shown under the map pin, for example a venue or shop name.",
+ "Street address shown under the name. Only displayed when a name is also set.": "Street address shown under the name. Only displayed when a name is also set.",
+ "Display name shown on the card.": "Display name shown on the card.",
+ "One entry per number the recipient can call or message.": "One entry per number the recipient can call or message.",
+ "One entry per email address.": "One entry per email address.",
+ "The WhatsApp message ID (wamid), for example from the New Incoming Message trigger.": "The WhatsApp message ID (wamid), for example from the New Incoming Message trigger.",
+ "A single emoji such as 👍. Leave empty to remove your reaction.": "A single emoji such as 👍. Leave empty to remove your reaction.",
+ "Display \"typing…\" to the sender until you reply or 25 seconds pass.": "Display \"typing…\" to the sender until you reply or 25 seconds pass.",
+ "The file to upload, from a previous step or a URL.": "The file to upload, from a previous step or a URL.",
+ "Must match the actual file contents; WhatsApp rejects mismatches.": "Must match the actual file contents; WhatsApp rejects mismatches.",
+ "The media ID returned by Upload Media or received on an incoming media message.": "The media ID returned by Upload Media or received on an incoming media message.",
+ "Only return templates in this review state. Leave empty for all.": "Only return templates in this review state. Leave empty for all.",
+ "Maximum number of templates to return. Defaults to 100.": "Maximum number of templates to return. Defaults to 100.",
+ "Lowercase letters, digits and underscores only, for example order_update.": "Lowercase letters, digits and underscores only, for example order_update.",
+ "Language and locale code, for example en_US.": "Language and locale code, for example en_US.",
+ "Meta reviews and prices the template by category. Utility for transactional updates, Marketing for promotions, Authentication for one-time passcodes.": "Meta reviews and prices the template by category. Utility for transactional updates, Marketing for promotions, Authentication for one-time passcodes.",
+ "Template components array as documented by Meta. Write variables as [[1]] or [[name]] instead of double curly braces, which Activepieces reserves for its own expressions; they are converted before sending. Example: [{\"type\":\"BODY\",\"text\":\"Hello [[1]]\",\"example\":{\"body_text\":[[\"Sam\"]]}}].": "Template components array as documented by Meta. Write variables as [[1]] or [[name]] instead of double curly braces, which Activepieces reserves for its own expressions; they are converted before sending. Example: [{\"type\":\"BODY\",\"text\":\"Hello [[1]]\",\"example\":{\"body_text\":[[\"Sam\"]]}}].",
+ "Leave empty to keep the current category.": "Leave empty to keep the current category.",
+ "Short status line, max 139 characters.": "Short status line, max 139 characters.",
+ "Up to two URLs.": "Up to two URLs.",
+ "Industry shown on the business profile.": "Industry shown on the business profile.",
+ "None": "None",
+ "Text": "Text",
+ "Image": "Image",
+ "Video": "Video",
+ "Document": "Document",
+ "JPEG image": "JPEG image",
+ "PNG image": "PNG image",
+ "WebP sticker": "WebP sticker",
+ "MP4 video": "MP4 video",
+ "3GPP video": "3GPP video",
+ "AAC audio": "AAC audio",
+ "AMR audio": "AMR audio",
+ "MP3 audio": "MP3 audio",
+ "MP4 audio": "MP4 audio",
+ "OGG audio": "OGG audio",
+ "PDF document": "PDF document",
+ "Plain text": "Plain text",
+ "Word document": "Word document",
+ "Excel spreadsheet": "Excel spreadsheet",
+ "PowerPoint presentation": "PowerPoint presentation",
+ "Approved": "Approved",
+ "Pending": "Pending",
+ "Rejected": "Rejected",
+ "Paused": "Paused",
+ "Disabled": "Disabled",
+ "Marketing": "Marketing",
+ "Utility": "Utility",
+ "Authentication": "Authentication",
+ "OTHER": "OTHER",
+ "AUTO": "AUTO",
+ "BEAUTY": "BEAUTY",
+ "APPAREL": "APPAREL",
+ "EDU": "EDU",
+ "ENTERTAIN": "ENTERTAIN",
+ "EVENT_PLAN": "EVENT_PLAN",
+ "FINANCE": "FINANCE",
+ "GROCERY": "GROCERY",
+ "GOVT": "GOVT",
+ "HOTEL": "HOTEL",
+ "HEALTH": "HEALTH",
+ "NONPROFIT": "NONPROFIT",
+ "PROF_SERVICES": "PROF_SERVICES",
+ "RETAIL": "RETAIL",
+ "TRAVEL": "TRAVEL",
+ "RESTAURANT": "RESTAURANT",
+ "ALCOHOL": "ALCOHOL",
+ "ONLINE_GAMBLING": "ONLINE_GAMBLING",
+ "PHYSICAL_GAMBLING": "PHYSICAL_GAMBLING",
+ "OTC_DRUGS": "OTC_DRUGS",
+ "New Incoming Message": "New Incoming Message",
+ "New Message Reaction": "New Message Reaction",
+ "Message Status Updated": "Message Status Updated",
+ "Template Status Updated": "Template Status Updated",
+ "Fires when a customer sends your business number a message.": "Fires when a customer sends your business number a message.",
+ "Fires when a customer reacts to one of your messages with an emoji, or removes a reaction.": "Fires when a customer reacts to one of your messages with an emoji, or removes a reaction.",
+ "Fires when a message you sent is delivered, read, or fails.": "Fires when a message you sent is delivered, read, or fails.",
+ "Fires when Meta approves, rejects, pauses or otherwise changes a message template.": "Fires when Meta approves, rejects, pauses or otherwise changes a message template.",
+ "Markdown": "Markdown",
+ "Verify Token": "Verify Token",
+ "Statuses": "Statuses",
+ "\n**Connect this trigger to your Meta app**\n\n1. **Publish this flow first.** Meta verifies the URL immediately, and an unpublished flow cannot answer.\n2. Open [developers.facebook.com](https://developers.facebook.com/apps), pick your app and go to **WhatsApp → Configuration**.\n3. Under **Webhook**, click **Edit** and paste this URL as the Callback URL:\n\n `{{webhookUrl}}`\n\n4. Enter the same value you put in **Verify Token** below (any secret string), then click **Verify and save**.\n5. Click **Manage** next ": "\n**Connect this trigger to your Meta app**\n\n1. **Publish this flow first.** Meta verifies the URL immediately, and an unpublished flow cannot answer.\n2. Open [developers.facebook.com](https://developers.facebook.com/apps), pick your app and go to **WhatsApp → Configuration**.\n3. Under **Webhook**, click **Edit** and paste this URL as the Callback URL:\n\n `{{webhookUrl}}`\n\n4. Enter the same value you put in **Verify Token** below (any secret string), then click **Verify and save**.\n5. Click **Manage** next to Webhook fields and subscribe to **messages** (and **message_template_status_update** for template triggers).\n6. Make sure your app is subscribed to the WhatsApp Business Account itself. If events never arrive although the URL verified, call `POST /{WABA_ID}/subscribed_apps` with your access token; the dashboard does not show this state.\n\nTo reject deliveries that are not signed by Meta, add your **App Secret** to the WhatsApp connection.\n\nMeta accepts **one callback URL per app**, so only the flow whose URL you paste receives events. To react to several event kinds, use one flow with this trigger and branch on the payload, or forward the payload to your other flows from a step.\n",
+ "Optional. If set, Meta must send this exact token during webhook verification or the handshake is rejected.": "Optional. If set, Meta must send this exact token during webhook verification or the handshake is rejected.",
+ "Only fire for these statuses. Leave empty for all.": "Only fire for these statuses. Leave empty for all.",
+ "Sent": "Sent",
+ "Delivered": "Delivered",
+ "Read": "Read",
+ "Failed": "Failed"
}
\ No newline at end of file
diff --git a/packages/pieces/community/whatsapp/src/index.ts b/packages/pieces/community/whatsapp/src/index.ts
index 9cfa156a59a..27aa4c8cdc1 100644
--- a/packages/pieces/community/whatsapp/src/index.ts
+++ b/packages/pieces/community/whatsapp/src/index.ts
@@ -2,6 +2,30 @@ import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { sendMessage } from './lib/actions/send-message';
import { sendMedia } from './lib/actions/send-media';
import { sendTemplateMessageAction } from './lib/actions/send-from-template';
+import { sendTemplate } from './lib/actions/send-template';
+import { sendInteractiveButtons } from './lib/actions/send-interactive-buttons';
+import { sendInteractiveList } from './lib/actions/send-interactive-list';
+import { sendInteractiveCtaUrl } from './lib/actions/send-interactive-cta-url';
+import { sendLocation } from './lib/actions/send-location';
+import { sendContact } from './lib/actions/send-contact';
+import { sendReaction } from './lib/actions/send-reaction';
+import { markMessageAsRead } from './lib/actions/mark-message-as-read';
+import { uploadMedia } from './lib/actions/upload-media';
+import { getMediaUrl } from './lib/actions/get-media-url';
+import { downloadMedia } from './lib/actions/download-media';
+import { deleteMedia } from './lib/actions/delete-media';
+import { listMessageTemplates } from './lib/actions/list-message-templates';
+import { createMessageTemplate } from './lib/actions/create-message-template';
+import { editMessageTemplate } from './lib/actions/edit-message-template';
+import { deleteMessageTemplate } from './lib/actions/delete-message-template';
+import { listPhoneNumbers } from './lib/actions/list-phone-numbers';
+import { getPhoneNumber } from './lib/actions/get-phone-number';
+import { getBusinessProfile } from './lib/actions/get-business-profile';
+import { updateBusinessProfile } from './lib/actions/update-business-profile';
+import { newIncomingMessage } from './lib/triggers/new-incoming-message';
+import { newMessageReaction } from './lib/triggers/new-message-reaction';
+import { messageStatusUpdated } from './lib/triggers/message-status-updated';
+import { templateStatusUpdated } from './lib/triggers/template-status-updated';
import { whatsappAuth } from './lib/auth';
export const whatsapp = createPiece({
@@ -12,6 +36,30 @@ export const whatsapp = createPiece({
logoUrl: 'https://cdn.activepieces.com/pieces/whatsapp.png',
categories: [PieceCategory.COMMUNICATION],
authors: ['LevwTech', 'kishanprmr'],
- actions: [sendMessage, sendMedia, sendTemplateMessageAction],
- triggers: [],
+ actions: [
+ sendMessage,
+ sendMedia,
+ sendTemplateMessageAction,
+ sendTemplate,
+ sendInteractiveButtons,
+ sendInteractiveList,
+ sendInteractiveCtaUrl,
+ sendLocation,
+ sendContact,
+ sendReaction,
+ markMessageAsRead,
+ uploadMedia,
+ getMediaUrl,
+ downloadMedia,
+ deleteMedia,
+ listMessageTemplates,
+ createMessageTemplate,
+ editMessageTemplate,
+ deleteMessageTemplate,
+ listPhoneNumbers,
+ getPhoneNumber,
+ getBusinessProfile,
+ updateBusinessProfile,
+ ],
+ triggers: [newIncomingMessage, newMessageReaction, messageStatusUpdated, templateStatusUpdated],
});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/create-message-template.ts b/packages/pieces/community/whatsapp/src/lib/actions/create-message-template.ts
new file mode 100644
index 00000000000..a887310d315
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/create-message-template.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { createMessageTemplateOutputSchema } from '../output-schemas';
+
+export const createMessageTemplate = createAction({
+ auth: whatsappAuth,
+ name: 'create_message_template',
+ outputSchema: createMessageTemplateOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Create Message Template',
+ description: 'Submits a new message template for Meta review.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a WhatsApp message template on the business account and submits it for Meta approval; it returns the new template id and a PENDING status, and Template Status Updated fires when review completes. Names must be lowercase letters, digits and underscores, unique per language. Not idempotent — a duplicate name for the same language is rejected rather than reused.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({
+ displayName: 'Name',
+ description: 'Lowercase letters, digits and underscores only, for example order_update.',
+ required: true,
+ }),
+ language: Property.ShortText({
+ displayName: 'Language',
+ description: 'Language and locale code, for example en_US.',
+ required: true,
+ }),
+ category: whatsappProps.templateCategory,
+ components: whatsappProps.templateComponents,
+ },
+ async run(context) {
+ const { name, language, category, components } = context.propsValue;
+ return whatsappClient.request<{ id: string; status: string; category: string }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.POST,
+ path: `/${context.auth.props.businessAccountId}/message_templates`,
+ body: { name, language, category, components: whatsappClient.normalizeTemplateComponents(components) },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/delete-media.ts b/packages/pieces/community/whatsapp/src/lib/actions/delete-media.ts
new file mode 100644
index 00000000000..69feb74f06a
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/delete-media.ts
@@ -0,0 +1,31 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { deleteMediaOutputSchema } from '../output-schemas';
+
+export const deleteMedia = createAction({
+ auth: whatsappAuth,
+ name: 'delete_media',
+ outputSchema: deleteMediaOutputSchema,
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Media',
+ description: 'Deletes an uploaded media file from WhatsApp.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a media file previously stored on WhatsApp by its media ID, so it can no longer be sent or downloaded. Use it to clean up after Upload Media; messages already delivered are unaffected. Not idempotent — a second call for the same ID fails because the media no longer exists.',
+ idempotent: false,
+ },
+ props: {
+ media_id: whatsappProps.mediaId,
+ },
+ async run(context) {
+ return whatsappClient.request<{ success: boolean }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.DELETE,
+ path: `/${context.propsValue.media_id}`,
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/delete-message-template.ts b/packages/pieces/community/whatsapp/src/lib/actions/delete-message-template.ts
new file mode 100644
index 00000000000..d40df4c3cc6
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/delete-message-template.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappClient } from '../common/client';
+import { deleteMessageTemplateOutputSchema } from '../output-schemas';
+
+export const deleteMessageTemplate = createAction({
+ auth: whatsappAuth,
+ name: 'delete_message_template',
+ outputSchema: deleteMessageTemplateOutputSchema,
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Message Template',
+ description: 'Deletes a message template from the business account.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Deletes one WhatsApp message template, selected by id, from the business account. Deleting an approved template blocks reuse of its name for 30 days, and templates with messages still in flight move to PENDING_DELETION first. Not idempotent — a second call for the same template fails because it no longer exists.',
+ idempotent: false,
+ },
+ props: {
+ message_template_id: commonProps.message_template_id,
+ },
+ async run(context) {
+ const accessToken = context.auth.props.access_token;
+ const templateId = context.propsValue.message_template_id;
+ const template = await whatsappClient.request<{ id: string; name: string }>({
+ accessToken,
+ method: HttpMethod.GET,
+ path: `/${templateId}`,
+ queryParams: { fields: 'id,name' },
+ });
+ return whatsappClient.request<{ success: boolean }>({
+ accessToken,
+ method: HttpMethod.DELETE,
+ path: `/${context.auth.props.businessAccountId}/message_templates`,
+ queryParams: { hsm_id: template.id, name: template.name },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/download-media.ts b/packages/pieces/community/whatsapp/src/lib/actions/download-media.ts
new file mode 100644
index 00000000000..8dbef1f46da
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/download-media.ts
@@ -0,0 +1,72 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { MediaInfo } from './get-media-url';
+import { downloadMediaOutputSchema } from '../output-schemas';
+
+export const downloadMedia = createAction({
+ auth: whatsappAuth,
+ name: 'download_media',
+ outputSchema: downloadMediaOutputSchema,
+ classification: 'READ',
+ displayName: 'Download Media',
+ description: 'Downloads a received media file so later steps can use it.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Downloads the file behind a WhatsApp media ID, typically one received on the New Incoming Message trigger, and returns it as a file plus its MIME type and size. Use this instead of Get Media URL when you need the content rather than a short-lived link. Idempotent — a pure read.',
+ idempotent: true,
+ },
+ props: {
+ media_id: whatsappProps.mediaId,
+ },
+ async run(context) {
+ const accessToken = context.auth.props.access_token;
+ const info = await whatsappClient.request<MediaInfo>({
+ accessToken,
+ method: HttpMethod.GET,
+ path: `/${context.propsValue.media_id}`,
+ });
+ const download = await httpClient.sendRequest({
+ method: HttpMethod.GET,
+ url: info.url,
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: accessToken,
+ },
+ responseType: 'stream',
+ });
+ const extension = mimeExtension(info.mime_type);
+ const fileName = `${info.id}${extension ? `.${extension}` : ''}`;
+ const file = await context.files.write({ fileName, data: download.body });
+ return {
+ file,
+ id: info.id,
+ mime_type: info.mime_type,
+ sha256: info.sha256,
+ file_size: info.file_size,
+ };
+ },
+});
+
+function mimeExtension(mimeType: string): string | undefined {
+ const subtype = mimeType.split('/')[1];
+ return MIME_EXTENSIONS[mimeType] ?? subtype;
+}
+
+const MIME_EXTENSIONS: Record<string, string> = {
+ 'image/jpeg': 'jpg',
+ 'audio/mpeg': 'mp3',
+ 'audio/mp4': 'm4a',
+ 'audio/ogg': 'ogg',
+ 'video/3gpp': '3gp',
+ 'text/plain': 'txt',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
+ 'application/msword': 'doc',
+ 'application/vnd.ms-excel': 'xls',
+ 'application/vnd.ms-powerpoint': 'ppt',
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/edit-message-template.ts b/packages/pieces/community/whatsapp/src/lib/actions/edit-message-template.ts
new file mode 100644
index 00000000000..97ba30bb7fd
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/edit-message-template.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { editMessageTemplateOutputSchema } from '../output-schemas';
+
+export const editMessageTemplate = createAction({
+ auth: whatsappAuth,
+ name: 'edit_message_template',
+ outputSchema: editMessageTemplateOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Edit Message Template',
+ description: 'Replaces the components of an existing template and resubmits it for review.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Edits an existing WhatsApp message template by replacing all of its components, optionally changing its category, and resubmits it for Meta review. Only APPROVED, REJECTED or PAUSED templates can be edited, and the whole components array is replaced rather than merged, so pass every component you want to keep. Idempotent — resending the same components converges on the same template.',
+ idempotent: true,
+ },
+ props: {
+ message_template_id: commonProps.message_template_id,
+ components: whatsappProps.templateComponents,
+ category: Property.StaticDropdown({
+ displayName: 'Category',
+ description: 'Leave empty to keep the current category.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Marketing', value: 'MARKETING' },
+ { label: 'Utility', value: 'UTILITY' },
+ { label: 'Authentication', value: 'AUTHENTICATION' },
+ ],
+ },
+ }),
+ },
+ async run(context) {
+ const { message_template_id, components, category } = context.propsValue;
+ return whatsappClient.request<{ success: boolean }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.POST,
+ path: `/${message_template_id}`,
+ body: {
+ components: whatsappClient.normalizeTemplateComponents(components),
+ ...(category ? { category } : {}),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/get-business-profile.ts b/packages/pieces/community/whatsapp/src/lib/actions/get-business-profile.ts
new file mode 100644
index 00000000000..30e47bbece3
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/get-business-profile.ts
@@ -0,0 +1,46 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappClient } from '../common/client';
+import { getBusinessProfileOutputSchema } from '../output-schemas';
+
+export const getBusinessProfile = createAction({
+ auth: whatsappAuth,
+ name: 'get_business_profile',
+ outputSchema: getBusinessProfileOutputSchema,
+ classification: 'READ',
+ displayName: 'Get Business Profile',
+ description: 'Returns the public business profile shown for a phone number.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the WhatsApp business profile attached to a phone number: about text, address, description, email, websites, vertical and profile picture URL. Use it to read the current values before Update Business Profile. Idempotent — a pure read.',
+ idempotent: true,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ },
+ async run(context) {
+ const response = await whatsappClient.request<{ data: BusinessProfile[] }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.GET,
+ path: `/${context.propsValue.phone_number_id}/whatsapp_business_profile`,
+ queryParams: {
+ fields: 'about,address,description,email,profile_picture_url,websites,vertical',
+ },
+ });
+ return response.data[0];
+ },
+});
+
+export type BusinessProfile = {
+ messaging_product: string;
+ about?: string;
+ address?: string;
+ description?: string;
+ email?: string;
+ profile_picture_url?: string;
+ websites?: string[];
+ vertical?: string;
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/get-media-url.ts b/packages/pieces/community/whatsapp/src/lib/actions/get-media-url.ts
new file mode 100644
index 00000000000..2100956aa77
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/get-media-url.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { getMediaUrlOutputSchema } from '../output-schemas';
+
+export const getMediaUrl = createAction({
+ auth: whatsappAuth,
+ name: 'get_media_url',
+ outputSchema: getMediaUrlOutputSchema,
+ classification: 'READ',
+ displayName: 'Get Media URL',
+ description: 'Looks up a media ID and returns its download URL and metadata.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Resolves a WhatsApp media ID to its temporary download URL, MIME type, size and SHA-256 hash. The URL expires after five minutes and needs the access token to fetch, so prefer Download Media when you want the file itself. Idempotent — a pure read.',
+ idempotent: true,
+ },
+ props: {
+ media_id: whatsappProps.mediaId,
+ },
+ async run(context) {
+ return whatsappClient.request<MediaInfo>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.GET,
+ path: `/${context.propsValue.media_id}`,
+ });
+ },
+});
+
+export type MediaInfo = {
+ messaging_product: string;
+ url: string;
+ mime_type: string;
+ sha256: string;
+ file_size: number;
+ id: string;
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/get-phone-number.ts b/packages/pieces/community/whatsapp/src/lib/actions/get-phone-number.ts
new file mode 100644
index 00000000000..efc06fa38da
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/get-phone-number.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappClient } from '../common/client';
+import { getPhoneNumberOutputSchema } from '../output-schemas';
+
+export const getPhoneNumber = createAction({
+ auth: whatsappAuth,
+ name: 'get_phone_number',
+ outputSchema: getPhoneNumberOutputSchema,
+ classification: 'READ',
+ displayName: 'Get Phone Number',
+ description: 'Returns the details and health of one business phone number.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns one WhatsApp business phone number with its verified name, quality rating, messaging throughput level, verification status and name status. Use it to check the sender health before a campaign; use List Phone Numbers to enumerate them. Idempotent — a pure read.',
+ idempotent: true,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ },
+ async run(context) {
+ return whatsappClient.request({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.GET,
+ path: `/${context.propsValue.phone_number_id}`,
+ queryParams: {
+ fields:
+ 'id,verified_name,display_phone_number,quality_rating,code_verification_status,name_status,status,throughput,platform_type',
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/list-message-templates.ts b/packages/pieces/community/whatsapp/src/lib/actions/list-message-templates.ts
new file mode 100644
index 00000000000..7f1d3400eb3
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/list-message-templates.ts
@@ -0,0 +1,69 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod, QueryParams } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { whatsappClient } from '../common/client';
+import { listMessageTemplatesOutputSchema } from '../output-schemas';
+
+export const listMessageTemplates = createAction({
+ auth: whatsappAuth,
+ name: 'list_message_templates',
+ outputSchema: listMessageTemplatesOutputSchema,
+ classification: 'SEARCH',
+ displayName: 'List Message Templates',
+ description: 'Lists the message templates on the business account, optionally filtered by status.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the message templates registered on the WhatsApp Business Account with their id, name, language, category, status and components. Use it to find a template id or check approval state before Send Template Message. Filter by status (APPROVED, PENDING, REJECTED, PAUSED, DISABLED) to narrow the result. Idempotent — a pure read.',
+ idempotent: true,
+ },
+ props: {
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ description: 'Only return templates in this review state. Leave empty for all.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Approved', value: 'APPROVED' },
+ { label: 'Pending', value: 'PENDING' },
+ { label: 'Rejected', value: 'REJECTED' },
+ { label: 'Paused', value: 'PAUSED' },
+ { label: 'Disabled', value: 'DISABLED' },
+ ],
+ },
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum number of templates to return. Defaults to 100.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { status, limit } = context.propsValue;
+ const queryParams: QueryParams = {
+ fields: 'id,name,language,category,status,components,quality_score',
+ limit: String(limit ?? 100),
+ };
+ if (status) queryParams['status'] = status;
+ const response = await whatsappClient.request<{ data: TemplateRecord[] }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.GET,
+ path: `/${context.auth.props.businessAccountId}/message_templates`,
+ queryParams,
+ });
+ return {
+ templates: response.data,
+ count: response.data.length,
+ };
+ },
+});
+
+type TemplateRecord = {
+ id: string;
+ name: string;
+ language: string;
+ category: string;
+ status: string;
+ components: unknown[];
+ quality_score?: { score: string };
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/list-phone-numbers.ts b/packages/pieces/community/whatsapp/src/lib/actions/list-phone-numbers.ts
new file mode 100644
index 00000000000..f0e9124cf72
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/list-phone-numbers.ts
@@ -0,0 +1,70 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { whatsappClient } from '../common/client';
+import { listPhoneNumbersOutputSchema } from '../output-schemas';
+
+export const listPhoneNumbers = createAction({
+ auth: whatsappAuth,
+ name: 'list_phone_numbers',
+ outputSchema: listPhoneNumbersOutputSchema,
+ classification: 'SEARCH',
+ displayName: 'List Phone Numbers',
+ description: 'Lists the phone numbers registered on the business account.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists every phone number on the WhatsApp Business Account with its id, verified display name, formatted number and quality rating. Use it to resolve the phone number id that every send action requires. Idempotent — a pure read.',
+ idempotent: true,
+ },
+ props: {},
+ async run(context) {
+ const phoneNumbers = await fetchAllPhoneNumbers({
+ accessToken: context.auth.props.access_token,
+ businessAccountId: context.auth.props.businessAccountId,
+ });
+ return {
+ phone_numbers: phoneNumbers,
+ count: phoneNumbers.length,
+ };
+ },
+});
+
+async function fetchAllPhoneNumbers({ accessToken, businessAccountId }: FetchAllParams): Promise<PhoneNumberRecord[]> {
+ const pages: PhoneNumberRecord[][] = [];
+ let after: string | undefined = undefined;
+ for (let page = 0; page < MAX_PAGES; page++) {
+ const response: PhoneNumbersPage = await whatsappClient.request<PhoneNumbersPage>({
+ accessToken,
+ method: HttpMethod.GET,
+ path: `/${businessAccountId}/phone_numbers`,
+ queryParams: {
+ fields: 'id,verified_name,display_phone_number,quality_rating,code_verification_status,platform_type',
+ limit: String(PAGE_SIZE),
+ ...(after ? { after } : {}),
+ },
+ });
+ pages.push(response.data);
+ after = response.paging?.next ? response.paging.cursors?.after : undefined;
+ if (!after) break;
+ }
+ return pages.flat();
+}
+
+const PAGE_SIZE = 100;
+const MAX_PAGES = 50;
+
+type FetchAllParams = { accessToken: string; businessAccountId: string };
+type PhoneNumbersPage = {
+ data: PhoneNumberRecord[];
+ paging?: { cursors?: { before?: string; after?: string }; next?: string };
+};
+
+type PhoneNumberRecord = {
+ id: string;
+ verified_name: string;
+ display_phone_number: string;
+ quality_rating: string;
+ code_verification_status?: string;
+ platform_type?: string;
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/mark-message-as-read.ts b/packages/pieces/community/whatsapp/src/lib/actions/mark-message-as-read.ts
new file mode 100644
index 00000000000..00917680e53
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/mark-message-as-read.ts
@@ -0,0 +1,46 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { markMessageAsReadOutputSchema } from '../output-schemas';
+
+export const markMessageAsRead = createAction({
+ auth: whatsappAuth,
+ name: 'mark_message_as_read',
+ outputSchema: markMessageAsReadOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Mark Message As Read',
+ description: 'Shows the sender blue ticks for a received message, optionally with a typing indicator.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Marks an incoming WhatsApp message as read so the sender sees blue ticks, and can show a typing indicator for up to 25 seconds while you prepare a reply. Use it right after the New Incoming Message trigger, before sending a response. Idempotent — marking an already-read message again is a no-op.',
+ idempotent: true,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ message_id: whatsappProps.messageId,
+ show_typing_indicator: Property.Checkbox({
+ displayName: 'Show Typing Indicator',
+ description: 'Display "typing…" to the sender until you reply or 25 seconds pass.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const { phone_number_id, message_id, show_typing_indicator } = context.propsValue;
+ return whatsappClient.request<{ success: boolean }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.POST,
+ path: `/${phone_number_id}/messages`,
+ body: {
+ messaging_product: 'whatsapp',
+ status: 'read',
+ message_id,
+ ...(show_typing_indicator ? { typing_indicator: { type: 'text' } } : {}),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-contact.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-contact.ts
new file mode 100644
index 00000000000..c75023dfdb6
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-contact.ts
@@ -0,0 +1,132 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { inputUtils } from '../common/inputs';
+import { messageSendOutputSchema } from '../output-schemas';
+
+export const sendContact = createAction({
+ auth: whatsappAuth,
+ name: 'send_contact',
+ outputSchema: messageSendOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Send Contact',
+ description: 'Sends a contact card the recipient can save.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a WhatsApp contact card with a name and optional phone numbers, emails, company and website that the recipient can save to their address book. Choose this over Send Message when sharing a person or business as a savable contact. Free-form, so it only delivers inside the 24-hour customer service window. Not idempotent — each call sends a new message.',
+ idempotent: false,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ to: whatsappProps.to,
+ formatted_name: Property.ShortText({
+ displayName: 'Full Name',
+ description: 'Display name shown on the card.',
+ required: true,
+ }),
+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),
+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),
+ phones: Property.Array({
+ displayName: 'Phone Numbers',
+ description: 'One entry per number the recipient can call or message.',
+ required: false,
+ properties: {
+ phone: Property.ShortText({
+ displayName: 'Phone',
+ description: 'Include the country code, for example +962791234567.',
+ required: true,
+ }),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ description: 'Label shown next to the number.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Cell', value: 'CELL' },
+ { label: 'Main', value: 'MAIN' },
+ { label: 'Work', value: 'WORK' },
+ { label: 'Home', value: 'HOME' },
+ { label: 'iPhone', value: 'IPHONE' },
+ ],
+ },
+ }),
+ },
+ }),
+ emails: Property.Array({
+ displayName: 'Emails',
+ description: 'One entry per email address.',
+ required: false,
+ properties: {
+ email: Property.ShortText({ displayName: 'Email', required: true }),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ description: 'Label shown next to the address.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Work', value: 'WORK' },
+ { label: 'Home', value: 'HOME' },
+ ],
+ },
+ }),
+ },
+ }),
+ company: Property.ShortText({ displayName: 'Company', required: false }),
+ job_title: Property.ShortText({ displayName: 'Job Title', required: false }),
+ website: Property.ShortText({ displayName: 'Website', required: false }),
+ reply_to_message_id: whatsappProps.replyToMessageId,
+ },
+ async run(context) {
+ const {
+ phone_number_id,
+ to,
+ formatted_name,
+ first_name,
+ last_name,
+ phones,
+ emails,
+ company,
+ job_title,
+ website,
+ reply_to_message_id,
+ } = context.propsValue;
+ const phoneEntries = inputUtils.asRecords(phones).map((entry) => ({
+ phone: inputUtils.requiredString({ record: entry, key: 'phone', label: 'Phone' }),
+ type: inputUtils.optionalString({ record: entry, key: 'type' }),
+ }));
+ const emailEntries = inputUtils.asRecords(emails).map((entry) => ({
+ email: inputUtils.requiredString({ record: entry, key: 'email', label: 'Email' }),
+ type: inputUtils.optionalString({ record: entry, key: 'type' }),
+ }));
+ const org = company || job_title ? { ...(company ? { company } : {}), ...(job_title ? { title: job_title } : {}) } : undefined;
+ return whatsappClient.sendMessage({
+ accessToken: context.auth.props.access_token,
+ phoneNumberId: phone_number_id,
+ to,
+ replyToMessageId: reply_to_message_id,
+ payload: {
+ type: 'contacts',
+ contacts: [
+ {
+ name: {
+ formatted_name,
+ ...(first_name ? { first_name } : {}),
+ ...(last_name ? { last_name } : {}),
+ },
+ ...(phoneEntries.length > 0
+ ? { phones: phoneEntries.map((entry) => ({ phone: entry.phone, ...(entry.type ? { type: entry.type } : {}) })) }
+ : {}),
+ ...(emailEntries.length > 0
+ ? { emails: emailEntries.map((entry) => ({ email: entry.email, ...(entry.type ? { type: entry.type } : {}) })) }
+ : {}),
+ ...(org ? { org } : {}),
+ ...(website ? { urls: [{ url: website, type: 'WORK' }] } : {}),
+ },
+ ],
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-from-template.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-from-template.ts
index d7b1d8765ff..329a2600a68 100644
--- a/packages/pieces/community/whatsapp/src/lib/actions/send-from-template.ts
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-from-template.ts
@@ -1,15 +1,17 @@
import { whatsappAuth } from '../auth';
import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { commonProps } from '../common/utils';
+import { commonProps, WHATSAPP_API_BASE } from '../common/utils';
+import { messageSendOutputSchema } from '../output-schemas';
export const sendTemplateMessageAction = createAction({
auth: whatsappAuth,
name: 'send-template-message',
+ outputSchema: messageSendOutputSchema,
classification: 'WRITE',
displayName: 'Send Template Message',
description: 'Send an approved template, filling in its placeholders.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Sends a pre-approved WhatsApp message template to a recipient, filling its header, body, and button placeholders from the supplied fields. Choose this to initiate conversations outside the 24-hour customer service window or for notifications/marketing where a registered template is required; the template must already be approved in the WhatsApp Business account. Requires the sender phone number ID, recipient phone number, and the template ID (its name and language are resolved automatically). Not idempotent — each call delivers a new message.', idempotent: false },
props: {
phone_number_id: commonProps.phone_number_id,
@@ -69,7 +71,7 @@ export const sendTemplateMessageAction = createAction({
// fetch template language code
const templateData = await httpClient.sendRequest({
method: HttpMethod.GET,
- url: `https://graph.facebook.com/v20.0/${templateId}`,
+ url: `${WHATSAPP_API_BASE}/${templateId}`,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
token: context.auth.props.access_token,
@@ -85,7 +87,7 @@ export const sendTemplateMessageAction = createAction({
// https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-message-templates/#text-based
const response = await httpClient.sendRequest({
method: HttpMethod.POST,
- url: `https://graph.facebook.com/v20.0/${phoneNumberId}/messages`,
+ url: `${WHATSAPP_API_BASE}/${phoneNumberId}/messages`,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
token: context.auth.props.access_token,
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-buttons.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-buttons.ts
new file mode 100644
index 00000000000..43713d5ab5d
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-buttons.ts
@@ -0,0 +1,91 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { inputUtils } from '../common/inputs';
+import { messageSendOutputSchema } from '../output-schemas';
+
+export const sendInteractiveButtons = createAction({
+ auth: whatsappAuth,
+ name: 'send_interactive_buttons',
+ outputSchema: messageSendOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Send Interactive Buttons',
+ description: 'Sends a message with up to three quick-reply buttons.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a WhatsApp message with up to three tappable reply buttons; the recipient tap arrives as an incoming interactive message carrying the button id. Choose this over Send Message when you need a structured yes/no or menu-style answer, and over Send Interactive List when there are three options or fewer. Free-form, so it only delivers inside the 24-hour customer service window. Not idempotent — each call sends a new message.',
+ idempotent: false,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ to: whatsappProps.to,
+ body: whatsappProps.bodyText,
+ buttons: Property.Array({
+ displayName: 'Buttons',
+ description: 'Between one and three buttons. Titles must be unique and at most 20 characters.',
+ required: true,
+ properties: {
+ id: Property.ShortText({
+ displayName: 'Button ID',
+ description: 'Returned to you when the recipient taps this button. Max 256 characters.',
+ required: true,
+ }),
+ title: Property.ShortText({
+ displayName: 'Title',
+ description: 'Text on the button. Max 20 characters, unique across the buttons.',
+ required: true,
+ }),
+ },
+ }),
+ header_type: whatsappProps.interactiveHeaderType,
+ header_text: whatsappProps.interactiveHeaderText,
+ header_media_url: whatsappProps.interactiveHeaderMediaUrl,
+ footer: whatsappProps.footerText,
+ reply_to_message_id: whatsappProps.replyToMessageId,
+ },
+ async run(context) {
+ const { phone_number_id, to, body, buttons, header_type, header_text, header_media_url, footer, reply_to_message_id } =
+ context.propsValue;
+ const buttonEntries = inputUtils.asRecords(buttons).map((entry) => ({
+ id: inputUtils.requiredString({ record: entry, key: 'id', label: 'Button ID', maxLength: 256 }),
+ title: inputUtils.requiredString({ record: entry, key: 'title', label: 'Button title', maxLength: 20 }),
+ }));
+ if (buttonEntries.length < 1 || buttonEntries.length > 3) {
+ throw new Error('Interactive button messages need between 1 and 3 buttons.');
+ }
+ inputUtils.assertUnique({ values: buttonEntries.map((button) => button.title), label: 'Button titles' });
+ inputUtils.assertUnique({ values: buttonEntries.map((button) => button.id), label: 'Button IDs' });
+ inputUtils.assertMaxLength({ value: body, maxLength: 1024, label: 'Body' });
+ inputUtils.assertMaxLength({ value: footer, maxLength: 60, label: 'Footer' });
+ inputUtils.assertMaxLength({ value: header_text, maxLength: 60, label: 'Header text' });
+ const header = whatsappClient.buildInteractiveHeader({
+ headerType: header_type,
+ headerText: header_text,
+ headerMediaUrl: header_media_url,
+ });
+ return whatsappClient.sendMessage({
+ accessToken: context.auth.props.access_token,
+ phoneNumberId: phone_number_id,
+ to,
+ replyToMessageId: reply_to_message_id,
+ payload: {
+ type: 'interactive',
+ interactive: {
+ type: 'button',
+ ...(header ? { header } : {}),
+ body: { text: body },
+ ...(footer ? { footer: { text: footer } } : {}),
+ action: {
+ buttons: buttonEntries.map((button) => ({
+ type: 'reply',
+ reply: { id: button.id, title: button.title },
+ })),
+ },
+ },
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-cta-url.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-cta-url.ts
new file mode 100644
index 00000000000..2d51c7fe577
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-cta-url.ts
@@ -0,0 +1,74 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { inputUtils } from '../common/inputs';
+import { messageSendOutputSchema } from '../output-schemas';
+
+export const sendInteractiveCtaUrl = createAction({
+ auth: whatsappAuth,
+ name: 'send_interactive_cta_url',
+ outputSchema: messageSendOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Send Interactive CTA URL',
+ description: 'Sends a message with a single button that opens a web link.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a WhatsApp message with one call-to-action button that opens a URL, without needing an approved template. Choose this over Send Message when the recipient should tap through to a page rather than read a raw link. Free-form, so it only delivers inside the 24-hour customer service window. Not idempotent — each call sends a new message.',
+ idempotent: false,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ to: whatsappProps.to,
+ body: whatsappProps.bodyText,
+ button_text: Property.ShortText({
+ displayName: 'Button Text',
+ description: 'Label of the button. Max 20 characters.',
+ required: true,
+ }),
+ url: Property.ShortText({
+ displayName: 'Button URL',
+ description: 'The link the button opens.',
+ required: true,
+ }),
+ header_type: whatsappProps.interactiveHeaderType,
+ header_text: whatsappProps.interactiveHeaderText,
+ header_media_url: whatsappProps.interactiveHeaderMediaUrl,
+ footer: whatsappProps.footerText,
+ reply_to_message_id: whatsappProps.replyToMessageId,
+ },
+ async run(context) {
+ const { phone_number_id, to, body, button_text, url, header_type, header_text, header_media_url, footer, reply_to_message_id } =
+ context.propsValue;
+ inputUtils.assertMaxLength({ value: button_text, maxLength: 20, label: 'Button text' });
+ inputUtils.assertMaxLength({ value: body, maxLength: 1024, label: 'Body' });
+ inputUtils.assertMaxLength({ value: footer, maxLength: 60, label: 'Footer' });
+ inputUtils.assertMaxLength({ value: header_text, maxLength: 60, label: 'Header text' });
+ const header = whatsappClient.buildInteractiveHeader({
+ headerType: header_type,
+ headerText: header_text,
+ headerMediaUrl: header_media_url,
+ });
+ return whatsappClient.sendMessage({
+ accessToken: context.auth.props.access_token,
+ phoneNumberId: phone_number_id,
+ to,
+ replyToMessageId: reply_to_message_id,
+ payload: {
+ type: 'interactive',
+ interactive: {
+ type: 'cta_url',
+ ...(header ? { header } : {}),
+ body: { text: body },
+ ...(footer ? { footer: { text: footer } } : {}),
+ action: {
+ name: 'cta_url',
+ parameters: { display_text: button_text, url },
+ },
+ },
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-list.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-list.ts
new file mode 100644
index 00000000000..9977945abc9
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-interactive-list.ts
@@ -0,0 +1,106 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { inputUtils } from '../common/inputs';
+import { messageSendOutputSchema } from '../output-schemas';
+
+export const sendInteractiveList = createAction({
+ auth: whatsappAuth,
+ name: 'send_interactive_list',
+ outputSchema: messageSendOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Send Interactive List',
+ description: 'Sends a message that opens a menu of up to ten selectable rows.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a WhatsApp list message: a button that opens a menu of up to ten rows grouped in sections, and the recipient selection arrives as an incoming interactive message carrying the row id. Choose this over Send Interactive Buttons when there are more than three options. Free-form, so it only delivers inside the 24-hour customer service window. Not idempotent — each call sends a new message.',
+ idempotent: false,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ to: whatsappProps.to,
+ body: whatsappProps.bodyText,
+ button_text: Property.ShortText({
+ displayName: 'Button Text',
+ description: 'Label of the button that opens the list. Max 20 characters.',
+ required: true,
+ }),
+ section_title: Property.ShortText({
+ displayName: 'Section Title',
+ description: 'Title shown above the rows. Max 24 characters.',
+ required: true,
+ }),
+ rows: Property.Array({
+ displayName: 'Rows',
+ description: 'Between one and ten rows. Titles max 24 characters, descriptions max 72.',
+ required: true,
+ properties: {
+ id: Property.ShortText({
+ displayName: 'Row ID',
+ description: 'Returned to you when the recipient selects this row. Max 200 characters.',
+ required: true,
+ }),
+ title: Property.ShortText({
+ displayName: 'Title',
+ required: true,
+ }),
+ description: Property.ShortText({
+ displayName: 'Description',
+ required: false,
+ }),
+ },
+ }),
+ header_text: whatsappProps.interactiveHeaderText,
+ footer: whatsappProps.footerText,
+ reply_to_message_id: whatsappProps.replyToMessageId,
+ },
+ async run(context) {
+ const { phone_number_id, to, body, button_text, section_title, rows, header_text, footer, reply_to_message_id } =
+ context.propsValue;
+ const rowEntries = inputUtils.asRecords(rows).map((entry) => ({
+ id: inputUtils.requiredString({ record: entry, key: 'id', label: 'Row ID', maxLength: 200 }),
+ title: inputUtils.requiredString({ record: entry, key: 'title', label: 'Row title', maxLength: 24 }),
+ description: inputUtils.optionalString({ record: entry, key: 'description', label: 'Row description', maxLength: 72 }),
+ }));
+ if (rowEntries.length < 1 || rowEntries.length > 10) {
+ throw new Error('Interactive list messages need between 1 and 10 rows.');
+ }
+ inputUtils.assertUnique({ values: rowEntries.map((row) => row.id), label: 'Row IDs' });
+ inputUtils.assertMaxLength({ value: button_text, maxLength: 20, label: 'Button text' });
+ inputUtils.assertMaxLength({ value: section_title, maxLength: 24, label: 'Section title' });
+ inputUtils.assertMaxLength({ value: body, maxLength: 4096, label: 'Body' });
+ inputUtils.assertMaxLength({ value: footer, maxLength: 60, label: 'Footer' });
+ inputUtils.assertMaxLength({ value: header_text, maxLength: 60, label: 'Header text' });
+ return whatsappClient.sendMessage({
+ accessToken: context.auth.props.access_token,
+ phoneNumberId: phone_number_id,
+ to,
+ replyToMessageId: reply_to_message_id,
+ payload: {
+ type: 'interactive',
+ interactive: {
+ type: 'list',
+ ...(header_text ? { header: { type: 'text', text: header_text } } : {}),
+ body: { text: body },
+ ...(footer ? { footer: { text: footer } } : {}),
+ action: {
+ button: button_text,
+ sections: [
+ {
+ title: section_title,
+ rows: rowEntries.map((row) => ({
+ id: row.id,
+ title: row.title,
+ ...(row.description ? { description: row.description } : {}),
+ })),
+ },
+ ],
+ },
+ },
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-location.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-location.ts
new file mode 100644
index 00000000000..625a7cad41b
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-location.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { messageSendOutputSchema } from '../output-schemas';
+
+export const sendLocation = createAction({
+ auth: whatsappAuth,
+ name: 'send_location',
+ outputSchema: messageSendOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Send Location',
+ description: 'Sends a map pin for a latitude and longitude.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Sends a WhatsApp location message that renders as a map pin, with an optional place name and address. Choose this over Send Message when the payload is a physical place rather than text. Free-form, so it only delivers inside the 24-hour customer service window. Not idempotent — each call sends a new message.',
+ idempotent: false,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ to: whatsappProps.to,
+ latitude: Property.Number({
+ displayName: 'Latitude',
+ description: 'Decimal degrees, for example 31.9539.',
+ required: true,
+ }),
+ longitude: Property.Number({
+ displayName: 'Longitude',
+ description: 'Decimal degrees, for example 35.9106.',
+ required: true,
+ }),
+ name: Property.ShortText({
+ displayName: 'Location Name',
+ description: 'Title shown under the map pin, for example a venue or shop name.',
+ required: false,
+ }),
+ address: Property.ShortText({
+ displayName: 'Address',
+ description: 'Street address shown under the name. Only displayed when a name is also set.',
+ required: false,
+ }),
+ reply_to_message_id: whatsappProps.replyToMessageId,
+ },
+ async run(context) {
+ const { phone_number_id, to, latitude, longitude, name, address, reply_to_message_id } = context.propsValue;
+ return whatsappClient.sendMessage({
+ accessToken: context.auth.props.access_token,
+ phoneNumberId: phone_number_id,
+ to,
+ replyToMessageId: reply_to_message_id,
+ payload: {
+ type: 'location',
+ location: {
+ latitude: String(latitude),
+ longitude: String(longitude),
+ ...(name ? { name } : {}),
+ ...(address ? { address } : {}),
+ },
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-media.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-media.ts
index a827f4ed1e3..865fae8aace 100644
--- a/packages/pieces/community/whatsapp/src/lib/actions/send-media.ts
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-media.ts
@@ -6,11 +6,14 @@ import {
capitalizeFirstLetter,
mediaTypeSupportsCaption,
commonProps,
+ WHATSAPP_API_BASE,
} from '../common/utils';
+import { messageSendOutputSchema } from '../output-schemas';
export const sendMedia = createAction({
auth: whatsappAuth,
name: 'sendMedia',
+ outputSchema: messageSendOutputSchema,
classification: 'WRITE',
displayName: 'Send Media',
description: 'Send an image, video, audio, document or sticker by URL.',
@@ -60,24 +63,26 @@ export const sendMedia = createAction({
async run(context) {
const { to, caption, media, type, filename, phone_number_id } = context.propsValue;
const { access_token } = context.auth.props;
+ const mediaObject = {
+ link: media,
+ ...(caption && mediaTypeSupportsCaption(type) ? { caption } : {}),
+ ...(filename && type === 'document' ? { filename } : {}),
+ };
const body = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
to,
type,
- [type]: {
- link: media,
- },
+ [type]: mediaObject,
};
- if (caption && mediaTypeSupportsCaption(type)) (body[type] as any).caption = caption;
- if (filename && type === 'document') (body[type] as any).filename = filename;
- return await httpClient.sendRequest({
+ const response = await httpClient.sendRequest({
method: HttpMethod.POST,
- url: `https://graph.facebook.com/v17.0/${phone_number_id}/messages`,
+ url: `${WHATSAPP_API_BASE}/${phone_number_id}/messages`,
headers: {
Authorization: 'Bearer ' + access_token,
},
body,
});
+ return response.body;
},
});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-message.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-message.ts
index b5743ad01e7..00bc9a71e87 100644
--- a/packages/pieces/community/whatsapp/src/lib/actions/send-message.ts
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-message.ts
@@ -1,11 +1,13 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { whatsappAuth } from '../auth';
-import { commonProps } from '../common/utils';
+import { commonProps, WHATSAPP_API_BASE } from '../common/utils';
+import { messageSendOutputSchema } from '../output-schemas';
export const sendMessage = createAction({
auth: whatsappAuth,
name: 'sendMessage',
+ outputSchema: messageSendOutputSchema,
classification: 'WRITE',
displayName: 'Send Message',
description: 'Send a text message through WhatsApp',
@@ -28,9 +30,9 @@ export const sendMessage = createAction({
async run(context) {
const { to, text, phone_number_id } = context.propsValue;
const { access_token } = context.auth.props;
- return await httpClient.sendRequest({
+ const response = await httpClient.sendRequest({
method: HttpMethod.POST,
- url: `https://graph.facebook.com/v17.0/${phone_number_id}/messages`,
+ url: `${WHATSAPP_API_BASE}/${phone_number_id}/messages`,
headers: {
Authorization: 'Bearer ' + access_token,
},
@@ -44,5 +46,6 @@ export const sendMessage = createAction({
},
},
});
+ return response.body;
},
});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-reaction.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-reaction.ts
new file mode 100644
index 00000000000..1b0d8961a0c
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-reaction.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { messageSendOutputSchema } from '../output-schemas';
+
+export const sendReaction = createAction({
+ auth: whatsappAuth,
+ name: 'send_reaction',
+ outputSchema: messageSendOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Send Reaction',
+ description: 'Reacts to a message with an emoji, or removes an existing reaction.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Adds an emoji reaction to a specific WhatsApp message, or removes the reaction when the emoji is left empty. Choose this over Send Message to acknowledge a message without sending a new bubble. The target must be a message from the last 30 days that is not itself a reaction. Idempotent — reacting again with the same emoji leaves the same single reaction in place.',
+ idempotent: true,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ to: whatsappProps.to,
+ message_id: whatsappProps.messageId,
+ emoji: Property.ShortText({
+ displayName: 'Emoji',
+ description: 'A single emoji such as 👍. Leave empty to remove your reaction.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { phone_number_id, to, message_id, emoji } = context.propsValue;
+ return whatsappClient.sendMessage({
+ accessToken: context.auth.props.access_token,
+ phoneNumberId: phone_number_id,
+ to,
+ payload: {
+ type: 'reaction',
+ reaction: { message_id, emoji: emoji ?? '' },
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/send-template.ts b/packages/pieces/community/whatsapp/src/lib/actions/send-template.ts
new file mode 100644
index 00000000000..fc7042ec874
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/send-template.ts
@@ -0,0 +1,83 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { inputUtils } from '../common/inputs';
+import { messageSendOutputSchema } from '../output-schemas';
+
+export const sendTemplate = createAction({
+ auth: whatsappAuth,
+ name: 'send_template',
+ outputSchema: messageSendOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Send Template',
+ description: 'Sends an approved template by name with positional parameters.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sends a pre-approved WhatsApp message template identified by its name and language code, filling the numbered {{1}}, {{2}} placeholders from plain parameter lists for the header, body and URL button. Use this to start a conversation outside the 24-hour window or for notifications; resolve the template name, language and placeholder count with List Message Templates first. Only text parameters are supported. Not idempotent — each call sends a new message.',
+ idempotent: false,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ to: whatsappProps.to,
+ template_name: Property.ShortText({
+ displayName: 'Template Name',
+ description: 'Exact template name, for example hello_world. Get it from List Message Templates.',
+ required: true,
+ }),
+ language_code: Property.ShortText({
+ displayName: 'Language Code',
+ description: 'Language and locale of the approved template, for example en_US.',
+ required: true,
+ defaultValue: 'en_US',
+ }),
+ body_parameters: Property.Array({
+ displayName: 'Body Parameters',
+ description: 'Values for the body placeholders, in order: the first entry fills {{1}}, the second {{2}}.',
+ required: false,
+ }),
+ header_parameters: Property.Array({
+ displayName: 'Header Parameters',
+ description: 'Values for text header placeholders, in order.',
+ required: false,
+ }),
+ button_url_parameters: Property.Array({
+ displayName: 'Button URL Parameters',
+ description: 'Values for the dynamic URL suffix of the first URL button, in order.',
+ required: false,
+ }),
+ reply_to_message_id: whatsappProps.replyToMessageId,
+ },
+ async run(context) {
+ const { phone_number_id, to, template_name, language_code, body_parameters, header_parameters, button_url_parameters, reply_to_message_id } =
+ context.propsValue;
+ const body = inputUtils.asStrings(body_parameters);
+ const header = inputUtils.asStrings(header_parameters);
+ const button = inputUtils.asStrings(button_url_parameters);
+ const components = [
+ ...(header.length > 0 ? [{ type: 'header', parameters: textParameters(header) }] : []),
+ ...(body.length > 0 ? [{ type: 'body', parameters: textParameters(body) }] : []),
+ ...(button.length > 0 ? [{ type: 'button', sub_type: 'url', index: 0, parameters: textParameters(button) }] : []),
+ ];
+ return whatsappClient.sendMessage({
+ accessToken: context.auth.props.access_token,
+ phoneNumberId: phone_number_id,
+ to,
+ replyToMessageId: reply_to_message_id,
+ payload: {
+ type: 'template',
+ template: {
+ name: template_name,
+ language: { code: language_code },
+ ...(components.length > 0 ? { components } : {}),
+ },
+ },
+ });
+ },
+});
+
+function textParameters(values: string[]): { type: 'text'; text: string }[] {
+ return values.map((text) => ({ type: 'text', text }));
+}
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/update-business-profile.ts b/packages/pieces/community/whatsapp/src/lib/actions/update-business-profile.ts
new file mode 100644
index 00000000000..b1bc9e34c5a
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/update-business-profile.ts
@@ -0,0 +1,59 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappProps } from '../common/props';
+import { whatsappClient } from '../common/client';
+import { inputUtils } from '../common/inputs';
+import { updateBusinessProfileOutputSchema } from '../output-schemas';
+
+export const updateBusinessProfile = createAction({
+ auth: whatsappAuth,
+ name: 'update_business_profile',
+ outputSchema: updateBusinessProfileOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Update Business Profile',
+ description: 'Updates the public business profile for a phone number. Empty fields are left unchanged.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Updates the WhatsApp business profile of a phone number: about, address, description, email, websites and vertical. Only the fields you fill are sent, so existing values you leave empty are kept. Use Get Business Profile first to see the current values. Idempotent — resending the same values leaves the profile unchanged.',
+ idempotent: true,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ about: Property.ShortText({
+ displayName: 'About',
+ description: 'Short status line, max 139 characters.',
+ required: false,
+ }),
+ address: Property.ShortText({ displayName: 'Address', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ email: Property.ShortText({ displayName: 'Email', required: false }),
+ websites: Property.Array({
+ displayName: 'Websites',
+ description: 'Up to two URLs.',
+ required: false,
+ }),
+ vertical: whatsappProps.businessVertical,
+ },
+ async run(context) {
+ const { phone_number_id, about, address, description, email, websites, vertical } = context.propsValue;
+ const websiteEntries = inputUtils.asStrings(websites);
+ const response = await whatsappClient.request<{ success: boolean }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.POST,
+ path: `/${phone_number_id}/whatsapp_business_profile`,
+ body: {
+ messaging_product: 'whatsapp',
+ ...(about ? { about } : {}),
+ ...(address ? { address } : {}),
+ ...(description ? { description } : {}),
+ ...(email ? { email } : {}),
+ ...(websiteEntries.length > 0 ? { websites: websiteEntries } : {}),
+ ...(vertical ? { vertical } : {}),
+ },
+ });
+ return response;
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/actions/upload-media.ts b/packages/pieces/community/whatsapp/src/lib/actions/upload-media.ts
new file mode 100644
index 00000000000..63814458b40
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/actions/upload-media.ts
@@ -0,0 +1,67 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { whatsappAuth } from '../auth';
+import { commonProps } from '../common/utils';
+import { whatsappClient } from '../common/client';
+import { uploadMediaOutputSchema } from '../output-schemas';
+
+export const uploadMedia = createAction({
+ auth: whatsappAuth,
+ name: 'upload_media',
+ outputSchema: uploadMediaOutputSchema,
+ classification: 'WRITE',
+ displayName: 'Upload Media',
+ description: 'Uploads a file to WhatsApp and returns a media ID you can send.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Uploads a file from a previous step to WhatsApp and returns a media ID that stays valid for 30 days. Use this before Send Media when the file is not reachable at a public URL. Images max 5 MB, audio and video max 16 MB, documents max 100 MB. Not idempotent — each call stores a new copy and returns a new ID.',
+ idempotent: false,
+ },
+ props: {
+ phone_number_id: commonProps.phone_number_id,
+ file: Property.File({
+ displayName: 'File',
+ description: 'The file to upload, from a previous step or a URL.',
+ required: true,
+ }),
+ mime_type: Property.StaticDropdown({
+ displayName: 'File Type',
+ description: 'Must match the actual file contents; WhatsApp rejects mismatches.',
+ required: true,
+ options: {
+ options: [
+ { label: 'JPEG image', value: 'image/jpeg' },
+ { label: 'PNG image', value: 'image/png' },
+ { label: 'WebP sticker', value: 'image/webp' },
+ { label: 'MP4 video', value: 'video/mp4' },
+ { label: '3GPP video', value: 'video/3gpp' },
+ { label: 'AAC audio', value: 'audio/aac' },
+ { label: 'AMR audio', value: 'audio/amr' },
+ { label: 'MP3 audio', value: 'audio/mpeg' },
+ { label: 'MP4 audio', value: 'audio/mp4' },
+ { label: 'OGG audio', value: 'audio/ogg' },
+ { label: 'PDF document', value: 'application/pdf' },
+ { label: 'Plain text', value: 'text/plain' },
+ { label: 'Word document', value: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
+ { label: 'Excel spreadsheet', value: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
+ { label: 'PowerPoint presentation', value: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' },
+ ],
+ },
+ }),
+ },
+ async run(context) {
+ const { phone_number_id, file, mime_type } = context.propsValue;
+ const multipart = whatsappClient.buildMultipartBody({
+ fields: { messaging_product: 'whatsapp', type: mime_type },
+ file: { field: 'file', filename: file.filename, contentType: mime_type, data: file.data },
+ });
+ return whatsappClient.request<{ id: string }>({
+ accessToken: context.auth.props.access_token,
+ method: HttpMethod.POST,
+ path: `/${phone_number_id}/media`,
+ body: multipart.body,
+ headers: { 'Content-Type': multipart.contentType },
+ });
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/auth.ts b/packages/pieces/community/whatsapp/src/lib/auth.ts
index 2248f4b7d63..aa11216de56 100644
--- a/packages/pieces/community/whatsapp/src/lib/auth.ts
+++ b/packages/pieces/community/whatsapp/src/lib/auth.ts
@@ -7,6 +7,8 @@ You need the WhatsApp Business Account ID and a permanent System User access tok
2. Add the **WhatsApp** product to the app.
3. Go to **WhatsApp > API Setup** and copy the **WhatsApp Business Account ID**.
4. In [Meta Business Manager](https://business.facebook.com/) open **Settings > System Users**, add a system user with access to the app, and generate a permanent token with the **whatsapp_business_messaging** and **whatsapp_business_management** permissions.
+
+Optional: to have Activepieces verify that webhook deliveries really come from Meta, also paste your **App Secret** (App settings > Basic > App Secret). Triggers then reject any request that is not signed with it.
`;
export const whatsappAuth = PieceAuth.CustomAuth({
@@ -24,5 +26,10 @@ export const whatsappAuth = PieceAuth.CustomAuth({
placeholder: '102290129340398',
required: true,
}),
+ app_secret: PieceAuth.SecretText({
+ displayName: 'App Secret',
+ description: 'Optional. Your Meta app secret (App settings > Basic). When set, every webhook delivery must carry a valid X-Hub-Signature-256 or it is ignored.',
+ required: false,
+ }),
},
});
diff --git a/packages/pieces/community/whatsapp/src/lib/common/client.ts b/packages/pieces/community/whatsapp/src/lib/common/client.ts
new file mode 100644
index 00000000000..ddfb61bfe33
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/common/client.ts
@@ -0,0 +1,148 @@
+import { randomBytes } from 'crypto';
+import {
+ AuthenticationType,
+ httpClient,
+ HttpMethod,
+ HttpRequest,
+ QueryParams,
+} from '@activepieces/pieces-common';
+import { WHATSAPP_API_BASE } from './utils';
+
+async function request<T = Record<string, unknown>>({
+ accessToken,
+ method,
+ path,
+ body,
+ queryParams,
+ headers,
+}: RequestParams): Promise<T> {
+ const httpRequest: HttpRequest = {
+ method,
+ url: `${WHATSAPP_API_BASE}${path}`,
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: accessToken,
+ },
+ body,
+ queryParams,
+ headers,
+ };
+ const response = await httpClient.sendRequest<T>(httpRequest);
+ return response.body;
+}
+
+async function sendMessage({
+ accessToken,
+ phoneNumberId,
+ to,
+ replyToMessageId,
+ payload,
+}: SendMessageParams): Promise<MessageSendResponse> {
+ return request<MessageSendResponse>({
+ accessToken,
+ method: HttpMethod.POST,
+ path: `/${phoneNumberId}/messages`,
+ body: {
+ messaging_product: 'whatsapp',
+ recipient_type: 'individual',
+ to,
+ ...(replyToMessageId ? { context: { message_id: replyToMessageId } } : {}),
+ ...payload,
+ },
+ });
+}
+
+function buildMultipartBody({ fields, file }: MultipartParams): { body: Buffer; contentType: string } {
+ const boundary = `----ActivepiecesWhatsApp${randomBytes(12).toString('hex')}`;
+ const fieldParts = Object.entries(fields).map(([name, value]) =>
+ Buffer.from(`--${boundary}${CRLF}Content-Disposition: form-data; name="${name}"${CRLF}${CRLF}${value}${CRLF}`, 'utf8'),
+ );
+ const safeFilename = file.filename.replace(/["\r\n]/g, '_');
+ const fileHeader = Buffer.from(
+ `--${boundary}${CRLF}Content-Disposition: form-data; name="${file.field}"; filename="${safeFilename}"${CRLF}Content-Type: ${file.contentType}${CRLF}${CRLF}`,
+ 'utf8',
+ );
+ const closing = Buffer.from(`${CRLF}--${boundary}--${CRLF}`, 'utf8');
+ return {
+ body: Buffer.concat([...fieldParts, fileHeader, file.data, closing]),
+ contentType: `multipart/form-data; boundary=${boundary}`,
+ };
+}
+
+const CRLF = '\r\n';
+
+
+function buildInteractiveHeader({
+ headerType,
+ headerText,
+ headerMediaUrl,
+}: InteractiveHeaderParams): Record<string, unknown> | undefined {
+ if (!headerType || headerType === 'none') return undefined;
+ if (headerType === 'text') {
+ if (!headerText) {
+ throw new Error('Header Text is required when the header type is text.');
+ }
+ return { type: 'text', text: headerText };
+ }
+ if (!headerMediaUrl) {
+ throw new Error(`Header Media URL is required when the header type is ${headerType}.`);
+ }
+ return { type: headerType, [headerType]: { link: headerMediaUrl } };
+}
+
+function normalizeTemplateComponents(components: unknown): unknown {
+ if (typeof components === 'string') {
+ return components.replace(/\[\[(\w+)\]\]/g, '{{$1}}');
+ }
+ if (Array.isArray(components)) {
+ return components.map((item) => normalizeTemplateComponents(item));
+ }
+ if (components && typeof components === 'object') {
+ return Object.fromEntries(
+ Object.entries(components).map(([key, value]) => [key, normalizeTemplateComponents(value)]),
+ );
+ }
+ return components;
+}
+
+export const whatsappClient = {
+ buildMultipartBody,
+ request,
+ sendMessage,
+ buildInteractiveHeader,
+ normalizeTemplateComponents,
+};
+
+export type MessageSendResponse = {
+ messaging_product: string;
+ contacts: { input: string; wa_id: string }[];
+ messages: { id: string; message_status?: string }[];
+};
+
+type RequestParams = {
+ accessToken: string;
+ method: HttpMethod;
+ path: string;
+ body?: unknown;
+ queryParams?: QueryParams;
+ headers?: Record<string, string>;
+};
+
+type SendMessageParams = {
+ accessToken: string;
+ phoneNumberId: string;
+ to: string;
+ replyToMessageId?: string;
+ payload: Record<string, unknown>;
+};
+
+type InteractiveHeaderParams = {
+ headerType?: string;
+ headerText?: string;
+ headerMediaUrl?: string;
+};
+
+type MultipartParams = {
+ fields: Record<string, string>;
+ file: { field: string; filename: string; contentType: string; data: Buffer };
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/common/inputs.ts b/packages/pieces/community/whatsapp/src/lib/common/inputs.ts
new file mode 100644
index 00000000000..127604a2ca6
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/common/inputs.ts
@@ -0,0 +1,70 @@
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function parseIfJsonString(value: unknown): unknown {
+ if (typeof value !== 'string') return value;
+ const trimmed = value.trim();
+ if (!trimmed.startsWith('[') && !trimmed.startsWith('{')) return value;
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ return value;
+ }
+}
+
+function asRecords(value: unknown): Record<string, unknown>[] {
+ const parsed = parseIfJsonString(value);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter(isRecord);
+}
+
+function asStrings(value: unknown): string[] {
+ const parsed = parseIfJsonString(value);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((item): item is string => typeof item === 'string' && item.length > 0);
+}
+
+function assertMaxLength({ value, maxLength, label }: AssertMaxLengthParams): void {
+ if (value && value.length > maxLength) {
+ throw new Error(`${label} must be at most ${maxLength} characters (got ${value.length}).`);
+ }
+}
+
+function assertUnique({ values, label }: AssertUniqueParams): void {
+ if (new Set(values).size !== values.length) {
+ throw new Error(`${label} must be unique.`);
+ }
+}
+
+function optionalString({ record, key, label, maxLength }: OptionalFieldParams): string | undefined {
+ const value = record[key];
+ const text = typeof value === 'string' && value.length > 0 ? value : undefined;
+ if (maxLength !== undefined) {
+ assertMaxLength({ value: text, maxLength, label: label ?? key });
+ }
+ return text;
+}
+
+function requiredString({ record, key, label, maxLength }: RequiredFieldParams): string {
+ const value = optionalString({ record, key, label, maxLength });
+ if (!value) {
+ throw new Error(`${label} is required on every entry.`);
+ }
+ return value;
+}
+
+export const inputUtils = {
+ isRecord,
+ asRecords,
+ asStrings,
+ assertMaxLength,
+ assertUnique,
+ optionalString,
+ requiredString,
+};
+
+type AssertMaxLengthParams = { value: string | undefined; maxLength: number; label: string };
+type AssertUniqueParams = { values: string[]; label: string };
+type OptionalFieldParams = { record: Record<string, unknown>; key: string; label?: string; maxLength?: number };
+type RequiredFieldParams = { record: Record<string, unknown>; key: string; label: string; maxLength?: number };
diff --git a/packages/pieces/community/whatsapp/src/lib/common/props.ts b/packages/pieces/community/whatsapp/src/lib/common/props.ts
new file mode 100644
index 00000000000..e7ca76c2a0a
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/common/props.ts
@@ -0,0 +1,131 @@
+import { Property } from '@activepieces/pieces-framework';
+
+const to = Property.ShortText({
+ displayName: 'To',
+ description: 'Recipient phone number in international format, digits only (for example 962791234567).',
+ required: true,
+});
+
+const replyToMessageId = Property.ShortText({
+ displayName: 'Reply To Message ID',
+ description: 'Optional WhatsApp message ID (wamid) to send this message as a reply to.',
+ required: false,
+});
+
+const messageId = Property.ShortText({
+ displayName: 'Message ID',
+ description: 'The WhatsApp message ID (wamid), for example from the New Incoming Message trigger.',
+ required: true,
+});
+
+const mediaId = Property.ShortText({
+ displayName: 'Media ID',
+ description: 'The media ID returned by Upload Media or received on an incoming media message.',
+ required: true,
+});
+
+const bodyText = Property.LongText({
+ displayName: 'Body',
+ description: 'Main message text.',
+ required: true,
+});
+
+const footerText = Property.ShortText({
+ displayName: 'Footer',
+ description: 'Optional footer text, max 60 characters.',
+ required: false,
+});
+
+const interactiveHeaderType = Property.StaticDropdown({
+ displayName: 'Header Type',
+ description: 'Optional header shown above the body: a short text line or a media item from a public URL.',
+ required: false,
+ defaultValue: 'none',
+ options: {
+ options: [
+ { label: 'None', value: 'none' },
+ { label: 'Text', value: 'text' },
+ { label: 'Image', value: 'image' },
+ { label: 'Video', value: 'video' },
+ { label: 'Document', value: 'document' },
+ ],
+ },
+});
+
+const interactiveHeaderText = Property.ShortText({
+ displayName: 'Header Text',
+ description: 'Used when Header Type is Text. Max 60 characters.',
+ required: false,
+});
+
+const interactiveHeaderMediaUrl = Property.ShortText({
+ displayName: 'Header Media URL',
+ description: 'Public URL of the header image, video or document. Used when Header Type is a media type.',
+ required: false,
+});
+
+const templateCategory = Property.StaticDropdown({
+ displayName: 'Category',
+ description: 'Meta reviews and prices the template by category. Utility for transactional updates, Marketing for promotions, Authentication for one-time passcodes.',
+ required: true,
+ options: {
+ options: [
+ { label: 'Marketing', value: 'MARKETING' },
+ { label: 'Utility', value: 'UTILITY' },
+ { label: 'Authentication', value: 'AUTHENTICATION' },
+ ],
+ },
+});
+
+const templateComponents = Property.Json({
+ displayName: 'Components',
+ description:
+ 'Template components array as documented by Meta. Write variables as [[1]] or [[name]] instead of double curly braces, which Activepieces reserves for its own expressions; they are converted before sending. Example: [{"type":"BODY","text":"Hello [[1]]","example":{"body_text":[["Sam"]]}}].',
+ required: true,
+});
+
+const businessVertical = Property.StaticDropdown({
+ displayName: 'Vertical',
+ description: 'Industry shown on the business profile.',
+ required: false,
+ options: {
+ options: [
+ 'OTHER',
+ 'AUTO',
+ 'BEAUTY',
+ 'APPAREL',
+ 'EDU',
+ 'ENTERTAIN',
+ 'EVENT_PLAN',
+ 'FINANCE',
+ 'GROCERY',
+ 'GOVT',
+ 'HOTEL',
+ 'HEALTH',
+ 'NONPROFIT',
+ 'PROF_SERVICES',
+ 'RETAIL',
+ 'TRAVEL',
+ 'RESTAURANT',
+ 'ALCOHOL',
+ 'ONLINE_GAMBLING',
+ 'PHYSICAL_GAMBLING',
+ 'OTC_DRUGS',
+ ].map((value) => ({ label: value, value })),
+ },
+});
+
+export const whatsappProps = {
+ to,
+ replyToMessageId,
+ messageId,
+ mediaId,
+ bodyText,
+ footerText,
+ interactiveHeaderType,
+ interactiveHeaderText,
+ interactiveHeaderMediaUrl,
+ templateCategory,
+ templateComponents,
+ businessVertical,
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/common/utils.ts b/packages/pieces/community/whatsapp/src/lib/common/utils.ts
index 658cd26d99b..bec7f45d6d2 100644
--- a/packages/pieces/community/whatsapp/src/lib/common/utils.ts
+++ b/packages/pieces/community/whatsapp/src/lib/common/utils.ts
@@ -18,77 +18,7 @@ export const mediaTypeSupportsCaption = (type: string) =>
['image', 'video', 'document'].includes(type);
export const commonProps = {
- phone_number_id: Property.Dropdown({
- auth: whatsappAuth,
- displayName: 'From Phone Number',
- description: 'The business number the message is sent from.',
- refreshers: [],
- required: true,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- placeholder: 'Please connect your account first',
- disabled: true,
- options: [],
- };
- }
-
- const authValue = auth.props;
-
- const options: DropdownOption<string>[] = [];
-
- let hasMore = false;
- let cursor: string | undefined;
-
- do {
- const qs: QueryParams = {
- fields: 'verified_name,id,display_phone_number',
- limit: '100',
- };
- if (cursor) qs['after'] = cursor;
-
- const response = await httpClient.sendRequest<PhoneNumbersPage>({
- method: HttpMethod.GET,
- url: `https://graph.facebook.com/v20.0/${authValue.businessAccountId}/phone_numbers`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: authValue.access_token,
- },
- queryParams: qs,
- });
-
- for (const phoneNumber of response.body.data ?? []) {
- options.push({
- label: `${phoneNumber.verified_name} (${phoneNumber.display_phone_number})`,
- value: phoneNumber.id,
- });
- }
-
- const nextPage = response.body.paging?.next;
- const nextCursor = response.body.paging?.cursors?.after;
-
- if (nextPage && nextCursor) {
- hasMore = true;
- cursor = nextCursor;
- } else {
- hasMore = false;
- }
- } while (hasMore);
-
- if (options.length === 0) {
- return {
- placeholder: 'No phone numbers found in this account',
- disabled: false,
- options: [],
- };
- }
-
- return {
- disabled: false,
- options,
- };
- },
- }),
+ phone_number_id: phoneNumberDropdown({ required: true }),
message_template_id: Property.Dropdown({
displayName: 'Template',
description: 'Only templates approved by WhatsApp are delivered.',
@@ -108,19 +38,18 @@ export const commonProps = {
const options: DropdownOption<string>[] = [];
- let hasMore = false;
let cursor: string | undefined;
do {
const qs: QueryParams = {
fields: 'id,name,language',
- limit: '100',
+ limit: String(DROPDOWN_PAGE_SIZE),
};
if (cursor) qs['after'] = cursor;
- const response = await httpClient.sendRequest<TemplatesPage>({
+ const response = await httpClient.sendRequest<GraphPage<MessageTemplateRow>>({
method: HttpMethod.GET,
- url: `https://graph.facebook.com/v20.0/${authValue.businessAccountId}/message_templates`,
+ url: `${WHATSAPP_API_BASE}/${authValue.businessAccountId}/message_templates`,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
token: authValue.access_token,
@@ -135,16 +64,8 @@ export const commonProps = {
});
}
- const nextPage = response.body.paging?.next;
- const nextCursor = response.body.paging?.cursors?.after;
-
- if (nextPage && nextCursor) {
- hasMore = true;
- cursor = nextCursor;
- } else {
- hasMore = false;
- }
- } while (hasMore);
+ cursor = nextCursor(response.body);
+ } while (cursor);
if (options.length === 0) {
return {
@@ -175,7 +96,7 @@ export const commonProps = {
const templateId = String(message_template_id);
const response = await httpClient.sendRequest<TemplateDetails>({
- url: `https://graph.facebook.com/v20.0/${templateId}`,
+ url: `${WHATSAPP_API_BASE}/${templateId}`,
method: HttpMethod.GET,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
@@ -243,35 +164,88 @@ export const commonProps = {
}),
};
-function escapeTemplatePlaceholders(text: string) {
- return text.replace(/{{(\d+)}}/g, '`{`{$1`}`}');
+
+function nextCursor<T>(page: GraphPage<T>): string | undefined {
+ return page.paging?.next ? page.paging.cursors?.after : undefined;
}
-type Paging = {
- next?: string;
- cursors?: {
- after?: string;
- };
-};
+export function phoneNumberDropdown<R extends boolean>({ required }: { required: R }) {
+ return Property.Dropdown({
+ auth: whatsappAuth,
+ displayName: 'From Phone Number',
+ description: 'The business number the message is sent from.',
+ refreshers: [],
+ required,
+ options: async ({ auth }) => {
+ if (!auth) {
+ return {
+ placeholder: 'Please connect your account first',
+ disabled: true,
+ options: [],
+ };
+ }
-type PhoneNumbersPage = {
- data?: {
- id: string;
- verified_name: string;
- display_phone_number: string;
- }[];
- paging?: Paging;
-};
+ const authValue = auth.props;
-type TemplatesPage = {
- data?: {
- id: string;
- name: string;
- language: string;
- }[];
- paging?: Paging;
+ const options: DropdownOption<string>[] = [];
+
+ let cursor: string | undefined;
+
+ do {
+ const qs: QueryParams = {
+ fields: 'verified_name,id,display_phone_number',
+ limit: String(DROPDOWN_PAGE_SIZE),
+ };
+ if (cursor) qs['after'] = cursor;
+
+ const response = await httpClient.sendRequest<GraphPage<PhoneNumberRow>>({
+ method: HttpMethod.GET,
+ url: `${WHATSAPP_API_BASE}/${authValue.businessAccountId}/phone_numbers`,
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: authValue.access_token,
+ },
+ queryParams: qs,
+ });
+
+ for (const phoneNumber of response.body.data ?? []) {
+ options.push({
+ label: `${phoneNumber.verified_name} (${phoneNumber.display_phone_number})`,
+ value: phoneNumber.id,
+ });
+ }
+
+ cursor = nextCursor(response.body);
+ } while (cursor);
+
+ if (options.length === 0) {
+ return {
+ placeholder: 'No phone numbers found in this account',
+ disabled: false,
+ options: [],
+ };
+ }
+
+ return {
+ disabled: false,
+ options,
+ };
+ },
+ });
+}
+
+export const WHATSAPP_API_BASE = 'https://graph.facebook.com/v23.0';
+
+const DROPDOWN_PAGE_SIZE = 100;
+
+type GraphPage<T> = {
+ data?: T[];
+ paging?: { next?: string; cursors?: { after?: string } };
};
+type PhoneNumberRow = { id: string; verified_name: string; display_phone_number: string };
+type MessageTemplateRow = { id: string; name: string; language: string };
+
type TemplateDetails = {
components?: {
type: string;
@@ -284,3 +258,7 @@ type TemplateDetails = {
}[];
}[];
};
+
+function escapeTemplatePlaceholders(text: string) {
+ return text.replace(/{{(\d+)}}/g, '`{`{$1`}`}');
+}
diff --git a/packages/pieces/community/whatsapp/src/lib/common/webhook.ts b/packages/pieces/community/whatsapp/src/lib/common/webhook.ts
new file mode 100644
index 00000000000..53dc94c49f5
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/common/webhook.ts
@@ -0,0 +1,290 @@
+import { createHmac, timingSafeEqual } from 'crypto';
+import { Property, WebhookHandshakeStrategy, WebhookResponse } from '@activepieces/pieces-framework';
+import { inputUtils } from './inputs';
+
+const setupInstructions = Property.MarkDown({
+ value: `
+**Connect this trigger to your Meta app**
+
+1. **Publish this flow first.** Meta verifies the URL immediately, and an unpublished flow cannot answer.
+2. Open [developers.facebook.com](https://developers.facebook.com/apps), pick your app and go to **WhatsApp → Configuration**.
+3. Under **Webhook**, click **Edit** and paste this URL as the Callback URL:
+
+ \`{{webhookUrl}}\`
+
+4. Enter the same value you put in **Verify Token** below (any secret string), then click **Verify and save**.
+5. Click **Manage** next to Webhook fields and subscribe to **messages** (and **message_template_status_update** for template triggers).
+6. Make sure your app is subscribed to the WhatsApp Business Account itself. If events never arrive although the URL verified, call \`POST /{WABA_ID}/subscribed_apps\` with your access token; the dashboard does not show this state.
+
+To reject deliveries that are not signed by Meta, add your **App Secret** to the WhatsApp connection.
+
+Meta accepts **one callback URL per app**, so only the flow whose URL you paste receives events. To react to several event kinds, use one flow with this trigger and branch on the payload, or forward the payload to your other flows from a step.
+`,
+});
+
+const verifyToken = Property.ShortText({
+ displayName: 'Verify Token',
+ description: 'Optional. If set, Meta must send this exact token during webhook verification or the handshake is rejected.',
+ required: false,
+});
+
+const handshakeConfiguration = {
+ strategy: WebhookHandshakeStrategy.QUERY_PRESENT,
+ paramName: 'hub.challenge',
+} as const;
+
+function handleHandshake({ queryParams, expectedToken }: HandshakeParams): WebhookResponse {
+ const challenge = queryParams['hub.challenge'];
+ const sentToken = queryParams['hub.verify_token'];
+ if (expectedToken && sentToken !== expectedToken) {
+ return { status: 403, body: 'verify token mismatch', headers: { 'Content-Type': 'text/plain' } };
+ }
+ return { status: 200, body: challenge ?? '', headers: { 'Content-Type': 'text/plain' } };
+}
+
+function isSignedByMeta({ appSecret, headers, rawBody }: SignatureParams): boolean {
+ if (!appSecret) {
+ return true;
+ }
+ const header = headers['x-hub-signature-256'] ?? headers['X-Hub-Signature-256'];
+ const payload = rawBodyToBuffer(rawBody);
+ if (!header || !header.startsWith('sha256=') || payload === undefined) {
+ return false;
+ }
+ const expected = createHmac('sha256', appSecret).update(payload).digest('hex');
+ const received = header.slice('sha256='.length);
+ if (received.length !== expected.length) {
+ return false;
+ }
+ return timingSafeEqual(Buffer.from(received, 'utf8'), Buffer.from(expected, 'utf8'));
+}
+
+function rawBodyToBuffer(rawBody: unknown): Buffer | undefined {
+ if (Buffer.isBuffer(rawBody)) {
+ return rawBody;
+ }
+ if (typeof rawBody === 'string') {
+ return Buffer.from(rawBody, 'utf8');
+ }
+ return undefined;
+}
+
+function extractChanges({ body, field }: ExtractChangesParams): ChangeValue[] {
+ if (!isWebhookBody(body)) {
+ return [];
+ }
+ return (body.entry ?? []).flatMap((entry) =>
+ (entry.changes ?? [])
+ .filter((change) => change.field === field)
+ .map((change) => ({ ...change.value, waba_id: entry.id })),
+ );
+}
+
+function matchesPhoneNumber({ value, phoneNumberId }: MatchPhoneParams): boolean {
+ return !phoneNumberId || value.metadata?.phone_number_id === phoneNumberId;
+}
+
+function flattenIncomingMessage({ message, value }: FlattenMessageParams): FlatIncomingMessage {
+ const contact = value.contacts?.find((entry) => entry.wa_id === message.from) ?? value.contacts?.[0];
+ const media =
+ message.image ?? message.video ?? message.audio ?? message.document ?? message.sticker ?? undefined;
+ const interactiveReply = message.interactive?.button_reply ?? message.interactive?.list_reply;
+ return {
+ message_id: message.id,
+ from: message.from,
+ contact_name: contact?.profile?.name ?? null,
+ timestamp: message.timestamp,
+ received_at: toIso(message.timestamp),
+ type: message.type,
+ phone_number_id: value.metadata?.phone_number_id ?? null,
+ display_phone_number: value.metadata?.display_phone_number ?? null,
+ text: message.text?.body ?? null,
+ caption: media?.caption ?? null,
+ media_id: media?.id ?? null,
+ mime_type: media?.mime_type ?? null,
+ sha256: media?.sha256 ?? null,
+ filename: message.document?.filename ?? null,
+ latitude: message.location?.latitude ?? null,
+ longitude: message.location?.longitude ?? null,
+ location_name: message.location?.name ?? null,
+ location_address: message.location?.address ?? null,
+ interactive_type: message.interactive?.type ?? null,
+ interactive_reply_id: interactiveReply?.id ?? null,
+ interactive_reply_title: interactiveReply?.title ?? null,
+ interactive_reply_description: message.interactive?.list_reply?.description ?? null,
+ button_payload: message.button?.payload ?? null,
+ button_text: message.button?.text ?? null,
+ reaction_emoji: message.reaction?.emoji ?? null,
+ reaction_message_id: message.reaction?.message_id ?? null,
+ context_message_id: message.context?.id ?? null,
+ context_from: message.context?.from ?? null,
+ forwarded: message.context?.forwarded ?? false,
+ raw: message,
+ };
+}
+
+function flattenStatus({ status, value }: FlattenStatusParams): FlatStatus {
+ const error = status.errors?.[0];
+ return {
+ message_id: status.id,
+ status: status.status,
+ recipient_id: status.recipient_id,
+ timestamp: status.timestamp,
+ updated_at: toIso(status.timestamp),
+ phone_number_id: value.metadata?.phone_number_id ?? null,
+ display_phone_number: value.metadata?.display_phone_number ?? null,
+ conversation_id: status.conversation?.id ?? null,
+ conversation_origin: status.conversation?.origin?.type ?? null,
+ conversation_expires_at: toIso(status.conversation?.expiration_timestamp),
+ billable: status.pricing?.billable ?? null,
+ pricing_model: status.pricing?.pricing_model ?? null,
+ pricing_category: status.pricing?.category ?? null,
+ error_code: error?.code ?? null,
+ error_title: error?.title ?? null,
+ error_message: error?.message ?? null,
+ error_details: error?.error_data?.details ?? null,
+ raw: status,
+ };
+}
+
+function toIso(unixSeconds?: string): string | null {
+ if (!unixSeconds) return null;
+ const seconds = Number(unixSeconds);
+ return Number.isFinite(seconds) ? new Date(seconds * 1000).toISOString() : null;
+}
+
+function isWebhookBody(body: unknown): body is WebhookBody {
+ return inputUtils.isRecord(body) && body['object'] === 'whatsapp_business_account' && Array.isArray(body['entry']);
+}
+
+export const whatsappWebhook = {
+ setupInstructions,
+ verifyToken,
+ handshakeConfiguration,
+ handleHandshake,
+ isSignedByMeta,
+ extractChanges,
+ matchesPhoneNumber,
+ flattenIncomingMessage,
+ flattenStatus,
+};
+
+export type ChangeValue = {
+ waba_id: string;
+ messaging_product?: string;
+ metadata?: { display_phone_number?: string; phone_number_id?: string };
+ contacts?: { profile?: { name?: string }; wa_id: string }[];
+ messages?: IncomingMessage[];
+ statuses?: MessageStatus[];
+ event?: string;
+ message_template_id?: number | string;
+ message_template_name?: string;
+ message_template_language?: string;
+ reason?: string | null;
+ disable_info?: { disable_date?: string };
+ other_info?: { title?: string; description?: string };
+ rejection_info?: { reason?: string; recommendation?: string };
+};
+
+export type IncomingMessage = {
+ from: string;
+ id: string;
+ timestamp: string;
+ type: string;
+ text?: { body: string };
+ image?: MediaObject;
+ video?: MediaObject;
+ audio?: MediaObject;
+ document?: MediaObject & { filename?: string };
+ sticker?: MediaObject;
+ location?: { latitude: number; longitude: number; name?: string; address?: string };
+ contacts?: unknown[];
+ reaction?: { message_id: string; emoji?: string };
+ interactive?: {
+ type: string;
+ button_reply?: { id: string; title: string };
+ list_reply?: { id: string; title: string; description?: string };
+ };
+ button?: { payload: string; text: string };
+ context?: { from?: string; id?: string; forwarded?: boolean };
+ referral?: unknown;
+ errors?: unknown[];
+};
+
+export type MessageStatus = {
+ id: string;
+ status: string;
+ timestamp: string;
+ recipient_id: string;
+ conversation?: { id: string; origin?: { type: string }; expiration_timestamp?: string };
+ pricing?: { billable: boolean; pricing_model: string; category: string };
+ errors?: { code: number; title: string; message?: string; error_data?: { details?: string } }[];
+};
+
+export type FlatIncomingMessage = {
+ message_id: string;
+ from: string;
+ contact_name: string | null;
+ timestamp: string;
+ received_at: string | null;
+ type: string;
+ phone_number_id: string | null;
+ display_phone_number: string | null;
+ text: string | null;
+ caption: string | null;
+ media_id: string | null;
+ mime_type: string | null;
+ sha256: string | null;
+ filename: string | null;
+ latitude: number | null;
+ longitude: number | null;
+ location_name: string | null;
+ location_address: string | null;
+ interactive_type: string | null;
+ interactive_reply_id: string | null;
+ interactive_reply_title: string | null;
+ interactive_reply_description: string | null;
+ button_payload: string | null;
+ button_text: string | null;
+ reaction_emoji: string | null;
+ reaction_message_id: string | null;
+ context_message_id: string | null;
+ context_from: string | null;
+ forwarded: boolean;
+ raw: IncomingMessage;
+};
+
+export type FlatStatus = {
+ message_id: string;
+ status: string;
+ recipient_id: string;
+ timestamp: string;
+ updated_at: string | null;
+ phone_number_id: string | null;
+ display_phone_number: string | null;
+ conversation_id: string | null;
+ conversation_origin: string | null;
+ conversation_expires_at: string | null;
+ billable: boolean | null;
+ pricing_model: string | null;
+ pricing_category: string | null;
+ error_code: number | null;
+ error_title: string | null;
+ error_message: string | null;
+ error_details: string | null;
+ raw: MessageStatus;
+};
+
+type MediaObject = { id: string; mime_type: string; sha256: string; caption?: string };
+
+type WebhookBody = {
+ object: string;
+ entry?: { id: string; changes?: { field: string; value: Omit<ChangeValue, 'waba_id'> }[] }[];
+};
+
+type HandshakeParams = { queryParams: Record<string, string>; expectedToken?: string };
+type SignatureParams = { appSecret: string | undefined; headers: Record<string, string>; rawBody: unknown };
+type ExtractChangesParams = { body: unknown; field: string };
+type MatchPhoneParams = { value: ChangeValue; phoneNumberId?: string };
+type FlattenMessageParams = { message: IncomingMessage; value: ChangeValue };
+type FlattenStatusParams = { status: MessageStatus; value: ChangeValue };
diff --git a/packages/pieces/community/whatsapp/src/lib/output-schemas.ts b/packages/pieces/community/whatsapp/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..1ae7ee9f6a2
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/output-schemas.ts
@@ -0,0 +1,226 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const messageSendFields: OutputSchema['fields'] = [
+ { key: 'messaging_product', label: 'Messaging Product' },
+ {
+ key: 'contacts',
+ label: 'Contacts',
+ labelKey: 'wa_id',
+ listItems: [
+ { key: 'input', label: 'Input Number' },
+ { key: 'wa_id', label: 'WhatsApp ID' },
+ ],
+ },
+ {
+ key: 'messages',
+ label: 'Messages',
+ labelKey: 'id',
+ listItems: [
+ { key: 'id', label: 'Message ID' },
+ { key: 'message_status', label: 'Message Status' },
+ ],
+ },
+];
+
+const successFields: OutputSchema['fields'] = [{ key: 'success', label: 'Success', format: 'boolean' }];
+
+const mediaInfoFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Media ID' },
+ { key: 'mime_type', label: 'MIME Type' },
+ { key: 'sha256', label: 'SHA-256' },
+ { key: 'file_size', label: 'File Size', format: 'filesize' },
+];
+
+const templateFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Template ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'language', label: 'Language' },
+ { key: 'category', label: 'Category' },
+ { key: 'status', label: 'Status' },
+ { key: 'components', label: 'Components' },
+ {
+ key: 'quality_score',
+ label: 'Quality Score',
+ children: [
+ { key: 'score', label: 'Score' },
+ { key: 'date', label: 'Scored At' },
+ ],
+ },
+];
+
+const phoneNumberFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Phone Number ID' },
+ { key: 'verified_name', label: 'Verified Name' },
+ { key: 'display_phone_number', label: 'Display Phone Number' },
+ { key: 'quality_rating', label: 'Quality Rating' },
+ { key: 'code_verification_status', label: 'Code Verification Status' },
+ { key: 'platform_type', label: 'Platform Type' },
+];
+
+const businessProfileFields: OutputSchema['fields'] = [
+ { key: 'messaging_product', label: 'Messaging Product' },
+ { key: 'about', label: 'About' },
+ { key: 'address', label: 'Address' },
+ { key: 'description', label: 'Description' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'profile_picture_url', label: 'Profile Picture', format: 'image' },
+ { key: 'websites', label: 'Websites' },
+ { key: 'vertical', label: 'Vertical' },
+];
+
+const incomingMessageCommonFields: OutputSchema['fields'] = [
+ { key: 'message_id', label: 'Message ID' },
+ { key: 'from', label: 'From' },
+ { key: 'contact_name', label: 'Contact Name' },
+ { key: 'timestamp', label: 'Timestamp' },
+ { key: 'received_at', label: 'Received At', format: 'datetime' },
+ { key: 'type', label: 'Type' },
+ { key: 'phone_number_id', label: 'Phone Number ID' },
+ { key: 'display_phone_number', label: 'Display Phone Number' },
+];
+
+const incomingMessageContextFields: OutputSchema['fields'] = [
+ { key: 'context_message_id', label: 'Replied-To Message ID' },
+ { key: 'context_from', label: 'Replied-To Sender' },
+ { key: 'forwarded', label: 'Forwarded', format: 'boolean' },
+ { key: 'raw', label: 'Raw Message' },
+];
+
+export const messageSendOutputSchema: OutputSchema = { fields: messageSendFields };
+
+export const markMessageAsReadOutputSchema: OutputSchema = { fields: successFields };
+
+export const uploadMediaOutputSchema: OutputSchema = {
+ fields: [{ key: 'id', label: 'Media ID' }],
+};
+
+export const getMediaUrlOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'messaging_product', label: 'Messaging Product' },
+ { key: 'url', label: 'Download URL', format: 'url' },
+ ...mediaInfoFields,
+ ],
+};
+
+export const downloadMediaOutputSchema: OutputSchema = {
+ fields: [{ key: 'file', label: 'File', format: 'url' }, ...mediaInfoFields],
+};
+
+export const deleteMediaOutputSchema: OutputSchema = { fields: successFields };
+
+export const listMessageTemplatesOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'templates', label: 'Templates', listItems: templateFields, labelKey: 'name' },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const createMessageTemplateOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Template ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'category', label: 'Category' },
+ ],
+};
+
+export const editMessageTemplateOutputSchema: OutputSchema = {
+ fields: [
+ ...successFields,
+ { key: 'id', label: 'Template ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'category', label: 'Category' },
+ ],
+};
+
+export const deleteMessageTemplateOutputSchema: OutputSchema = { fields: successFields };
+
+export const listPhoneNumbersOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'phone_numbers', label: 'Phone Numbers', listItems: phoneNumberFields, labelKey: 'display_phone_number' },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+};
+
+export const getPhoneNumberOutputSchema: OutputSchema = {
+ fields: [
+ ...phoneNumberFields,
+ { key: 'name_status', label: 'Name Status' },
+ { key: 'status', label: 'Status' },
+ { key: 'throughput', label: 'Throughput', children: [{ key: 'level', label: 'Level' }] },
+ ],
+};
+
+export const getBusinessProfileOutputSchema: OutputSchema = { fields: businessProfileFields };
+
+export const updateBusinessProfileOutputSchema: OutputSchema = { fields: successFields };
+
+export const newIncomingMessageOutputSchema: OutputSchema = {
+ fields: [
+ ...incomingMessageCommonFields,
+ { key: 'text', label: 'Text' },
+ { key: 'caption', label: 'Caption' },
+ { key: 'media_id', label: 'Media ID' },
+ { key: 'mime_type', label: 'MIME Type' },
+ { key: 'sha256', label: 'SHA-256' },
+ { key: 'filename', label: 'Filename' },
+ { key: 'latitude', label: 'Latitude', format: 'number' },
+ { key: 'longitude', label: 'Longitude', format: 'number' },
+ { key: 'location_name', label: 'Location Name' },
+ { key: 'location_address', label: 'Location Address' },
+ { key: 'interactive_type', label: 'Interactive Type' },
+ { key: 'interactive_reply_id', label: 'Selected Option ID' },
+ { key: 'interactive_reply_title', label: 'Selected Option Title' },
+ { key: 'interactive_reply_description', label: 'Selected Option Description' },
+ { key: 'button_payload', label: 'Template Button Payload' },
+ { key: 'button_text', label: 'Template Button Text' },
+ ...incomingMessageContextFields,
+ ],
+};
+
+export const newMessageReactionOutputSchema: OutputSchema = {
+ fields: [
+ ...incomingMessageCommonFields,
+ { key: 'reaction_emoji', label: 'Emoji' },
+ { key: 'reaction_message_id', label: 'Reacted-To Message ID' },
+ ...incomingMessageContextFields,
+ ],
+};
+
+export const messageStatusUpdatedOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'message_id', label: 'Message ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'recipient_id', label: 'Recipient' },
+ { key: 'timestamp', label: 'Timestamp' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'phone_number_id', label: 'Phone Number ID' },
+ { key: 'display_phone_number', label: 'Display Phone Number' },
+ { key: 'conversation_id', label: 'Conversation ID' },
+ { key: 'conversation_origin', label: 'Conversation Origin' },
+ { key: 'conversation_expires_at', label: 'Conversation Expires At', format: 'datetime' },
+ { key: 'billable', label: 'Billable', format: 'boolean' },
+ { key: 'pricing_model', label: 'Pricing Model' },
+ { key: 'pricing_category', label: 'Pricing Category' },
+ { key: 'error_code', label: 'Error Code', format: 'number' },
+ { key: 'error_title', label: 'Error Title' },
+ { key: 'error_message', label: 'Error Message' },
+ { key: 'error_details', label: 'Error Details' },
+ { key: 'raw', label: 'Raw Status' },
+ ],
+};
+
+export const templateStatusUpdatedOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'waba_id', label: 'Business Account ID' },
+ { key: 'event', label: 'Event' },
+ { key: 'message_template_id', label: 'Template ID' },
+ { key: 'message_template_name', label: 'Template Name' },
+ { key: 'message_template_language', label: 'Template Language' },
+ { key: 'reason', label: 'Reason' },
+ { key: 'disable_date', label: 'Disabled At' },
+ { key: 'other_info_title', label: 'Info Title' },
+ { key: 'other_info_description', label: 'Info Description' },
+ { key: 'rejection_reason', label: 'Rejection Reason' },
+ { key: 'rejection_recommendation', label: 'Rejection Recommendation' },
+ ],
+};
diff --git a/packages/pieces/community/whatsapp/src/lib/triggers/message-status-updated.ts b/packages/pieces/community/whatsapp/src/lib/triggers/message-status-updated.ts
new file mode 100644
index 00000000000..a85f7034225
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/triggers/message-status-updated.ts
@@ -0,0 +1,93 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { phoneNumberDropdown } from '../common/utils';
+import { whatsappWebhook } from '../common/webhook';
+import { inputUtils } from '../common/inputs';
+import { messageStatusUpdatedOutputSchema } from '../output-schemas';
+
+export const messageStatusUpdated = createTrigger({
+ auth: whatsappAuth,
+ name: 'message_status_updated',
+ outputSchema: messageStatusUpdatedOutputSchema,
+ classification: 'READ',
+ displayName: 'Message Status Updated',
+ description: 'Fires when a message you sent is delivered, read, or fails.',
+ aiMetadata: {
+ description:
+ 'Fires once per delivery-state change of a message the business sent: sent, delivered, read or failed. The payload has the message id to match against your send step, the new status, conversation and pricing details, and the error code and message when delivery failed. Filter by status to react only to failures or read receipts.',
+ },
+ type: TriggerStrategy.WEBHOOK,
+ props: {
+ instructions: whatsappWebhook.setupInstructions,
+ verify_token: whatsappWebhook.verifyToken,
+ phone_number_id: phoneNumberDropdown({ required: false }),
+ status: Property.StaticMultiSelectDropdown({
+ displayName: 'Statuses',
+ description: 'Only fire for these statuses. Leave empty for all.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Sent', value: 'sent' },
+ { label: 'Delivered', value: 'delivered' },
+ { label: 'Read', value: 'read' },
+ { label: 'Failed', value: 'failed' },
+ ],
+ },
+ }),
+ },
+ sampleData: {
+ message_id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAERgSRTAwNUQyMjA1MTA2QUIxODREAA==',
+ status: 'delivered',
+ recipient_id: '962782550213',
+ timestamp: '1789520050',
+ updated_at: '2026-09-16T00:54:10.000Z',
+ phone_number_id: '1285944454608901',
+ display_phone_number: '15551394669',
+ conversation_id: 'a8b1c2d3e4f5061728394a5b6c7d8e9f',
+ conversation_origin: 'utility',
+ conversation_expires_at: '2026-09-17T00:53:20.000Z',
+ billable: true,
+ pricing_model: 'CBP',
+ pricing_category: 'utility',
+ error_code: null,
+ error_title: null,
+ error_message: null,
+ error_details: null,
+ raw: {
+ id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAERgSRTAwNUQyMjA1MTA2QUIxODREAA==',
+ status: 'delivered',
+ timestamp: '1789520050',
+ recipient_id: '962782550213',
+ conversation: { id: 'a8b1c2d3e4f5061728394a5b6c7d8e9f', origin: { type: 'utility' }, expiration_timestamp: '1789606400' },
+ pricing: { billable: true, pricing_model: 'CBP', category: 'utility' },
+ },
+ },
+ handshakeConfiguration: whatsappWebhook.handshakeConfiguration,
+ async onHandshake(context) {
+ return whatsappWebhook.handleHandshake({
+ queryParams: context.payload.queryParams,
+ expectedToken: context.propsValue.verify_token,
+ });
+ },
+ async onEnable() {
+ return;
+ },
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ if (!whatsappWebhook.isSignedByMeta({ appSecret: context.auth.props.app_secret, headers: context.payload.headers, rawBody: context.payload.rawBody })) {
+ return [];
+ }
+ const phoneNumberId = context.propsValue.phone_number_id;
+ const wantedStatuses = inputUtils.asStrings(context.propsValue.status);
+ return whatsappWebhook
+ .extractChanges({ body: context.payload.body, field: 'messages' })
+ .filter((value) => whatsappWebhook.matchesPhoneNumber({ value, phoneNumberId }))
+ .flatMap((value) =>
+ (value.statuses ?? [])
+ .filter((status) => wantedStatuses.length === 0 || wantedStatuses.includes(status.status))
+ .map((status) => whatsappWebhook.flattenStatus({ status, value })),
+ );
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/triggers/new-incoming-message.ts b/packages/pieces/community/whatsapp/src/lib/triggers/new-incoming-message.ts
new file mode 100644
index 00000000000..01aaf0d9e57
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/triggers/new-incoming-message.ts
@@ -0,0 +1,89 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { phoneNumberDropdown } from '../common/utils';
+import { whatsappWebhook } from '../common/webhook';
+import { newIncomingMessageOutputSchema } from '../output-schemas';
+
+export const newIncomingMessage = createTrigger({
+ auth: whatsappAuth,
+ name: 'new_incoming_message',
+ outputSchema: newIncomingMessageOutputSchema,
+ classification: 'READ',
+ displayName: 'New Incoming Message',
+ description: 'Fires when a customer sends your business number a message.',
+ aiMetadata: {
+ description:
+ 'Fires once per message a WhatsApp user sends to the business number: text, media, location, contacts, interactive button or list replies. Reactions are excluded and have their own trigger. The payload is flattened with the sender, message id, type-specific fields and a media id you can pass to Download Media; receiving a message opens the 24-hour window for free-form replies.',
+ },
+ type: TriggerStrategy.WEBHOOK,
+ props: {
+ instructions: whatsappWebhook.setupInstructions,
+ verify_token: whatsappWebhook.verifyToken,
+ phone_number_id: phoneNumberDropdown({ required: false }),
+ },
+ sampleData: {
+ message_id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAEhgUM0E3RjM1QjQ1RTk0RkY1RkQ4QjcA',
+ from: '962782550213',
+ contact_name: 'Odai',
+ timestamp: '1789520000',
+ received_at: '2026-09-16T00:53:20.000Z',
+ type: 'text',
+ phone_number_id: '1285944454608901',
+ display_phone_number: '15551394669',
+ text: 'Hello, I would like to know my order status.',
+ caption: null,
+ media_id: null,
+ mime_type: null,
+ sha256: null,
+ filename: null,
+ latitude: null,
+ longitude: null,
+ location_name: null,
+ location_address: null,
+ interactive_type: null,
+ interactive_reply_id: null,
+ interactive_reply_title: null,
+ interactive_reply_description: null,
+ button_payload: null,
+ button_text: null,
+ reaction_emoji: null,
+ reaction_message_id: null,
+ context_message_id: null,
+ context_from: null,
+ forwarded: false,
+ raw: {
+ from: '962782550213',
+ id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAEhgUM0E3RjM1QjQ1RTk0RkY1RkQ4QjcA',
+ timestamp: '1789520000',
+ type: 'text',
+ text: { body: 'Hello, I would like to know my order status.' },
+ },
+ },
+ handshakeConfiguration: whatsappWebhook.handshakeConfiguration,
+ async onHandshake(context) {
+ return whatsappWebhook.handleHandshake({
+ queryParams: context.payload.queryParams,
+ expectedToken: context.propsValue.verify_token,
+ });
+ },
+ async onEnable() {
+ return;
+ },
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ if (!whatsappWebhook.isSignedByMeta({ appSecret: context.auth.props.app_secret, headers: context.payload.headers, rawBody: context.payload.rawBody })) {
+ return [];
+ }
+ const phoneNumberId = context.propsValue.phone_number_id;
+ return whatsappWebhook
+ .extractChanges({ body: context.payload.body, field: 'messages' })
+ .filter((value) => whatsappWebhook.matchesPhoneNumber({ value, phoneNumberId }))
+ .flatMap((value) =>
+ (value.messages ?? [])
+ .filter((message) => message.type !== 'reaction')
+ .map((message) => whatsappWebhook.flattenIncomingMessage({ message, value })),
+ );
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/triggers/new-message-reaction.ts b/packages/pieces/community/whatsapp/src/lib/triggers/new-message-reaction.ts
new file mode 100644
index 00000000000..dc2aef68f7d
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/triggers/new-message-reaction.ts
@@ -0,0 +1,91 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { phoneNumberDropdown } from '../common/utils';
+import { whatsappWebhook } from '../common/webhook';
+import { newMessageReactionOutputSchema } from '../output-schemas';
+
+export const newMessageReaction = createTrigger({
+ auth: whatsappAuth,
+ name: 'new_message_reaction',
+ outputSchema: newMessageReactionOutputSchema,
+ classification: 'READ',
+ displayName: 'New Message Reaction',
+ description: 'Fires when a customer reacts to one of your messages with an emoji, or removes a reaction.',
+ aiMetadata: {
+ description:
+ 'Fires once each time a WhatsApp user adds or removes an emoji reaction on a message from the business number. The payload carries the reacted-to message id and the emoji; an empty emoji means the reaction was removed. Use New Incoming Message for every other message type.',
+ },
+ type: TriggerStrategy.WEBHOOK,
+ props: {
+ instructions: whatsappWebhook.setupInstructions,
+ verify_token: whatsappWebhook.verifyToken,
+ phone_number_id: phoneNumberDropdown({ required: false }),
+ },
+ sampleData: {
+ message_id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAEhgUM0E3RjM1QjQ1RTk0RkY1RkQ4QjcA',
+ from: '962782550213',
+ contact_name: 'Odai',
+ timestamp: '1789520100',
+ received_at: '2026-09-16T00:55:00.000Z',
+ type: 'reaction',
+ phone_number_id: '1285944454608901',
+ display_phone_number: '15551394669',
+ reaction_emoji: '👍',
+ reaction_message_id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAERgSRTAwNUQyMjA1MTA2QUIxODREAA==',
+ context_message_id: null,
+ context_from: null,
+ forwarded: false,
+ raw: {
+ from: '962782550213',
+ id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAEhgUM0E3RjM1QjQ1RTk0RkY1RkQ4QjcA',
+ timestamp: '1789520100',
+ type: 'reaction',
+ reaction: { message_id: 'wamid.HBgMOTYyNzgyNTUwMjEzFQIAERgSRTAwNUQyMjA1MTA2QUIxODREAA==', emoji: '👍' },
+ },
+ },
+ handshakeConfiguration: whatsappWebhook.handshakeConfiguration,
+ async onHandshake(context) {
+ return whatsappWebhook.handleHandshake({
+ queryParams: context.payload.queryParams,
+ expectedToken: context.propsValue.verify_token,
+ });
+ },
+ async onEnable() {
+ return;
+ },
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ if (!whatsappWebhook.isSignedByMeta({ appSecret: context.auth.props.app_secret, headers: context.payload.headers, rawBody: context.payload.rawBody })) {
+ return [];
+ }
+ const phoneNumberId = context.propsValue.phone_number_id;
+ return whatsappWebhook
+ .extractChanges({ body: context.payload.body, field: 'messages' })
+ .filter((value) => whatsappWebhook.matchesPhoneNumber({ value, phoneNumberId }))
+ .flatMap((value) =>
+ (value.messages ?? [])
+ .filter((message) => message.type === 'reaction')
+ .map((message) => {
+ const flat = whatsappWebhook.flattenIncomingMessage({ message, value });
+ return {
+ message_id: flat.message_id,
+ from: flat.from,
+ contact_name: flat.contact_name,
+ timestamp: flat.timestamp,
+ received_at: flat.received_at,
+ type: flat.type,
+ phone_number_id: flat.phone_number_id,
+ display_phone_number: flat.display_phone_number,
+ reaction_emoji: flat.reaction_emoji,
+ reaction_message_id: flat.reaction_message_id,
+ context_message_id: flat.context_message_id,
+ context_from: flat.context_from,
+ forwarded: flat.forwarded,
+ raw: flat.raw,
+ };
+ }),
+ );
+ },
+});
diff --git a/packages/pieces/community/whatsapp/src/lib/triggers/template-status-updated.ts b/packages/pieces/community/whatsapp/src/lib/triggers/template-status-updated.ts
new file mode 100644
index 00000000000..f3e39c7235e
--- /dev/null
+++ b/packages/pieces/community/whatsapp/src/lib/triggers/template-status-updated.ts
@@ -0,0 +1,68 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { whatsappAuth } from '../auth';
+import { whatsappWebhook } from '../common/webhook';
+import { templateStatusUpdatedOutputSchema } from '../output-schemas';
+
+export const templateStatusUpdated = createTrigger({
+ auth: whatsappAuth,
+ name: 'template_status_updated',
+ outputSchema: templateStatusUpdatedOutputSchema,
+ classification: 'READ',
+ displayName: 'Template Status Updated',
+ description: 'Fires when Meta approves, rejects, pauses or otherwise changes a message template.',
+ aiMetadata: {
+ description:
+ 'Fires once per status change on a WhatsApp message template: APPROVED, REJECTED, PAUSED, DISABLED, PENDING and related events. The payload names the template, its language, the new event and, for rejections, the reason and Meta\'s recommendation. Subscribe your app to the message_template_status_update webhook field for this to fire.',
+ },
+ type: TriggerStrategy.WEBHOOK,
+ props: {
+ instructions: whatsappWebhook.setupInstructions,
+ verify_token: whatsappWebhook.verifyToken,
+ },
+ sampleData: {
+ waba_id: '102290129340398',
+ event: 'APPROVED',
+ message_template_id: '959304846505478',
+ message_template_name: 'hello_world',
+ message_template_language: 'en_US',
+ reason: null,
+ disable_date: null,
+ other_info_title: null,
+ other_info_description: null,
+ rejection_reason: null,
+ rejection_recommendation: null,
+ },
+ handshakeConfiguration: whatsappWebhook.handshakeConfiguration,
+ async onHandshake(context) {
+ return whatsappWebhook.handleHandshake({
+ queryParams: context.payload.queryParams,
+ expectedToken: context.propsValue.verify_token,
+ });
+ },
+ async onEnable() {
+ return;
+ },
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ if (!whatsappWebhook.isSignedByMeta({ appSecret: context.auth.props.app_secret, headers: context.payload.headers, rawBody: context.payload.rawBody })) {
+ return [];
+ }
+ return whatsappWebhook
+ .extractChanges({ body: context.payload.body, field: 'message_template_status_update' })
+ .map((value) => ({
+ waba_id: value.waba_id,
+ event: value.event ?? null,
+ message_template_id: value.message_template_id != null ? String(value.message_template_id) : null,
+ message_template_name: value.message_template_name ?? null,
+ message_template_language: value.message_template_language ?? null,
+ reason: value.reason ?? null,
+ disable_date: value.disable_info?.disable_date ?? null,
+ other_info_title: value.other_info?.title ?? null,
+ other_info_description: value.other_info?.description ?? null,
+ rejection_reason: value.rejection_info?.reason ?? null,
+ rejection_recommendation: value.rejection_info?.recommendation ?? null,
+ }));
+ },
+});
diff --git a/packages/pieces/community/whatsapp/test/actions.test.ts b/packages/pieces/community/whatsapp/test/actions.test.ts
new file mode 100644
index 00000000000..febf72176a5
--- /dev/null
+++ b/packages/pieces/community/whatsapp/test/actions.test.ts
@@ -0,0 +1,402 @@
+/// <reference types="vitest/globals" />
+
+import { httpClient, HttpMethod, HttpRequest, HttpResponse } from '@activepieces/pieces-common';
+import { createMockActionContext } from '@activepieces/pieces-framework';
+import { sendInteractiveButtons } from '../src/lib/actions/send-interactive-buttons';
+import { sendInteractiveList } from '../src/lib/actions/send-interactive-list';
+import { sendInteractiveCtaUrl } from '../src/lib/actions/send-interactive-cta-url';
+import { sendLocation } from '../src/lib/actions/send-location';
+import { sendContact } from '../src/lib/actions/send-contact';
+import { sendReaction } from '../src/lib/actions/send-reaction';
+import { markMessageAsRead } from '../src/lib/actions/mark-message-as-read';
+import { uploadMedia } from '../src/lib/actions/upload-media';
+import { createMessageTemplate } from '../src/lib/actions/create-message-template';
+import { deleteMessageTemplate } from '../src/lib/actions/delete-message-template';
+import { updateBusinessProfile } from '../src/lib/actions/update-business-profile';
+import { getBusinessProfile } from '../src/lib/actions/get-business-profile';
+import { listMessageTemplates } from '../src/lib/actions/list-message-templates';
+import { listPhoneNumbers } from '../src/lib/actions/list-phone-numbers';
+import { sendMessage } from '../src/lib/actions/send-message';
+import { sendMedia } from '../src/lib/actions/send-media';
+import { sendTemplate } from '../src/lib/actions/send-template';
+import { inputUtils } from '../src/lib/common/inputs';
+
+const AUTH = { type: 'CUSTOM_AUTH', props: { access_token: 'tok', businessAccountId: 'WABA' } };
+const SEND_RESPONSE = { messaging_product: 'whatsapp', contacts: [{ input: '1', wa_id: '1' }], messages: [{ id: 'wamid.NEW' }] };
+const BASE = { phone_number_id: 'PN', to: '962782550213' };
+
+const requests: HttpRequest[] = [];
+
+function objectAt({ value, path }: ObjectAtParams): Record<string, unknown> {
+ const found = path.split('.').reduce<unknown>((current, segment) => {
+ if (inputUtils.isRecord(current)) return current[segment];
+ if (Array.isArray(current)) return current[Number(segment)];
+ return undefined;
+ }, value);
+ if (!inputUtils.isRecord(found)) {
+ throw new Error(`expected an object at ${path}`);
+ }
+ return found;
+}
+
+function bufferBody(value: unknown): Buffer {
+ if (!Buffer.isBuffer(value)) {
+ throw new Error('expected a Buffer request body');
+ }
+ return value;
+}
+
+function context<T extends Record<string, unknown>>(propsValue: T) {
+ return { ...createMockActionContext({ propsValue }), auth: AUTH };
+}
+
+function respondWith(...bodies: unknown[]) {
+ let call = 0;
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request: HttpRequest): Promise<HttpResponse> => {
+ requests.push(request);
+ const body = bodies[Math.min(call, bodies.length - 1)];
+ call += 1;
+ return { status: 200, headers: {}, body };
+ });
+}
+
+beforeEach(() => {
+ requests.length = 0;
+ respondWith(SEND_RESPONSE);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('send actions return the bare API payload', () => {
+ test('Send Message posts a text payload and returns response.body, not the HTTP envelope', async () => {
+ const out = await sendMessage.run(context({ ...BASE, text: 'hello' }));
+ expect(out).toEqual(SEND_RESPONSE);
+ expect(out).not.toHaveProperty('status');
+ expect(requests[0].url).toBe('https://graph.facebook.com/v23.0/PN/messages');
+ expect(requests[0].body).toEqual({ messaging_product: 'whatsapp', recipient_type: 'individual', to: '962782550213', type: 'text', text: { body: 'hello' } });
+ });
+
+ test('Send Media only attaches caption where the type allows it, and filename only for documents', async () => {
+ await sendMedia.run(context({ ...BASE, type: 'audio', media: 'https://x/a.mp3', caption: 'ignored', filename: 'ignored' }));
+ expect(requests[0].body).toMatchObject({ type: 'audio', audio: { link: 'https://x/a.mp3' } });
+ expect(requests[0].body).not.toMatchObject({ audio: { caption: 'ignored' } });
+
+ await sendMedia.run(context({ ...BASE, type: 'document', media: 'https://x/a.pdf', caption: 'see attached', filename: 'a.pdf' }));
+ expect(requests[1].body).toMatchObject({ type: 'document', document: { link: 'https://x/a.pdf', caption: 'see attached', filename: 'a.pdf' } });
+
+ await sendMedia.run(context({ ...BASE, type: 'image', media: 'https://x/a.png', filename: 'nope.png' }));
+ expect(requests[2].body).toMatchObject({ image: { link: 'https://x/a.png' } });
+ expect(requests[2].body).not.toMatchObject({ image: { filename: 'nope.png' } });
+ });
+});
+
+describe('Send Template (agent twin)', () => {
+ test('sends name + language only when there are no parameters', async () => {
+ await sendTemplate.run(context({ ...BASE, template_name: 'hello_world', language_code: 'en_US' }));
+ expect(requests[0].body).toEqual({
+ messaging_product: 'whatsapp',
+ recipient_type: 'individual',
+ to: '962782550213',
+ type: 'template',
+ template: { name: 'hello_world', language: { code: 'en_US' } },
+ });
+ });
+
+ test('builds header, body and url-button components from positional lists, accepting JSON strings', async () => {
+ await sendTemplate.run(
+ context({
+ ...BASE,
+ template_name: 'order_update',
+ language_code: 'en_US',
+ header_parameters: ['Sam'],
+ body_parameters: '["A1","tomorrow"]',
+ button_url_parameters: ['track/A1', ''],
+ reply_to_message_id: 'wamid.R',
+ }),
+ );
+ expect(requests[0].body).toMatchObject({
+ context: { message_id: 'wamid.R' },
+ template: {
+ name: 'order_update',
+ language: { code: 'en_US' },
+ components: [
+ { type: 'header', parameters: [{ type: 'text', text: 'Sam' }] },
+ { type: 'body', parameters: [{ type: 'text', text: 'A1' }, { type: 'text', text: 'tomorrow' }] },
+ { type: 'button', sub_type: 'url', index: 0, parameters: [{ type: 'text', text: 'track/A1' }] },
+ ],
+ },
+ });
+ });
+});
+
+describe('Send Interactive Buttons', () => {
+ test('a selected header with no content is rejected instead of sent without a header', async () => {
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body_text: 'Pick', header_type: 'image', buttons: [{ id: 'a', title: 'A' }] }))).rejects.toThrow('Header Media URL is required');
+ expect(requests).toHaveLength(0);
+ });
+ const buttons = [{ id: 'yes', title: 'Yes' }, { id: 'no', title: 'No' }];
+
+ test('happy path builds the interactive button payload with optional header and footer', async () => {
+ const out = await sendInteractiveButtons.run(
+ context({ ...BASE, body: 'Pick', buttons, header_type: 'text', header_text: 'Head', footer: 'Foot', reply_to_message_id: 'wamid.R' }),
+ );
+ expect(out).toEqual(SEND_RESPONSE);
+ expect(requests[0].body).toEqual({
+ messaging_product: 'whatsapp',
+ recipient_type: 'individual',
+ to: '962782550213',
+ context: { message_id: 'wamid.R' },
+ type: 'interactive',
+ interactive: {
+ type: 'button',
+ header: { type: 'text', text: 'Head' },
+ body: { text: 'Pick' },
+ footer: { text: 'Foot' },
+ action: { buttons: [{ type: 'reply', reply: { id: 'yes', title: 'Yes' } }, { type: 'reply', reply: { id: 'no', title: 'No' } }] },
+ },
+ });
+ });
+
+ test('omits header and footer when not provided and accepts the array as a JSON string', async () => {
+ await sendInteractiveButtons.run(context({ ...BASE, body: 'Pick', buttons: JSON.stringify(buttons), header_type: 'none' }));
+ const interactive = objectAt({ value: requests[0].body, path: 'interactive' });
+ expect(interactive).not.toHaveProperty('header');
+ expect(interactive).not.toHaveProperty('footer');
+ expect(interactive.action).toEqual({ buttons: [{ type: 'reply', reply: { id: 'yes', title: 'Yes' } }, { type: 'reply', reply: { id: 'no', title: 'No' } }] });
+ });
+
+ test('rejects zero or more than three buttons before calling the API', async () => {
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body: 'x', buttons: [] }))).rejects.toThrow('between 1 and 3');
+ await expect(
+ sendInteractiveButtons.run(context({ ...BASE, body: 'x', buttons: [1, 2, 3, 4].map((n) => ({ id: `${n}`, title: `T${n}` })) })),
+ ).rejects.toThrow('between 1 and 3');
+ expect(requests).toHaveLength(0);
+ });
+
+ test('rejects duplicate titles, duplicate ids, missing ids, over-long titles and over-long body', async () => {
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body: 'x', buttons: [{ id: 'a', title: 'Same' }, { id: 'b', title: 'Same' }] }))).rejects.toThrow(
+ 'Button titles must be unique.',
+ );
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body: 'x', buttons: [{ id: 'a', title: 'One' }, { id: 'a', title: 'Two' }] }))).rejects.toThrow(
+ 'Button IDs must be unique.',
+ );
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body: 'x', buttons: [{ title: 'No id' }] }))).rejects.toThrow('Button ID is required');
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body: 'x', buttons: [{ id: 'a', title: 'x'.repeat(21) }] }))).rejects.toThrow(
+ 'Button title must be at most 20 characters (got 21).',
+ );
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body: 'x'.repeat(1025), buttons }))).rejects.toThrow('Body must be at most 1024');
+ await expect(sendInteractiveButtons.run(context({ ...BASE, body: 'ok', buttons, footer: 'f'.repeat(61) }))).rejects.toThrow('Footer must be at most 60');
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('Send Interactive List', () => {
+ const rows = [{ id: 'r1', title: 'Row one', description: 'first' }, { id: 'r2', title: 'Row two' }];
+ const base = { ...BASE, body: 'Choose', button_text: 'Open', section_title: 'Options', rows };
+
+ test('happy path builds one section with rows and drops empty descriptions', async () => {
+ await sendInteractiveList.run(context({ ...base, header_text: 'Menu' }));
+ expect(requests[0].body).toMatchObject({
+ type: 'interactive',
+ interactive: {
+ type: 'list',
+ header: { type: 'text', text: 'Menu' },
+ body: { text: 'Choose' },
+ action: { button: 'Open', sections: [{ title: 'Options', rows: [{ id: 'r1', title: 'Row one', description: 'first' }, { id: 'r2', title: 'Row two' }] }] },
+ },
+ });
+ const secondRow = objectAt({ value: requests[0].body, path: 'interactive.action.sections.0.rows.1' });
+ expect(secondRow).not.toHaveProperty('description');
+ });
+
+ test('enforces Meta limits: 1–10 rows, unique ids, 24-char titles, 72-char descriptions, 20-char button, 4096-char body', async () => {
+ await expect(sendInteractiveList.run(context({ ...base, rows: [] }))).rejects.toThrow('between 1 and 10');
+ await expect(sendInteractiveList.run(context({ ...base, rows: Array.from({ length: 11 }, (_, i) => ({ id: `${i}`, title: `T${i}` })) }))).rejects.toThrow(
+ 'between 1 and 10',
+ );
+ await expect(sendInteractiveList.run(context({ ...base, rows: [{ id: 'dup', title: 'A' }, { id: 'dup', title: 'B' }] }))).rejects.toThrow('Row IDs must be unique.');
+ await expect(sendInteractiveList.run(context({ ...base, rows: [{ id: 'a', title: 't'.repeat(25) }] }))).rejects.toThrow('Row title must be at most 24');
+ await expect(sendInteractiveList.run(context({ ...base, rows: [{ id: 'a', title: 'ok', description: 'd'.repeat(73) }] }))).rejects.toThrow(
+ 'Row description must be at most 72',
+ );
+ await expect(sendInteractiveList.run(context({ ...base, button_text: 'b'.repeat(21) }))).rejects.toThrow('Button text must be at most 20');
+ await expect(sendInteractiveList.run(context({ ...base, section_title: 's'.repeat(25) }))).rejects.toThrow('Section title must be at most 24');
+ await expect(sendInteractiveList.run(context({ ...base, body: 'b'.repeat(4097) }))).rejects.toThrow('Body must be at most 4096');
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('Send Interactive CTA URL', () => {
+ test('builds the cta_url action with an image header', async () => {
+ await sendInteractiveCtaUrl.run(
+ context({ ...BASE, body: 'Visit', button_text: 'Open', url: 'https://activepieces.com', header_type: 'image', header_media_url: 'https://x/i.png' }),
+ );
+ expect(requests[0].body).toMatchObject({
+ interactive: {
+ type: 'cta_url',
+ header: { type: 'image', image: { link: 'https://x/i.png' } },
+ body: { text: 'Visit' },
+ action: { name: 'cta_url', parameters: { display_text: 'Open', url: 'https://activepieces.com' } },
+ },
+ });
+ });
+
+ test('rejects an over-long button label', async () => {
+ await expect(sendInteractiveCtaUrl.run(context({ ...BASE, body: 'x', button_text: 'l'.repeat(21), url: 'https://a' }))).rejects.toThrow('Button text must be at most 20');
+ expect(requests).toHaveLength(0);
+ });
+});
+
+describe('Send Location', () => {
+ test('sends coordinates as strings and omits empty name/address', async () => {
+ await sendLocation.run(context({ ...BASE, latitude: 31.9539, longitude: 35.9106 }));
+ expect(requests[0].body).toMatchObject({ type: 'location', location: { latitude: '31.9539', longitude: '35.9106' } });
+ expect(objectAt({ value: requests[0].body, path: 'location' })).not.toHaveProperty('name');
+ await sendLocation.run(context({ ...BASE, latitude: 0, longitude: -0.5, name: 'Null Island', address: 'Ocean' }));
+ expect(requests[1].body).toMatchObject({ location: { latitude: '0', longitude: '-0.5', name: 'Null Island', address: 'Ocean' } });
+ });
+});
+
+describe('Send Contact', () => {
+ test('includes only the provided sections and requires a phone on each phone entry', async () => {
+ await sendContact.run(context({ ...BASE, formatted_name: 'Jane Doe' }));
+ expect(requests[0].body).toEqual({
+ messaging_product: 'whatsapp',
+ recipient_type: 'individual',
+ to: '962782550213',
+ type: 'contacts',
+ contacts: [{ name: { formatted_name: 'Jane Doe' } }],
+ });
+
+ await sendContact.run(
+ context({
+ ...BASE,
+ formatted_name: 'Jane Doe',
+ first_name: 'Jane',
+ phones: [{ phone: '+15551234567', type: 'WORK' }, { phone: '+15557654321' }],
+ emails: '[{"email":"[email protected]","type":"WORK"}]',
+ company: 'Acme',
+ website: 'https://acme.test',
+ }),
+ );
+ expect(requests[1].body).toMatchObject({
+ contacts: [
+ {
+ name: { formatted_name: 'Jane Doe', first_name: 'Jane' },
+ phones: [{ phone: '+15551234567', type: 'WORK' }, { phone: '+15557654321' }],
+ emails: [{ email: '[email protected]', type: 'WORK' }],
+ org: { company: 'Acme' },
+ urls: [{ url: 'https://acme.test', type: 'WORK' }],
+ },
+ ],
+ });
+
+ await expect(sendContact.run(context({ ...BASE, formatted_name: 'X', phones: [{ type: 'WORK' }] }))).rejects.toThrow('Phone is required');
+ });
+});
+
+describe('Send Reaction and Mark As Read', () => {
+ test('an empty emoji removes the reaction', async () => {
+ await sendReaction.run(context({ ...BASE, message_id: 'wamid.T', emoji: '👍' }));
+ expect(requests[0].body).toMatchObject({ type: 'reaction', reaction: { message_id: 'wamid.T', emoji: '👍' } });
+ await sendReaction.run(context({ ...BASE, message_id: 'wamid.T', emoji: undefined }));
+ expect(requests[1].body).toMatchObject({ reaction: { message_id: 'wamid.T', emoji: '' } });
+ });
+
+ test('mark as read sends status=read and adds the typing indicator only when asked', async () => {
+ respondWith({ success: true });
+ const out = await markMessageAsRead.run(context({ phone_number_id: 'PN', message_id: 'wamid.IN', show_typing_indicator: false }));
+ expect(out).toEqual({ success: true });
+ expect(requests[0].url).toBe('https://graph.facebook.com/v23.0/PN/messages');
+ expect(requests[0].body).toEqual({ messaging_product: 'whatsapp', status: 'read', message_id: 'wamid.IN' });
+ await markMessageAsRead.run(context({ phone_number_id: 'PN', message_id: 'wamid.IN', show_typing_indicator: true }));
+ expect(requests[1].body).toMatchObject({ typing_indicator: { type: 'text' } });
+ });
+});
+
+describe('Upload Media', () => {
+ test('posts a hand-built multipart body with messaging_product, type and the file under its own boundary', async () => {
+ respondWith({ id: 'MEDIA' });
+ const result = await uploadMedia.run(
+ context({ phone_number_id: 'PN', mime_type: 'image/png', file: { filename: 'a.png', data: Buffer.from('png-bytes'), extension: 'png', base64: '' } }),
+ );
+ expect(result).toEqual({ id: 'MEDIA' });
+ const contentType = String(requests[0].headers?.['Content-Type']);
+ expect(contentType).toMatch(/^multipart\/form-data; boundary=----ActivepiecesWhatsApp[0-9a-f]{24}$/);
+ const boundary = contentType.split('boundary=')[1];
+ const body = bufferBody(requests[0].body).toString('utf8');
+ expect(body).toContain(`--${boundary}\r\nContent-Disposition: form-data; name="messaging_product"\r\n\r\nwhatsapp\r\n`);
+ expect(body).toContain(`--${boundary}\r\nContent-Disposition: form-data; name="type"\r\n\r\nimage/png\r\n`);
+ expect(body).toContain(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="a.png"\r\nContent-Type: image/png\r\n\r\npng-bytes\r\n`);
+ expect(body.endsWith(`--${boundary}--\r\n`)).toBe(true);
+ });
+});
+
+describe('Templates', () => {
+ test('create converts [[n]] markers and posts to the WABA', async () => {
+ respondWith({ id: 't1', status: 'PENDING', category: 'UTILITY' });
+ const out = await createMessageTemplate.run(
+ context({ name: 'order_update', language: 'en_US', category: 'UTILITY', components: [{ type: 'BODY', text: 'Order [[1]] shipped.', example: { body_text: [['A1']] } }] }),
+ );
+ expect(out).toEqual({ id: 't1', status: 'PENDING', category: 'UTILITY' });
+ expect(requests[0].url).toBe('https://graph.facebook.com/v23.0/WABA/message_templates');
+ expect(requests[0].body).toEqual({
+ name: 'order_update',
+ language: 'en_US',
+ category: 'UTILITY',
+ components: [{ type: 'BODY', text: 'Order {{1}} shipped.', example: { body_text: [['A1']] } }],
+ });
+ });
+
+ test('delete resolves the template name first, then deletes by hsm_id and name', async () => {
+ respondWith({ id: 't1', name: 'order_update' }, { success: true });
+ const out = await deleteMessageTemplate.run(context({ message_template_id: 't1' }));
+ expect(out).toEqual({ success: true });
+ expect(requests[0]).toMatchObject({ method: HttpMethod.GET, url: 'https://graph.facebook.com/v23.0/t1', queryParams: { fields: 'id,name' } });
+ expect(requests[1]).toMatchObject({
+ method: HttpMethod.DELETE,
+ url: 'https://graph.facebook.com/v23.0/WABA/message_templates',
+ queryParams: { hsm_id: 't1', name: 'order_update' },
+ });
+ });
+
+ test('list passes the status filter only when set and returns a count', async () => {
+ respondWith({ data: [{ id: 'a' }, { id: 'b' }] });
+ const out = await listMessageTemplates.run(context({ status: undefined, limit: undefined }));
+ expect(out).toEqual({ templates: [{ id: 'a' }, { id: 'b' }], count: 2 });
+ expect(requests[0].queryParams).toEqual({ fields: 'id,name,language,category,status,components,quality_score', limit: '100' });
+ await listMessageTemplates.run(context({ status: 'APPROVED', limit: 5 }));
+ expect(requests[1].queryParams).toMatchObject({ status: 'APPROVED', limit: '5' });
+ });
+});
+
+describe('List Phone Numbers', () => {
+ test('follows the after cursor until the last page and counts every number', async () => {
+ respondWith(
+ { data: [{ id: '1' }, { id: '2' }], paging: { cursors: { after: 'c1' }, next: 'https://graph/next' } },
+ { data: [{ id: '3' }], paging: { cursors: { after: 'c2' } } },
+ );
+ const result = await listPhoneNumbers.run(context({}));
+ expect(requests).toHaveLength(2);
+ expect(requests[0].queryParams).toMatchObject({ limit: '100' });
+ expect(requests[0].queryParams).not.toHaveProperty('after');
+ expect(requests[1].queryParams).toMatchObject({ after: 'c1' });
+ expect(result).toEqual({ phone_numbers: [{ id: '1' }, { id: '2' }, { id: '3' }], count: 3 });
+ });
+});
+
+describe('Business profile', () => {
+ test('get unwraps data[0]; update sends only filled fields plus messaging_product', async () => {
+ respondWith({ data: [{ messaging_product: 'whatsapp', vertical: 'OTHER' }] });
+ expect(await getBusinessProfile.run(context({ phone_number_id: 'PN' }))).toEqual({ messaging_product: 'whatsapp', vertical: 'OTHER' });
+ expect(requests[0].url).toBe('https://graph.facebook.com/v23.0/PN/whatsapp_business_profile');
+
+ respondWith({ success: true });
+ await updateBusinessProfile.run(context({ phone_number_id: 'PN', about: 'Hi', address: '', email: undefined, websites: ['https://a.test', ''], vertical: undefined }));
+ expect(requests[1].body).toEqual({ messaging_product: 'whatsapp', about: 'Hi', websites: ['https://a.test'] });
+ });
+});
+
+type ObjectAtParams = { value: unknown; path: string };
diff --git a/packages/pieces/community/whatsapp/test/client.test.ts b/packages/pieces/community/whatsapp/test/client.test.ts
new file mode 100644
index 00000000000..169ba84d708
--- /dev/null
+++ b/packages/pieces/community/whatsapp/test/client.test.ts
@@ -0,0 +1,107 @@
+/// <reference types="vitest/globals" />
+
+import { httpClient, HttpMethod, HttpRequest, HttpResponse } from '@activepieces/pieces-common';
+import { whatsappClient } from '../src/lib/common/client';
+import { WHATSAPP_API_BASE } from '../src/lib/common/utils';
+
+let lastRequest: HttpRequest | undefined;
+
+beforeEach(() => {
+ lastRequest = undefined;
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request: HttpRequest): Promise<HttpResponse> => {
+ lastRequest = request;
+ return { status: 200, headers: {}, body: { ok: true } };
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('WHATSAPP_API_BASE', () => {
+ test('pins a single, current Graph API version for the whole piece', () => {
+ expect(WHATSAPP_API_BASE).toBe('https://graph.facebook.com/v23.0');
+ });
+});
+
+describe('request', () => {
+ test('builds the URL from the base, sends a bearer token and returns only the body', async () => {
+ const body = await whatsappClient.request({ accessToken: 'tok', method: HttpMethod.GET, path: '/123', queryParams: { fields: 'id' } });
+ expect(body).toEqual({ ok: true });
+ expect(lastRequest?.url).toBe('https://graph.facebook.com/v23.0/123');
+ expect(lastRequest?.authentication).toEqual({ type: 'BEARER_TOKEN', token: 'tok' });
+ expect(lastRequest?.queryParams).toEqual({ fields: 'id' });
+ });
+});
+
+describe('sendMessage', () => {
+ test('posts to /{phone}/messages with the WhatsApp envelope and the payload merged in', async () => {
+ await whatsappClient.sendMessage({
+ accessToken: 'tok',
+ phoneNumberId: 'PN',
+ to: '962782550213',
+ payload: { type: 'text', text: { body: 'hi' } },
+ });
+ expect(lastRequest?.method).toBe(HttpMethod.POST);
+ expect(lastRequest?.url).toBe('https://graph.facebook.com/v23.0/PN/messages');
+ expect(lastRequest?.body).toEqual({
+ messaging_product: 'whatsapp',
+ recipient_type: 'individual',
+ to: '962782550213',
+ type: 'text',
+ text: { body: 'hi' },
+ });
+ });
+
+ test('adds a context.message_id only when replying to a message', async () => {
+ await whatsappClient.sendMessage({ accessToken: 't', phoneNumberId: 'PN', to: '1', replyToMessageId: 'wamid.X', payload: { type: 'text' } });
+ expect(lastRequest?.body).toMatchObject({ context: { message_id: 'wamid.X' } });
+ await whatsappClient.sendMessage({ accessToken: 't', phoneNumberId: 'PN', to: '1', replyToMessageId: '', payload: { type: 'text' } });
+ expect(lastRequest?.body).not.toHaveProperty('context');
+ });
+});
+
+describe('buildInteractiveHeader', () => {
+ test('none or missing type yields no header', () => {
+ expect(whatsappClient.buildInteractiveHeader({ headerType: 'none', headerText: 'x' })).toBeUndefined();
+ expect(whatsappClient.buildInteractiveHeader({ headerType: undefined, headerText: 'x' })).toBeUndefined();
+ });
+
+ test('text header without text and media header without a URL are rejected instead of silently dropped', () => {
+ expect(whatsappClient.buildInteractiveHeader({ headerType: 'text', headerText: 'Hello' })).toEqual({ type: 'text', text: 'Hello' });
+ expect(() => whatsappClient.buildInteractiveHeader({ headerType: 'text', headerText: '' })).toThrow('Header Text is required');
+ expect(whatsappClient.buildInteractiveHeader({ headerType: 'image', headerMediaUrl: 'https://x/y.png' })).toEqual({
+ type: 'image',
+ image: { link: 'https://x/y.png' },
+ });
+ expect(() => whatsappClient.buildInteractiveHeader({ headerType: 'video', headerMediaUrl: '' })).toThrow('Header Media URL is required when the header type is video');
+ expect(whatsappClient.buildInteractiveHeader({ headerType: 'document', headerMediaUrl: 'https://x/a.pdf' })).toEqual({
+ type: 'document',
+ document: { link: 'https://x/a.pdf' },
+ });
+ });
+});
+
+describe('normalizeTemplateComponents', () => {
+ test('converts [[n]] and [[name]] markers to WhatsApp double braces at any depth', () => {
+ const input = [
+ { type: 'HEADER', format: 'TEXT', text: 'Hi [[1]]' },
+ { type: 'BODY', text: 'Order [[order_id]] ships [[2]].', example: { body_text: [['A1', 'today']] } },
+ { type: 'BUTTONS', buttons: [{ type: 'URL', text: 'Track', url: 'https://x/[[1]]' }] },
+ ];
+ expect(whatsappClient.normalizeTemplateComponents(input)).toEqual([
+ { type: 'HEADER', format: 'TEXT', text: 'Hi {{1}}' },
+ { type: 'BODY', text: 'Order {{order_id}} ships {{2}}.', example: { body_text: [['A1', 'today']] } },
+ { type: 'BUTTONS', buttons: [{ type: 'URL', text: 'Track', url: 'https://x/{{1}}' }] },
+ ]);
+ });
+
+ test('leaves numbers, booleans, null and unrelated brackets untouched and does not mutate the input', () => {
+ const input = { n: 1, b: true, z: null, s: 'a [b] [[c d]] [[ok]]' };
+ const out = whatsappClient.normalizeTemplateComponents(input);
+ expect(out).toEqual({ n: 1, b: true, z: null, s: 'a [b] [[c d]] {{ok}}' });
+ expect(input.s).toBe('a [b] [[c d]] [[ok]]');
+ expect(whatsappClient.normalizeTemplateComponents('plain')).toBe('plain');
+ expect(whatsappClient.normalizeTemplateComponents(undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/pieces/community/whatsapp/test/inputs.test.ts b/packages/pieces/community/whatsapp/test/inputs.test.ts
new file mode 100644
index 00000000000..f5538935961
--- /dev/null
+++ b/packages/pieces/community/whatsapp/test/inputs.test.ts
@@ -0,0 +1,80 @@
+/// <reference types="vitest/globals" />
+
+import { inputUtils } from '../src/lib/common/inputs';
+
+describe('asRecords', () => {
+ test('keeps only object entries of an array', () => {
+ expect(inputUtils.asRecords([{ id: 'a' }, 'x', null, 3, [{ id: 'nested' }], { id: 'b' }])).toEqual([{ id: 'a' }, { id: 'b' }]);
+ });
+
+ test('accepts a JSON-encoded array string, as the builder sends when a prop is toggled to dynamic', () => {
+ expect(inputUtils.asRecords('[{"id":"a","title":"A"}]')).toEqual([{ id: 'a', title: 'A' }]);
+ expect(inputUtils.asRecords(' [{"id":"a"}] ')).toEqual([{ id: 'a' }]);
+ });
+
+ test('returns an empty list for anything that is not an array', () => {
+ expect(inputUtils.asRecords(undefined)).toEqual([]);
+ expect(inputUtils.asRecords(null)).toEqual([]);
+ expect(inputUtils.asRecords({ id: 'a' })).toEqual([]);
+ expect(inputUtils.asRecords('not json')).toEqual([]);
+ expect(inputUtils.asRecords('[broken')).toEqual([]);
+ expect(inputUtils.asRecords('{"id":"a"}')).toEqual([]);
+ });
+});
+
+describe('asStrings', () => {
+ test('keeps non-empty strings only, from arrays or JSON strings', () => {
+ expect(inputUtils.asStrings(['a', '', 1, null, 'b'])).toEqual(['a', 'b']);
+ expect(inputUtils.asStrings('["x","y"]')).toEqual(['x', 'y']);
+ expect(inputUtils.asStrings('plain')).toEqual([]);
+ expect(inputUtils.asStrings(undefined)).toEqual([]);
+ });
+});
+
+describe('requiredString / optionalString', () => {
+ test('reads a string field and treats empty or non-string values as missing', () => {
+ expect(inputUtils.optionalString({ record: { a: 'x' }, key: 'a' })).toBe('x');
+ expect(inputUtils.optionalString({ record: { a: '' }, key: 'a' })).toBeUndefined();
+ expect(inputUtils.optionalString({ record: { a: 5 }, key: 'a' })).toBeUndefined();
+ expect(inputUtils.optionalString({ record: {}, key: 'a' })).toBeUndefined();
+ });
+
+ test('requiredString names the field in its error', () => {
+ expect(() => inputUtils.requiredString({ record: {}, key: 'id', label: 'Button ID' })).toThrow('Button ID is required on every entry.');
+ expect(inputUtils.requiredString({ record: { id: 'ok' }, key: 'id', label: 'Button ID' })).toBe('ok');
+ });
+
+ test('maxLength is enforced with the actual length in the message and is inclusive', () => {
+ expect(inputUtils.requiredString({ record: { t: 'x'.repeat(20) }, key: 't', label: 'Title', maxLength: 20 })).toHaveLength(20);
+ expect(() => inputUtils.requiredString({ record: { t: 'x'.repeat(21) }, key: 't', label: 'Title', maxLength: 20 })).toThrow(
+ 'Title must be at most 20 characters (got 21).',
+ );
+ expect(() => inputUtils.optionalString({ record: { d: 'y'.repeat(73) }, key: 'd', label: 'Description', maxLength: 72 })).toThrow(
+ 'Description must be at most 72 characters (got 73).',
+ );
+ expect(inputUtils.optionalString({ record: {}, key: 'd', label: 'Description', maxLength: 72 })).toBeUndefined();
+ });
+});
+
+describe('assertMaxLength / assertUnique', () => {
+ test('assertMaxLength ignores undefined and empty values', () => {
+ expect(() => inputUtils.assertMaxLength({ value: undefined, maxLength: 1, label: 'X' })).not.toThrow();
+ expect(() => inputUtils.assertMaxLength({ value: '', maxLength: 1, label: 'X' })).not.toThrow();
+ expect(() => inputUtils.assertMaxLength({ value: 'ab', maxLength: 1, label: 'X' })).toThrow('X must be at most 1 characters (got 2).');
+ });
+
+ test('assertUnique rejects duplicates and accepts distinct or empty lists', () => {
+ expect(() => inputUtils.assertUnique({ values: ['Yes', 'No', 'Yes'], label: 'Button titles' })).toThrow('Button titles must be unique.');
+ expect(() => inputUtils.assertUnique({ values: ['Yes', 'No'], label: 'Button titles' })).not.toThrow();
+ expect(() => inputUtils.assertUnique({ values: [], label: 'Button titles' })).not.toThrow();
+ });
+});
+
+describe('isRecord', () => {
+ test('distinguishes plain objects from arrays, null and primitives', () => {
+ expect(inputUtils.isRecord({})).toBe(true);
+ expect(inputUtils.isRecord([])).toBe(false);
+ expect(inputUtils.isRecord(null)).toBe(false);
+ expect(inputUtils.isRecord('s')).toBe(false);
+ });
+});
diff --git a/packages/pieces/community/whatsapp/test/webhook.test.ts b/packages/pieces/community/whatsapp/test/webhook.test.ts
new file mode 100644
index 00000000000..332879beb03
--- /dev/null
+++ b/packages/pieces/community/whatsapp/test/webhook.test.ts
@@ -0,0 +1,302 @@
+/// <reference types="vitest/globals" />
+
+import { createHmac } from 'crypto';
+
+import { ChangeValue, IncomingMessage, MessageStatus, whatsappWebhook } from '../src/lib/common/webhook';
+
+const METADATA = { display_phone_number: '15551394669', phone_number_id: '1285944454608901' };
+
+function wabaBody({ changes, entryId = 'waba-1' }: WabaBodyParams) {
+ return { object: 'whatsapp_business_account', entry: [{ id: entryId, changes }] };
+}
+
+function sign({ secret, body }: SignParams): string {
+ return `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`;
+}
+
+function textMessage(overrides: Partial<IncomingMessage> = {}): IncomingMessage {
+ return {
+ from: '962782550213',
+ id: 'wamid.TEXT',
+ timestamp: '1789520000',
+ type: 'text',
+ text: { body: 'hello' },
+ ...overrides,
+ };
+}
+
+function value(overrides: Partial<ChangeValue> = {}): ChangeValue {
+ return {
+ waba_id: 'waba-1',
+ messaging_product: 'whatsapp',
+ metadata: METADATA,
+ contacts: [{ profile: { name: 'Odai' }, wa_id: '962782550213' }],
+ ...overrides,
+ };
+}
+
+describe('extractChanges', () => {
+ test('returns nothing for a body that is not a WhatsApp Business Account event', () => {
+ expect(whatsappWebhook.extractChanges({ body: { object: 'page', entry: [] }, field: 'messages' })).toEqual([]);
+ expect(whatsappWebhook.extractChanges({ body: undefined, field: 'messages' })).toEqual([]);
+ expect(whatsappWebhook.extractChanges({ body: 'not json', field: 'messages' })).toEqual([]);
+ expect(whatsappWebhook.extractChanges({ body: { object: 'whatsapp_business_account' }, field: 'messages' })).toEqual([]);
+ });
+
+ test('keeps only changes for the requested field and attaches the WABA id', () => {
+ const body = wabaBody({
+ changes: [
+ { field: 'messages', value: { messages: [textMessage()] } },
+ { field: 'message_template_status_update', value: { event: 'APPROVED' } },
+ ],
+ });
+ const messages = whatsappWebhook.extractChanges({ body, field: 'messages' });
+ const templates = whatsappWebhook.extractChanges({ body, field: 'message_template_status_update' });
+ expect(messages).toHaveLength(1);
+ expect(messages[0].waba_id).toBe('waba-1');
+ expect(messages[0].messages).toHaveLength(1);
+ expect(templates).toHaveLength(1);
+ expect(templates[0].event).toBe('APPROVED');
+ });
+
+ test('flattens across several entries and tolerates an entry without changes', () => {
+ const body = {
+ object: 'whatsapp_business_account',
+ entry: [
+ { id: 'a', changes: [{ field: 'messages', value: { messages: [textMessage()] } }] },
+ { id: 'b' },
+ { id: 'c', changes: [{ field: 'messages', value: { statuses: [] } }] },
+ ],
+ };
+ const changes = whatsappWebhook.extractChanges({ body, field: 'messages' });
+ expect(changes.map((change) => change.waba_id)).toEqual(['a', 'c']);
+ });
+});
+
+describe('matchesPhoneNumber', () => {
+ test('accepts every event when no filter is set', () => {
+ expect(whatsappWebhook.matchesPhoneNumber({ value: value(), phoneNumberId: undefined })).toBe(true);
+ expect(whatsappWebhook.matchesPhoneNumber({ value: value(), phoneNumberId: '' })).toBe(true);
+ });
+
+ test('filters on the metadata phone number id', () => {
+ expect(whatsappWebhook.matchesPhoneNumber({ value: value(), phoneNumberId: '1285944454608901' })).toBe(true);
+ expect(whatsappWebhook.matchesPhoneNumber({ value: value(), phoneNumberId: 'other' })).toBe(false);
+ expect(whatsappWebhook.matchesPhoneNumber({ value: value({ metadata: undefined }), phoneNumberId: 'other' })).toBe(false);
+ });
+});
+
+describe('flattenIncomingMessage', () => {
+ test('text message: core fields, contact name and ISO timestamp', () => {
+ const flat = whatsappWebhook.flattenIncomingMessage({ message: textMessage(), value: value() });
+ expect(flat).toMatchObject({
+ message_id: 'wamid.TEXT',
+ from: '962782550213',
+ contact_name: 'Odai',
+ timestamp: '1789520000',
+ received_at: '2026-09-16T00:53:20.000Z',
+ type: 'text',
+ phone_number_id: '1285944454608901',
+ display_phone_number: '15551394669',
+ text: 'hello',
+ media_id: null,
+ interactive_reply_id: null,
+ reaction_emoji: null,
+ context_message_id: null,
+ forwarded: false,
+ });
+ expect(flat.raw).toBe(flat.raw);
+ });
+
+ test('a non-numeric or missing timestamp yields a null received_at instead of throwing', () => {
+ const bad = whatsappWebhook.flattenIncomingMessage({ message: textMessage({ timestamp: 'not-a-number' }), value: value() });
+ expect(bad.received_at).toBeNull();
+ const empty = whatsappWebhook.flattenIncomingMessage({ message: textMessage({ timestamp: '' }), value: value() });
+ expect(empty.received_at).toBeNull();
+ });
+
+ test('picks the contact matching the sender, falling back to the first contact, then null', () => {
+ const twoContacts = value({
+ contacts: [
+ { profile: { name: 'Someone Else' }, wa_id: '111' },
+ { profile: { name: 'Odai' }, wa_id: '962782550213' },
+ ],
+ });
+ expect(whatsappWebhook.flattenIncomingMessage({ message: textMessage(), value: twoContacts }).contact_name).toBe('Odai');
+ const unrelated = value({ contacts: [{ profile: { name: 'Fallback' }, wa_id: '999' }] });
+ expect(whatsappWebhook.flattenIncomingMessage({ message: textMessage(), value: unrelated }).contact_name).toBe('Fallback');
+ expect(whatsappWebhook.flattenIncomingMessage({ message: textMessage(), value: value({ contacts: undefined }) }).contact_name).toBeNull();
+ expect(whatsappWebhook.flattenIncomingMessage({ message: textMessage(), value: value({ metadata: undefined }) }).phone_number_id).toBeNull();
+ });
+
+ test('media messages expose the media id, mime type, hash, caption and document filename', () => {
+ const image = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({ type: 'image', text: undefined, image: { id: 'm1', mime_type: 'image/jpeg', sha256: 'abc', caption: 'pic' } }),
+ value: value(),
+ });
+ expect(image).toMatchObject({ type: 'image', text: null, media_id: 'm1', mime_type: 'image/jpeg', sha256: 'abc', caption: 'pic', filename: null });
+
+ const doc = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({ type: 'document', text: undefined, document: { id: 'd1', mime_type: 'application/pdf', sha256: 'h', filename: 'invoice.pdf' } }),
+ value: value(),
+ });
+ expect(doc).toMatchObject({ media_id: 'd1', filename: 'invoice.pdf', caption: null });
+ });
+
+ test('location, interactive replies, template buttons, reactions and reply context are flattened', () => {
+ const location = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({ type: 'location', text: undefined, location: { latitude: 31.95, longitude: 35.91, name: 'Amman', address: 'JO' } }),
+ value: value(),
+ });
+ expect(location).toMatchObject({ latitude: 31.95, longitude: 35.91, location_name: 'Amman', location_address: 'JO' });
+
+ const button = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({
+ type: 'interactive',
+ text: undefined,
+ interactive: { type: 'button_reply', button_reply: { id: 'yes', title: 'Yes' } },
+ context: { from: '15551394669', id: 'wamid.ORIGINAL', forwarded: true },
+ }),
+ value: value(),
+ });
+ expect(button).toMatchObject({
+ interactive_type: 'button_reply',
+ interactive_reply_id: 'yes',
+ interactive_reply_title: 'Yes',
+ interactive_reply_description: null,
+ context_message_id: 'wamid.ORIGINAL',
+ context_from: '15551394669',
+ forwarded: true,
+ });
+
+ const list = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({ type: 'interactive', text: undefined, interactive: { type: 'list_reply', list_reply: { id: 'r1', title: 'Row', description: 'first' } } }),
+ value: value(),
+ });
+ expect(list).toMatchObject({ interactive_reply_id: 'r1', interactive_reply_title: 'Row', interactive_reply_description: 'first' });
+
+ const templateButton = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({ type: 'button', text: undefined, button: { payload: 'STOP', text: 'Stop' } }),
+ value: value(),
+ });
+ expect(templateButton).toMatchObject({ button_payload: 'STOP', button_text: 'Stop' });
+
+ const reaction = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({ type: 'reaction', text: undefined, reaction: { message_id: 'wamid.X', emoji: '👍' } }),
+ value: value(),
+ });
+ expect(reaction).toMatchObject({ reaction_emoji: '👍', reaction_message_id: 'wamid.X' });
+
+ const removed = whatsappWebhook.flattenIncomingMessage({
+ message: textMessage({ type: 'reaction', text: undefined, reaction: { message_id: 'wamid.X' } }),
+ value: value(),
+ });
+ expect(removed.reaction_emoji).toBeNull();
+ });
+});
+
+describe('flattenStatus', () => {
+ const delivered: MessageStatus = {
+ id: 'wamid.SENT',
+ status: 'delivered',
+ timestamp: '1789520050',
+ recipient_id: '962782550213',
+ conversation: { id: 'conv', origin: { type: 'utility' }, expiration_timestamp: '1789606400' },
+ pricing: { billable: true, pricing_model: 'CBP', category: 'utility' },
+ };
+
+ test('delivered status with conversation and pricing', () => {
+ expect(whatsappWebhook.flattenStatus({ status: delivered, value: value() })).toEqual({
+ message_id: 'wamid.SENT',
+ status: 'delivered',
+ recipient_id: '962782550213',
+ timestamp: '1789520050',
+ updated_at: '2026-09-16T00:54:10.000Z',
+ phone_number_id: '1285944454608901',
+ display_phone_number: '15551394669',
+ conversation_id: 'conv',
+ conversation_origin: 'utility',
+ conversation_expires_at: '2026-09-17T00:53:20.000Z',
+ billable: true,
+ pricing_model: 'CBP',
+ pricing_category: 'utility',
+ error_code: null,
+ error_title: null,
+ error_message: null,
+ error_details: null,
+ raw: delivered,
+ });
+ });
+
+ test('failed status surfaces the first error and nulls the missing conversation', () => {
+ const failed: MessageStatus = {
+ id: 'wamid.FAIL',
+ status: 'failed',
+ timestamp: 'garbage',
+ recipient_id: '962782550213',
+ errors: [{ code: 131026, title: 'Message undeliverable', message: 'Message undeliverable.', error_data: { details: 'Not on WhatsApp' } }],
+ };
+ expect(whatsappWebhook.flattenStatus({ status: failed, value: value() })).toMatchObject({
+ status: 'failed',
+ updated_at: null,
+ conversation_id: null,
+ conversation_expires_at: null,
+ billable: null,
+ error_code: 131026,
+ error_title: 'Message undeliverable',
+ error_message: 'Message undeliverable.',
+ error_details: 'Not on WhatsApp',
+ });
+ });
+});
+
+describe('handleHandshake', () => {
+ test('echoes the challenge as text/plain when no verify token is configured', () => {
+ expect(
+ whatsappWebhook.handleHandshake({
+ queryParams: { 'hub.mode': 'subscribe', 'hub.verify_token': 'anything', 'hub.challenge': '12345' },
+ expectedToken: undefined,
+ }),
+ ).toEqual({ status: 200, body: '12345', headers: { 'Content-Type': 'text/plain' } });
+ });
+
+ test('accepts a matching token and rejects a mismatch with 403', () => {
+ const good = whatsappWebhook.handleHandshake({ queryParams: { 'hub.verify_token': 'secret', 'hub.challenge': 'c' }, expectedToken: 'secret' });
+ expect(good.status).toBe(200);
+ expect(good.body).toBe('c');
+ const bad = whatsappWebhook.handleHandshake({ queryParams: { 'hub.verify_token': 'wrong', 'hub.challenge': 'c' }, expectedToken: 'secret' });
+ expect(bad.status).toBe(403);
+ expect(bad.body).not.toBe('c');
+ const missing = whatsappWebhook.handleHandshake({ queryParams: { 'hub.challenge': 'c' }, expectedToken: 'secret' });
+ expect(missing.status).toBe(403);
+ });
+
+ test('a missing challenge still answers 200 with an empty body', () => {
+ expect(whatsappWebhook.handleHandshake({ queryParams: {}, expectedToken: undefined }).body).toBe('');
+ });
+});
+
+describe('delivery signature', () => {
+ const raw = JSON.stringify({ object: 'whatsapp_business_account', entry: [] });
+
+ test('without an app secret every delivery is accepted, as before', () => {
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: undefined, headers: {}, rawBody: raw })).toBe(true);
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: '', headers: {}, rawBody: undefined })).toBe(true);
+ });
+
+ test('with an app secret a valid signature over the raw body is required', () => {
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: 's3cret', headers: { 'x-hub-signature-256': sign({ secret: 's3cret', body: raw }) }, rawBody: raw })).toBe(true);
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: 's3cret', headers: { 'x-hub-signature-256': sign({ secret: 's3cret', body: raw }) }, rawBody: Buffer.from(raw) })).toBe(true);
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: 's3cret', headers: { 'x-hub-signature-256': sign({ secret: 'other', body: raw }) }, rawBody: raw })).toBe(false);
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: 's3cret', headers: { 'x-hub-signature-256': sign({ secret: 's3cret', body: raw + ' ' }) }, rawBody: raw })).toBe(false);
+ });
+
+ test('a missing header, wrong prefix or missing raw body is rejected when a secret is set', () => {
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: 's3cret', headers: {}, rawBody: raw })).toBe(false);
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: 's3cret', headers: { 'x-hub-signature-256': 'sha1=abc' }, rawBody: raw })).toBe(false);
+ expect(whatsappWebhook.isSignedByMeta({ appSecret: 's3cret', headers: { 'x-hub-signature-256': sign({ secret: 's3cret', body: raw }) }, rawBody: undefined })).toBe(false);
+ });
+});
+
+type WabaBodyParams = { changes: { field: string; value: Record<string, unknown> }[]; entryId?: string };
+type SignParams = { secret: string; body: string };
diff --git a/packages/pieces/community/whatsapp/vitest.config.ts b/packages/pieces/community/whatsapp/vitest.config.ts
new file mode 100644
index 00000000000..5ad1d9d905f
--- /dev/null
+++ b/packages/pieces/community/whatsapp/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path';
+import { defineConfig } from 'vitest/config';
+
+const repoRoot = path.resolve(__dirname, '../../../..');
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+});