Repository navigation
Issue #922: Added WhatsApp Business Cloud API messaging. - #4590
joshua1234511 wants to merge 7 commits into
Conversation
…pensourcepos#922) Add WhatsApp config tab, a messaging page with customer conversation history, send-bill-via-WhatsApp buttons on invoices/receipts/quotes/ work orders, and a public webhook for inbound replies and status updates. Includes Whatsapp_lib (Cloud API text + PDF document send), Whatsapp controller + views, Whatsapp_webhook, Whatsapp_message model, a whatsapp_messages table, module/permission/grant seeding, and language keys.
📝 WalkthroughWalkthroughThis PR adds WhatsApp Business Cloud API support for configuration, outbound sending, inbound webhook processing, conversation storage, sales document delivery, and related UI and localization. ChangesWhatsApp Messaging Feature
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant Meta as Meta WhatsApp Cloud API
participant Webhook as Whatsapp_webhook
participant MessageModel as Whatsapp_message
Meta->>Webhook: GET verify request
Webhook-->>Meta: hub_challenge or 403
Meta->>Webhook: POST signed payload
Webhook->>Webhook: validate X-Hub-Signature-256
Webhook->>MessageModel: log inbound messages / update_status
Webhook-->>Meta: HTTP 200
sequenceDiagram
participant User
participant Sales as Sales Controller
participant WhatsappLib as Whatsapp_lib
participant GraphAPI as WhatsApp Graph API
User->>Sales: getSendWhatsapp(sale_id, type)
Sales->>Sales: generate PDF + caption
Sales->>WhatsappLib: sendDocument(phone, pdf, caption)
WhatsappLib->>GraphAPI: upload media + send document
GraphAPI-->>WhatsappLib: message id
Sales-->>User: JSON success/message
Related issues: Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…docs from config.
…docs from config.
…docs from config.
There was a problem hiding this comment.
Actionable comments posted: 11
🧹 Nitpick comments (2)
app/Database/Migrations/20260703000000_AddWhatsappModule.php (1)
53-71: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAdd an index on
wa_message_id.
Whatsapp_message::update_status()filters bywa_message_idon every inbound status webhook callback, but no key is defined for that column here (onlymessage_id,phone,person_id,created_atare indexed). As conversation volume grows this becomes an unindexed lookup on every delivery/read receipt.⚡ Proposed fix
$this->forge->addKey('message_id', true); $this->forge->addKey('phone'); $this->forge->addKey('person_id'); $this->forge->addKey('created_at'); + $this->forge->addKey('wa_message_id'); $this->forge->createTable('whatsapp_messages', true);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/Database/Migrations/20260703000000_AddWhatsappModule.php` around lines 53 - 71, Add an index for wa_message_id in the whatsapp_messages table definition. Update the migration’s addKey calls in AddWhatsappModule so that Whatsapp_message::update_status() can efficiently look up rows by wa_message_id during inbound status webhook handling; keep the existing keys and add a dedicated key for that column.app/Libraries/Whatsapp_lib.php (1)
206-231: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winHand-rolled phone normalization is fragile; consider a proven library.
The "already has country code" check is a heuristic: if a national number happens to start with the same digits as the configured country code without actually being prefixed, it's skipped and a malformed number is sent to the Graph API. Also, the comment says "drop a single leading trunk '0'" but
ltrim($digits, '0')strips all leading zeros, not just one.
giggsey/libphonenumber-for-php(based on Google's libphonenumber, actively maintained) handles this parsing/E.164 formatting robustly and would remove this class of edge-case bugs.♻️ Illustrative refactor using libphonenumber
+use libphonenumber\PhoneNumberUtil; +use libphonenumber\PhoneNumberFormat; + public function normalizePhone(string $phone): string { - $digits = preg_replace('/\D+/', '', $phone) ?? ''; - - if ($digits === '') { - return ''; - } - - $country = preg_replace('/\D+/', '', (string) ($this->config['whatsapp_default_country_code'] ?? '')) ?? ''; - - if ($country !== '' && ! str_starts_with($digits, $country)) { - // Drop a single leading trunk '0' before prefixing the country code. - $digits = $country . ltrim($digits, '0'); - } - - return $digits; + try { + $util = PhoneNumberUtil::getInstance(); + $region = $this->config['whatsapp_default_country_region'] ?? null; // e.g. 'US' + $parsed = $util->parse($phone, $region); + + return ltrim($util->format($parsed, PhoneNumberFormat::E164), '+'); + } catch (Throwable $e) { + return ''; + } }Since this introduces a new composer dependency, please confirm it's acceptable to add for this project before adopting.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/Libraries/Whatsapp_lib.php` around lines 206 - 231, The current normalizePhone method in Whatsapp_lib::normalizePhone uses a fragile prefix check and strips all leading zeros, which can produce invalid numbers. Replace the hand-rolled parsing with a robust E.164 formatter such as libphonenumber if adding the dependency is approved, and keep the behavior centralized in normalizePhone. If you do not adopt the library, at minimum change the trunk-prefix handling so only a single leading zero is removed and rework the country-code detection to avoid mistaking local numbers for already-prefixed ones.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/Controllers/Config.php`:
- Around line 596-612: In postSaveWhatsapp, both whatsapp_token and
whatsapp_app_secret are only updated inside the check_encryption() branch, so
when encryption is disabled the submitted values are ignored and the old config
stays in place. Update the logic in this method to read the raw POST values in
an else fallback when check_encryption() is false, storing them as plaintext,
while keeping the existing encrypted path and remove_backup() behavior
unchanged.
In `@app/Controllers/Sales.php`:
- Around line 1048-1061: The temp PDF handling in Sales::getSendPdf() and the
WhatsApp send flow reuses the same deterministic filename, which can cause
concurrent requests to collide and leaves orphaned files behind. Update the PDF
creation/sending path to generate a unique temp filename per request in the
Sales controller before calling create_pdf() and whatsapp_lib->sendDocument(),
and make sure the file is deleted after sendDocument() completes (including
failure paths). Keep the logic localized around the existing $filename,
create_pdf(), and sendDocument() usage so the email and WhatsApp flows no longer
share a writable temp path.
- Around line 1023-1046: The getSendWhatsapp() method is rendering a template
using the user-controlled $type value, which can reach sales/$type_email without
validation. Add a whitelist check in getSendWhatsapp() before the
Services::renderer()->render() call so only the supported sale types used
elsewhere (invoice, quote, receipt, work_order) are allowed, and reject or
default any other value before building the template name.
In `@app/Controllers/Whatsapp_webhook.php`:
- Around line 149-153: The fail-open path in signatureValid() is allowing
unauthenticated webhook payloads to be accepted when appSecret is empty. Update
Whatsapp_webhook::signatureValid() so missing config does not return true;
instead reject the request or short-circuit processing in the webhook handler
before any persistence occurs. Make sure the inbound message/status handling
path in Whatsapp_webhook only inserts into whatsapp_messages or updates statuses
after a successful signature check, with signature verification treated as
mandatory once the feature is enabled.
- Around line 66-74: The webhook signature check in receive() is using the
encrypted whatsapp_app_secret from config directly, so signatureValid() never
sees the real secret. Decrypt whatsapp_app_secret the same way
Whatsapp_lib::token() handles whatsapp_token before passing it into
signatureValid(), and keep the existing invalid-signature handling and logging
intact.
In `@app/Controllers/Whatsapp.php`:
- Around line 74-113: The WhatsApp send actions are sanitizing the outgoing
message with FILTER_SANITIZE_FULL_SPECIAL_CHARS, which converts user-typed text
into HTML entities before it is passed to Whatsapp_lib::sendText and then shown
to recipients. Update postSend and postSend_form to read the message without
HTML entity encoding, keeping only appropriate input validation, so the text is
sent as authored. Make the same adjustment in both controller methods so
outbound messages are not corrupted.
In `@app/Database/Migrations/sqlscripts/initial_schema.sql`:
- Around line 73-82: The baseline schema seeds the WhatsApp config rows but
never creates the backing table, so fresh installs will break when WhatsApp
features reference it. Update the initial_schema.sql migration by adding the
missing ospos_whatsapp_messages CREATE TABLE definition alongside the other
table creation statements, using the same schema conventions as the rest of the
initial setup so the WhatsApp feature can access it on a clean install.
In `@app/Models/Whatsapp_message.php`:
- Around line 78-87: The recent conversation lookup in
get_recent_conversations() is using both phone and person_id as the grouping
key, which splits one conversation into multiple rows when person_id is null for
inbound/outbound WhatsApp messages. Update the query in
Whatsapp_message::get_recent_conversations() to group and aggregate by phone
only, and keep the existing last_activity/message_count ordering so it matches
the conversation semantics used by get_conversation().
In `@app/Views/sales/invoice.php`:
- Around line 56-73: The WhatsApp send action in the invoice view is being
triggered through a GET request, but `sales/sendWhatsapp` is side-effecting and
should not be callable via GET. Update the click handler in `invoice.php` (and
the same `sendWhatsapp` usage in the matching `quote.php`, `receipt.php`, and
`work_order.php` views) to use a POST request with CSRF protection instead of
`$.get`, and disable the `#show_whatsapp_button` after the first click to avoid
duplicate sends from repeated submissions.
- Around line 56-73: The inline WhatsApp request URL in the invoice view is
being echoed without escaping, unlike the matching logic in the sibling views.
Update the `invoice.php` script block around the
`$("`#show_whatsapp_button`").click(...)` handler to wrap the interpolated
`site_url() . "sales/sendWhatsapp/$sale_id_num"` value with `esc()`, keeping the
same behavior while hardening the output consistently with `quote.php`,
`receipt.php`, and `work_order.php`.
In `@app/Views/whatsapp/form_whatsapp.php`:
- Around line 74-83: The `rules.phone` validation in `form_whatsapp.php` is too
strict because `number: true` rejects formatted phone input that
`Whatsapp_lib::normalizePhone()` already cleans up. Update the jQuery Validate
rules in this form to allow common phone formats by removing the numeric-only
restriction and keeping validation aligned with the landing-page form’s phone
field. Ensure the `phone` rule in the form validation block still requires a
value but no longer blocks `+`, spaces, dashes, or parentheses.
---
Nitpick comments:
In `@app/Database/Migrations/20260703000000_AddWhatsappModule.php`:
- Around line 53-71: Add an index for wa_message_id in the whatsapp_messages
table definition. Update the migration’s addKey calls in AddWhatsappModule so
that Whatsapp_message::update_status() can efficiently look up rows by
wa_message_id during inbound status webhook handling; keep the existing keys and
add a dedicated key for that column.
In `@app/Libraries/Whatsapp_lib.php`:
- Around line 206-231: The current normalizePhone method in
Whatsapp_lib::normalizePhone uses a fragile prefix check and strips all leading
zeros, which can produce invalid numbers. Replace the hand-rolled parsing with a
robust E.164 formatter such as libphonenumber if adding the dependency is
approved, and keep the behavior centralized in normalizePhone. If you do not
adopt the library, at minimum change the trunk-prefix handling so only a single
leading zero is removed and rework the country-code detection to avoid mistaking
local numbers for already-prefixed ones.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d62bd686-d9d1-4397-9f04-ac68338516f9
📒 Files selected for processing (23)
app/Config/Filters.phpapp/Config/Routes.phpapp/Controllers/Config.phpapp/Controllers/Sales.phpapp/Controllers/Whatsapp.phpapp/Controllers/Whatsapp_webhook.phpapp/Database/Migrations/20260703000000_AddWhatsappModule.phpapp/Database/Migrations/sqlscripts/initial_schema.sqlapp/Language/en/Config.phpapp/Language/en/Module.phpapp/Language/en/Sales.phpapp/Language/en/Whatsapp.phpapp/Libraries/Whatsapp_lib.phpapp/Models/Whatsapp_message.phpapp/Views/configs/system_config.phpapp/Views/configs/whatsapp_config.phpapp/Views/sales/invoice.phpapp/Views/sales/quote.phpapp/Views/sales/receipt.phpapp/Views/sales/work_order.phpapp/Views/whatsapp/conversation.phpapp/Views/whatsapp/form_whatsapp.phpapp/Views/whatsapp/whatsapp.php
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
app/Controllers/Whatsapp_webhook.php (1)
136-140: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winPrevent status regressions in webhook updates
update_status()overwrites the stored status unconditionally, so a latedeliveredevent can downgrade an alreadyreadmessage. Ignore backward transitions and only persist forward status changes.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/Controllers/Whatsapp_webhook.php` around lines 136 - 140, The webhook status loop in Whatsapp_webhook.php currently calls update_status() for every incoming status and can overwrite a newer state with an older one. Update the logic around update_status() to compare the incoming status against the stored message status and ignore backward transitions, only allowing forward progress such as sent → delivered → read. Keep the fix localized to the foreach over $value['statuses'] and the Whatsapp_message update_status() path so late webhook events cannot downgrade an already read message.
🧹 Nitpick comments (1)
app/Controllers/Sales.php (1)
936-977: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate PDF-generation/token logic between
getSendPdf()andgetSendWhatsapp().The token construction (
Token_invoice_sequence,Token_invoice_count,Token_customer), logo tag setup, andsales/{type}_emailrendering are duplicated almost verbatim betweengetSendPdf()(Lines 936-966) andgetSendWhatsapp()(Lines 1039-1052). Extracting a shared private helper (e.g._render_sale_pdf(array $sale_data, string $type): arrayreturning[html, tempFilePath]or similar) would reduce drift risk if one path is updated without the other.♻️ Suggested extraction
+ private function _render_sale_document(array $sale_data, string $type): string + { + $sale_data['mimetype'] = $this->email_lib->getLogoMimeType(); + $sale_data['img_tag'] = $this->email_lib->buildLogoImgTag(); + + $view = Services::renderer(); + return $view->setData($sale_data)->render("sales/$type" . '_email', $sale_data); + }Both
getSendPdf()andgetSendWhatsapp()can then call$this->_render_sale_document($sale_data, $type)instead of duplicating the render call.Also applies to: 1039-1069
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/Controllers/Sales.php` around lines 936 - 977, The PDF/token rendering flow is duplicated in getSendPdf() and getSendWhatsapp(), including token setup, logo image preparation, and sales/{type}_email rendering. Extract that shared logic into a private helper such as _render_sale_document() or _render_sale_pdf() that takes $sale_data and $type and returns the rendered HTML and any needed temp file data, then have both getSendPdf() and getSendWhatsapp() call the helper to keep the two paths in sync.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@app/Controllers/Whatsapp_webhook.php`:
- Around line 136-140: The webhook status loop in Whatsapp_webhook.php currently
calls update_status() for every incoming status and can overwrite a newer state
with an older one. Update the logic around update_status() to compare the
incoming status against the stored message status and ignore backward
transitions, only allowing forward progress such as sent → delivered → read.
Keep the fix localized to the foreach over $value['statuses'] and the
Whatsapp_message update_status() path so late webhook events cannot downgrade an
already read message.
---
Nitpick comments:
In `@app/Controllers/Sales.php`:
- Around line 936-977: The PDF/token rendering flow is duplicated in
getSendPdf() and getSendWhatsapp(), including token setup, logo image
preparation, and sales/{type}_email rendering. Extract that shared logic into a
private helper such as _render_sale_document() or _render_sale_pdf() that takes
$sale_data and $type and returns the rendered HTML and any needed temp file
data, then have both getSendPdf() and getSendWhatsapp() call the helper to keep
the two paths in sync.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f6b9c5af-4583-4457-8429-48654e713506
📒 Files selected for processing (11)
LICENSEapp/Controllers/Config.phpapp/Controllers/Sales.phpapp/Controllers/Whatsapp.phpapp/Controllers/Whatsapp_webhook.phpapp/Models/Whatsapp_message.phpapp/Views/sales/invoice.phpapp/Views/sales/quote.phpapp/Views/sales/receipt.phpapp/Views/sales/work_order.phpapp/Views/whatsapp/form_whatsapp.php
✅ Files skipped from review due to trivial changes (1)
- LICENSE
🚧 Files skipped from review as they are similar to previous changes (8)
- app/Views/sales/receipt.php
- app/Views/sales/invoice.php
- app/Views/sales/quote.php
- app/Controllers/Config.php
- app/Views/whatsapp/form_whatsapp.php
- app/Models/Whatsapp_message.php
- app/Views/sales/work_order.php
- app/Controllers/Whatsapp.php
…us regressions.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/Models/Whatsapp_message.php`:
- Around line 104-126: The update_status method in Whatsapp_message currently
reads the row and then updates it, which can race and allow older statuses to
overwrite newer ones. Make the transition check atomic by moving the rank
comparison into the whatsapp_messages UPDATE itself or by locking the selected
row before updating, so only forward status changes from sent to delivered to
read can commit. Keep the logic centered in update_status and use the existing
status rank mapping to guard the write.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: c6664af1-432d-434e-9b86-ba98e862467a
📒 Files selected for processing (3)
app/Database/Migrations/20260703000000_AddWhatsappModule.phpapp/Models/Whatsapp_message.phpapp/Views/sales/invoice.php
🚧 Files skipped from review as they are similar to previous changes (2)
- app/Views/sales/invoice.php
- app/Database/Migrations/20260703000000_AddWhatsappModule.php
|
Great work here. I think this is a very useful addition, however, I think this needs to be implemented as a plugin. See #4407 which will be merged shortly after the 3.4.2 release and will be the staple change in the 3.5.0 release. In that PR, you can see how Mailchimp was implemented as a plugin and there is a detailed README.md explaining how to create a plugin. @jekkos, what do you think here? WhatsApp is fairly ubiquitous but this kind of a change fits the mold of a plugin. @jekkos, I think we need to potentially create a repo to store publicly available plugins or potentially a repo for each publicly available plugin. I lean toward the first option, so that publicly shared plugins are stored in the same place. I'm not completely against storing publicly available plugins in this repo, though. However, they do need to be written as plugins, which means not touching the core code. @joshua1234511, if you need to add specific event triggers for this plugin to work, then create a branch from the one in #4407 and submit a PR for the event triggers you want to add. You'll need to potentially add a view trigger, but I think there may already be one exactly where you need it, since I added it for another plugin. |
|
@joshua1234511 the good news is that you've already done the legwork of developing the feature. All that needs to be done now is package it into a plugin and let the plugin system do the injecting. If you get stuck on it, let me know and I can help get you unstuck. If you are using AI to help the development, I would create a branch from #4407, and point your AI at this PR, then tell it to read the README.md and AGENTS.md then turn the changes in this PR into a plugin. That should get you most of the way there. |
Thanks for the feedback and moving this to a plugin makes sense, and I agree it's the better long-term approach. |
|
Thanks @objecttothis — converted this to a plugin as you suggested. Replaced by two PRs so the core changes stay reviewable on their own: #4605 — core enablers: view hooks for the invoice, quote and work order documents, plus a CSRF exemption for plugin webhook routes. The other thing I needed was a way to expose the inbound Meta webhook. A server-to-server callback has no CSRF token and no session, so #4605 exempts plugins/*/webhook from the global filter and the plugin authenticates the caller itself — it verifies Meta's X-Hub-Signature-256 HMAC against the app secret and stores nothing if that fails or if no secret is configured. Everything else moved into the plugin: settings to plugin_config instead of app_config (with the token and app secret encrypted at rest), the conversation table to a plugin migration, the menu entry and permission to registerModule(), the config tab to the plugin's own config view, and the four copies of the button block to a single plugin view. initial_schema.sql is back to untouched. One open question in #4605 that I'd like your and @jekkos's read on: Sales::_load_sale_data() is private, so the plugin has to rebuild the sale document data itself to render the PDF. My version only calls existing public APIs and reimplements no totals or tax logic, but it's still ~80 lines mirroring core and it will drift. If you'd rather core exposed that reusably — a public method, or moved into Sale_lib — I'm happy to add it to #4605 and delete the plugin-side copy. #4606 |



Summary
Adds WhatsApp as a first-class messaging channel alongside SMS and email, using Meta's WhatsApp Business Cloud API. Resolves #922.
Merchants can now configure WhatsApp credentials, send free-form messages to customers, send a bill/invoice PDF over WhatsApp the same way it's emailed today, and view the full conversation (outbound sends + inbound replies) with each customer.
What's included
/whatsapp) — mirrors/messages: send a free-form message, browse recent conversations, and a per-customer modal with the message thread.Key components
app/Libraries/Whatsapp_lib.phpapp/Controllers/Whatsapp.php,app/Views/whatsapp/*app/Controllers/Whatsapp_webhook.phpapp/Models/Whatsapp_message.php, migration20260703000000_AddWhatsappModuleapp/Controllers/Sales.php(getSendWhatsapp) + sale viewsapp/Controllers/Config.php(postSaveWhatsapp)Also: module/permission/grant seeding (migration +
initial_schema.sql), routes + CSRF exemption for the webhook, a menu icon, and English language keys.Security
X-Hub-Signature-256HMAC when an app secret is configured; the verify handshake usestext/plainso nothing is injected into the challenge echo.Testing
whatsapp_messagestable are created./whatsappand the config tab render (HTTP 200), config saves with the token encrypted and round-tripping.success:false), logs the row with Meta's real API error, and does not fatal.php-cs-fixer(CodeIgniter4 standard) and lint.Out of scope (follow-ups)
Screenshots
Summary by CodeRabbit