Skip to main content

WhatsApp Integration Guide

NeuraFlow integrates with WhatsApp Business API via Meta Cloud API. Organizations can connect their WhatsApp Business numbers to NeuraFlow agent flows using Facebook's Embedded Signup flow.


Overview

Architecture Components


Facebook App Setup

Step 1: Create Facebook App

FieldValue
App TypeBusiness
App NameNeuraFlow WhatsApp Connector
App PurposeCustomer engagement
Business PortfolioYour Business Account

Step 2: Add WhatsApp Product

Navigate to App DashboardAdd ProductsWhatsApp

Configure WhatsApp Business API access:

  • Create or link WhatsApp Business Account (WABA)
  • Add phone numbers
  • Configure webhook

Step 3: Configure Webhook

FieldValue
Callback URLhttps://neuraflow.brainstation23.com/api/v1/webhooks/whatsapp
Verify Token<custom-verification-token> (stored in integration)
Webhook Fieldsmessages

Required Webhook Subscriptions:

  • messages - Receive incoming messages

Step 4: Generate System User Access Token

Navigate to Business SettingsSystem UsersGenerate Token

FieldValue
Token Permissionswhatsapp_business_messaging, whatsapp_business_management
ExpirationNever (for production) or 60 days (for testing)

WhatsApp Embedded Signup

WhatsApp Embedded Signup enables customers to connect their WhatsApp Business numbers directly from NeuraFlow UI without leaving the platform.

Embedded Signup Flow

Required Environment Variables

# Facebook App Configuration
VITE_FB_APP_ID=<your-facebook-app-id>
VITE_FB_CONFIG_ID=<embedded-signup-config-id>

Frontend Implementation

The embedded signup is implemented using Facebook SDK:

// console/src/features/channels/whatsapp/components/embedded-signup.tsx
window.FB.login(callback, {
config_id: configId,
response_type: 'code',
override_default_response_type: true,
extras: { setup: {} }
})

Session Logging: The component listens for WA_EMBEDDED_SIGNUP message events from Facebook to track signup progress.


Integration Data Model

WhatsApp Integration Fields

FieldTypeDescriptionRequired
organization_idUUIDOrganization ownerOptional
agent_flow_idUUIDConnected agent flowYes
phone_numberStringDisplay number (e.g., +1-555-555-5555)No
phone_number_idStringMeta Phone Number IDYes
waba_idStringWhatsApp Business Account IDYes
access_tokenTextSystem User Access Token (encrypted)Yes
verify_tokenStringWebhook verification tokenYes
enabledBooleanIntegration statusYes

Security Considerations

  • ✅ Access tokens should be encrypted at rest
  • ✅ Verify tokens must be unique per integration
  • ✅ Webhook signature validation (optional but recommended)
  • ✅ Rate limiting on webhook endpoints

Message Flow

Incoming Message Flow

Webhook Verification

Message Processing

Supported Message Types:

  • text - Text messages
  • ⏸️ image - Images (planned)
  • ⏸️ document - Documents (planned)
  • ⏸️ audio - Voice messages (planned)

Status Updates:

  • read - Message read receipts (sent automatically)
  • delivered - Delivery confirmations (received, not processed)
  • sent - Message sent confirmations (received, not processed)

Developer Setup (Brain Station 23)

Prerequisites

RequirementDetails
Meta Business AccountRequired for creating Facebook Apps
Meta Developer AccountAccess to App Dashboard
WhatsApp Business AccountCreated during Embedded Signup or pre-existing
SSL CertificateRequired for webhook HTTPS endpoint

Step 1: Create Facebook App

  1. Go to Facebook Developers
  2. Create new Business App
  3. Add WhatsApp product
  4. Note the App ID and App Secret

Step 2: Configure Embedded Signup

  1. Navigate to WhatsAppConfiguration
  2. Click Embedded Signup
  3. Create configuration
  4. Note the Config ID
  5. Add redirect URL: https://neuraflow.brainstation23.com

Step 3: Set Environment Variables

Backend (core/.env):

# WhatsApp/Facebook Configuration
FB_APP_ID=<facebook-app-id>
FB_APP_SECRET=<facebook-app-secret>
FB_API_VERSION=v24.0

Frontend (console/.env):

# Facebook SDK
VITE_FB_APP_ID=<facebook-app-id>
VITE_FB_CONFIG_ID=<embedded-signup-config-id>

Step 4: Configure Webhook Endpoint

NeuraFlow Webhook URL:

https://neuraflow.brainstation23.com/api/v1/webhooks/whatsapp

Webhook Fields to Subscribe:

  • messages - Incoming messages

Verification:

  • Each integration has its own verify_token
  • During webhook verification, Meta sends a GET request with the token
  • NeuraFlow validates against stored integrations

Customer Onboarding

Prerequisites

RequirementDetails
Facebook Business AccountRequired for WhatsApp Business
WhatsApp Business NumberPhone number to connect (can be obtained during signup)
NeuraFlow AccountOrganization created with agent flows
Admin AccessPermission to manage integrations

Onboarding Flow

Step-by-Step Guide

1. Create Agent Flow

  1. Log into NeuraFlow
  2. Navigate to Agent Flows
  3. Create or select an existing flow
  4. Configure flow nodes and responses

2. WhatsApp Embedded Signup

  1. Navigate to ChannelsWhatsApp
  2. Click Login with Facebook
  3. Facebook login popup appears
  4. Log in with Facebook Business Manager account
  5. Select WhatsApp Business Account (or create new)
  6. Select phone number (or add new)
  7. Grant permissions
  8. Receive authorization code

3. Connect Number

  1. System automatically exchanges code for access token
  2. Integration created with:
    • Phone Number ID
    • WhatsApp Business Account ID
    • Access Token (encrypted)
  3. Configure verify token for webhook
  4. Select agent flow to connect
  5. Click Create Integration

4. Test Integration

  1. Send test message to WhatsApp number
  2. Verify webhook receives message
  3. Check conversation created in NeuraFlow
  4. Confirm agent flow response

Use Cases

Use Case 1: Customer Support Bot

Enable automated customer support via WhatsApp.

Benefits:

  • 24/7 availability
  • Instant responses
  • Multi-language support
  • Conversation history

Use Case 2: Appointment Booking

Allow customers to book appointments via WhatsApp chat.

Flow Example:

  1. Customer: "I want to book an appointment"
  2. Bot: "What date works for you?"
  3. Customer: "Tomorrow at 2pm"
  4. Bot: "Confirmed! Appointment booked for [date] at 2:00 PM"

Use Case 3: Order Status Updates

Proactive order status notifications.

Flow Example:

  • Order placed → WhatsApp notification
  • Order shipped → Tracking link via WhatsApp
  • Delivered → Confirmation message

API Endpoints

Integration Management

Create Integration

POST /api/v1/channels/whatsapp/integrations
Content-Type: application/json

{
"agent_flow_id": "uuid",
"organization_id": "uuid",
"phone_number": "+1-555-555-5555",
"phone_number_id": "123456789",
"waba_id": "987654321",
"access_token": "EAAxxxxx...",
"verify_token": "my-verify-token-123",
"enabled": true
}

List Integrations

GET /api/v1/channels/whatsapp/integrations

Update Integration

PUT /api/v1/channels/whatsapp/integrations/{integration_id}
Content-Type: application/json

{
"enabled": false,
"agent_flow_id": "new-uuid"
}

Delete Integration

DELETE /api/v1/channels/whatsapp/integrations/{integration_id}

Webhook Endpoints

Webhook Verification

GET /api/v1/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=TOKEN&hub.challenge=CHALLENGE

Receive Messages

POST /api/v1/webhooks/whatsapp
Content-Type: application/json

{
"object": "whatsapp_business_account",
"entry": [{
"changes": [{
"value": {
"messaging_product": "whatsapp",
"metadata": {
"phone_number_id": "123456789",
"display_phone_number": "+1-555-555-5555"
},
"messages": [{
"from": "15555555555",
"id": "wamid.xxx",
"timestamp": "1234567890",
"type": "text",
"text": {
"body": "Hello"
}
}]
}
}]
}]
}

Troubleshooting

"Webhook verification failed"

CauseSolution
Wrong verify tokenCheck token matches integration
Integration disabledEnable integration
No matching integrationCreate integration first
Network/firewall issuesVerify webhook URL is accessible

"Messages not received"

CauseSolution
Webhook not subscribedSubscribe to messages field in App Dashboard
Wrong phone number IDVerify phone_number_id matches Meta configuration
Integration disabledEnable integration in NeuraFlow
Certificate issuesEnsure HTTPS with valid SSL

"Facebook login fails"

CauseSolution
Wrong App IDVerify VITE_FB_APP_ID matches Facebook App
Wrong Config IDVerify VITE_FB_CONFIG_ID matches Embedded Signup config
Permissions missingGrant WhatsApp Business permissions
Popup blockedAllow popups for NeuraFlow domain

"OAuth code exchange fails"

CauseSolution
Invalid authorization codeCode expires quickly, retry signup
Wrong App SecretVerify FB_APP_SECRET matches Facebook App
Network timeoutRetry request

"Messages sent but not delivered"

CauseSolution
Invalid access tokenRegenerate token, token may have expired
Phone number not verifiedVerify number in Meta Business Suite
Rate limits exceededImplement exponential backoff
Message template requiredFor first message in 24h window, use template

WhatsApp Business API Limits

Message Sending Limits

WhatsApp enforces quality-based rate limits:

TierLimitHow to Increase
Tier 11,000 unique users/dayInitial tier
Tier 210,000 unique users/dayMaintain quality rating
Tier 3100,000 unique users/dayMaintain quality rating
UnlimitedNo limitApply for enterprise

Quality Rating Factors:

  • User blocks
  • Reports
  • User feedback
  • User engagement

24-Hour Session Window

  • User-initiated: Customer sends message → 24-hour window opens
  • Business-initiated: Requires approved message template
  • Within window: Free-form messages allowed

Quick Reference

Meta Configuration URLs

ResourceURL
App Dashboardhttps://developers.facebook.com/apps/{app_id}
Business Settingshttps://business.facebook.com/settings
WhatsApp Managerhttps://business.facebook.com/wa/manage
Embedded Signup ConfigApp Dashboard → WhatsApp → Configuration → Embedded Signup

Required IDs

IDWhere to FindExample
App IDApp Dashboard → Settings → Basic123456789012345
Config IDWhatsApp → Configuration → Embedded Signupconfig-id-123
Phone Number IDWhatsApp Manager → Phone Numbers123456789
WABA IDWhatsApp Manager → Account Info987654321

Webhook Events

EventDescriptionAction
messagesIncoming messageProcess and respond
message_statusDelivery statusLog for analytics
account_updateAccount changesUpdate integration

Message Templates

For business-initiated conversations, use approved templates:

# Example: Send template via API
curl -X POST "https://graph.facebook.com/v24.0/{phone_number_id}/messages" \
-H "Authorization: Bearer {access_token}" \
-H "Content-Type: application/json" \
-d '{
"messaging_product": "whatsapp",
"to": "15555555555",
"type": "template",
"template": {
"name": "hello_world",
"language": { "code": "en_US" }
}
}'

Security Best Practices

Token Security

# ✅ DO: Encrypt access tokens
from cryptography.fernet import Fernet

cipher_suite = Fernet(encryption_key)
encrypted_token = cipher_suite.encrypt(access_token.encode())

# ❌ DON'T: Store plain text tokens
access_token = "EAAxxxxx..." # Stored directly in database

Webhook Validation

# ✅ DO: Validate webhook signatures (recommended)
import hmac
import hashlib

def validate_signature(payload, signature, app_secret):
expected = hmac.new(
app_secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)

# Validate before processing
if not validate_signature(body, request.headers.get('X-Hub-Signature-256'), FB_APP_SECRET):
raise HTTPException(403, "Invalid signature")

Rate Limiting

# ✅ DO: Implement rate limiting on webhook
from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)

@router.post("/webhooks/whatsapp")
@limiter.limit("100/minute")
async def receive_message(request: Request):
# Process message
pass


Appendix: Code References

Backend Files

FilePurpose
core/app/models/whatsapp_integration.pyData model for integrations
core/app/schemas/whatsapp_channel.pyAPI request/response schemas
core/app/api/v1/whatsapp_channel.pyWebhook and API endpoints
core/app/repositories/whatsapp_repository.pyDatabase operations
core/app/services/channels/whatsapp/adapter.pyWhatsApp message adapter

Frontend Files

FilePurpose
console/src/features/channels/whatsapp/index.tsxMain WhatsApp page
console/src/features/channels/whatsapp/components/embedded-signup.tsxFacebook Embedded Signup
console/src/features/channels/whatsapp/components/create-integration-dialog.tsxCreate integration form
console/src/features/channels/whatsapp/components/integration-list.tsxList of integrations

Database Migration

# Migration file
core/alembic/versions/20260127_1055_9fd994d00236_add_whatsapp_integration.py

Support

For issues or questions: