Build a WhatsApp Coexistence Sync Monitor in Python
WhatsApp coexistence lets a team use the WhatsApp Business app and the WhatsApp Business API on the same phone number. That is useful when human agents handle sensitive or unusual conversations in the app while automated systems send reminders and updates through the API. It also creates a synchronization problem: when a human sends a message in the Business app, the API-side application needs a…
WhatsApp coexistence enables a team to utilize both the WhatsApp Business app and API on the same phone number. This is valuable for human agents managing sensitive or unusual conversations in the app, while automated systems handle reminders and updates via the API. However, this setup presents a synchronization challenge: when a human sends a message through the Business app, the API-side application requires a reliable method to learn about the event.
The whatsapp-coexistence-sync-monitor example addresses this issue. It is a Python Flask service that bridges the gap between the two systems.
The sample application checks Telnyx webhook signatures before parsing an event. It receives message.echo events generated by Business-app activity and ensures that only events from an active coexistence state are acknowledged, while skipping events during inactive periods. Accepted events are then written to a PII-minimized JSONL audit trail.
The Flask webhook receiver, defined at POST /webhooks/whatsapp/echo, first verifies the telnyx-signature-ed25519 and telnyx-timestamp headers. If the signature is missing, malformed, stale, or invalid, the service returns a 401 response without processing the payload. The timestamp window helps reject replayed requests.
Before processing the event, the monitor checks the number's coexistence state. If the number is not registered on the WhatsApp Business app or the coexistence_state is not active, the monitor returns a 200 response without logging the event. In live mode, the StateChecker retrieves the configured number from the WhatsApp Business Account.
The result is cached for 60 seconds to avoid repeated lifecycle requests during a burst of echo webhooks. For local exploration, the service uses DEMO_MODE to replace live requests with simulated active state, without disabling webhook signature verification.
If the number is active, the handler checks if the event's origin matches the WhatsApp Business app and retrieves the message cost. If the cost is not available or is None, the event is deemed to have no charge.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to