Frappe WhatsApp

A powerful WhatsApp integration for Frappe/ERPNext that enables seamless messaging capabilities within your business applications.

Features

💬 Two-way Messaging

Send and receive WhatsApp messages directly from your Frappe applications with full conversation tracking.

📋 Template Management

Create and manage WhatsApp Business API templates for consistent and compliant messaging.

🔔 WhatsApp Notifications

Automated WhatsApp messages triggered by DocType events, scheduler events, or date-based conditions.

📤 Bulk Messaging

Send campaigns to recipient lists with variable substitution, progress tracking, and retry support.

🏢 Multi-Account Support

Manage multiple WhatsApp Business accounts with flexible routing for different use cases.

🔄 Webhook Support

Real-time message delivery and status updates through WhatsApp webhook integration.

📊 Message Tracking

Monitor message delivery status, read receipts, and maintain complete conversation history.

🔌 ERPNext Integration

Native integration with ERPNext doctypes for automated notifications and alerts.

📝 WhatsApp Flows

Build interactive forms using WhatsApp's native Flow Builder for rich data collection experiences.

🔘 Interactive Messages

Send button and list messages for quick user responses and improved engagement.

🔄 Sync from Meta

Import and synchronize templates and flows from your Meta Business Account.

Installation

Prerequisites

Install the App

Get the app from the GitHub repository:

bench get-app https://github.com/shridarpatil/frappe_whatsapp.git

Install the app on your site:

bench --site your-site.com install-app frappe_whatsapp

Run migrations:

bench --site your-site.com migrate

Restart bench to load the new app:

bench restart

Note: Make sure your bench is in production mode for webhook support. Development mode may cause issues with webhook verification.

Configuration

WhatsApp Business API Setup

  1. Create a WhatsApp Business account at Meta Business
  2. Set up a WhatsApp Business API application in the Meta Developer Portal
  3. Obtain your Phone Number ID, Business Account ID, and Access Token from the Meta dashboard
  4. Configure webhook URL in the Meta Business platform

WhatsApp Account Setup

Navigate to WhatsApp Account in your Frappe site and create a new account with the following settings:

Setting Description Required
Account Name A friendly name for this WhatsApp account Yes
Token Meta API access token (permanent token recommended) Yes
Phone ID Your WhatsApp Business phone number ID Yes
Business ID Your WhatsApp Business Account ID Yes
App ID Your Meta App ID (for media uploads) Yes
Webhook Verify Token Custom token for webhook verification Yes
URL Meta API base URL (default: https://graph.facebook.com) No
Version API version (default: v17.0) No

Multi-Account Support

You can configure multiple WhatsApp accounts for different purposes:

Note: Only one account can be set as default for each type (incoming/outgoing).

Webhook Configuration

Set up your webhook URL in the Meta Business platform:

https://your-site.com/api/method/frappe_whatsapp.utils.webhook.webhook

Subscribe to the following webhook fields:

Important: Ensure your site is accessible over HTTPS. WhatsApp requires SSL for webhook endpoints.

WhatsApp Notifications

WhatsApp Notifications allow you to automatically send WhatsApp messages based on events in your Frappe/ERPNext system. This is similar to Email Alerts but for WhatsApp.

Creating a Notification

Navigate to WhatsApp Notification and create a new notification with the following settings:

Basic Settings

Field Description
Notification Type Choose between "DocType Event" or "Scheduler Event"
Reference DocType The DocType that triggers this notification (e.g., Sales Order, Lead)
Template The WhatsApp template to send
Field Name The field containing the recipient's phone number

Supported DocType Events

Scheduler Events

For scheduled notifications, choose from these frequencies:

Template Parameters

Map template placeholders to DocType fields using the Fields table:

Template: "Hello {{1}}, your order {{2}} is ready for delivery on {{3}}."

Field Mapping:
- Parameter 1 → customer_name
- Parameter 2 → name (document name/ID)
- Parameter 3 → delivery_date

Conditions

Add Python conditions to control when notifications are sent:

# Only send if order total is above 10000
doc.grand_total > 10000

# Only send for specific customer group
doc.customer_group == "Retail"

# Only send if not already notified
not doc.whatsapp_notified

Attachments

You can attach files to your WhatsApp notifications:

Post-Send Actions

Update a field after the notification is sent (useful for tracking):

Field Description
Set Property After Alert The field to update (e.g., "whatsapp_notified")
Property Value The value to set (e.g., "1" for checkbox)

Interactive Buttons

Map DocType fields to dynamic button URLs in your templates:

Button URL Template: https://yoursite.com/orders/{{1}}
Button Field Mapping: name (document ID)

Custom Data List

For advanced use cases, you can send templates using custom data instead of DocType fields by setting _data_list:

# In your condition or server script
doc.set("_data_list", [
    {
        "phone": "+1234567890",
        "customer_name": "John Doe",
        "order_id": "ORD-001"
    },
    {
        "phone": "+0987654321",
        "customer_name": "Jane Smith",
        "order_id": "ORD-002"
    }
])

Bulk WhatsApp Messaging

Send WhatsApp messages to multiple recipients at once using templates. Ideal for marketing campaigns, announcements, and batch notifications.

Creating a Bulk Message

Navigate to Bulk WhatsApp Message and create a new document:

Basic Settings

Field Description
Title A name for this bulk message campaign
WhatsApp Account Select which WhatsApp account to use for sending
Template The approved WhatsApp template to send
Recipient Type "Individual" for direct entry or "Recipient List" for pre-configured lists

Recipient Types

1. Individual Recipients

Add recipients directly in the document. Each recipient can have:

2. Recipient List

Use a pre-configured WhatsApp Recipient List that can be reused across campaigns.

Creating a Recipient List

Navigate to WhatsApp Recipient List to create reusable recipient groups:

Import from DocType

Import recipients from any DocType (Customer, Contact, Lead, etc.):

  1. Click "Import from DocType"
  2. Select the DocType (e.g., "Customer")
  3. Map the phone field (e.g., "mobile_no")
  4. Optionally add filters and additional data fields
Example: Import all retail customers
DocType: Customer
Phone Field: mobile_no
Name Field: customer_name
Filters: {"customer_group": "Retail"}
Data Fields: ["customer_name", "territory"]

Template Variables

Variable Types

Type Description Use Case
Common Same values for all recipients Sale announcements, company updates
Unique Different values per recipient Personalized messages, order updates

Using Unique Variables

Store recipient-specific data in the recipient_data JSON field:

{
    "customer_name": "John Doe",
    "order_id": "ORD-001",
    "delivery_date": "2024-01-15"
}

Message Workflow

  1. Draft - Configure recipients and template
  2. Submit - Messages are queued for background processing
  3. In Progress - Messages are being sent
  4. Completed - All messages sent successfully
  5. Partially Failed - Some messages failed (can retry)

Progress Tracking

Monitor your bulk message progress:

Retrying Failed Messages

If some messages fail, you can retry them:

  1. Open the Bulk WhatsApp Message document
  2. Click "Retry Failed" button
  3. Failed messages will be requeued for sending

Attachments

Attach media files to your bulk messages:

Rate Limits: WhatsApp has rate limits on message sending. For large campaigns, messages are processed in the background queue to avoid hitting these limits.

Template Management

WhatsApp templates are pre-approved message formats required for initiating conversations outside the 24-hour window.

Creating Templates

Navigate to WhatsApp Templates to create and manage templates:

Template Components

Component Description
Template Name Unique identifier (lowercase, underscores only)
Language Code Template language (e.g., en, en_US)
Header Optional header (TEXT, IMAGE, or DOCUMENT)
Body Main message content with placeholders ({{1}}, {{2}}, etc.)
Footer Optional footer text
Buttons Interactive buttons (Quick Reply, Call, URL)

Button Types

Syncing Templates

Fetch templates from Meta to sync approval status:

  1. Open WhatsApp Templates list
  2. Click "Fetch Templates" button
  3. Templates will be synced from all active WhatsApp accounts

Template Status

Tip: Templates must be approved by Meta before they can be used. This typically takes 24-48 hours.

Interactive Messages

Send interactive button and list messages for quick user responses and improved engagement.

Button Messages

Button messages allow users to respond with a single tap:

List Messages

List messages provide a menu-style interface:

Sending Interactive Messages

Set the content_type field when creating a WhatsApp Message:

# Button message
message = frappe.get_doc({
    "doctype": "WhatsApp Message",
    "to": "+1234567890",
    "content_type": "button",
    "message": "Please choose an option:",
    "buttons": [
        {"type": "button", "title": "Option 1", "id": "btn_1"},
        {"type": "button", "title": "Option 2", "id": "btn_2"},
        {"type": "button", "title": "Option 3", "id": "btn_3"}
    ]
})
message.insert()

WhatsApp Flows

Build interactive forms using WhatsApp's native Flow Builder. Flows provide a rich UI experience for collecting structured data from users.

Features

Creating a Flow

Navigate to WhatsApp Flow to create a new flow:

  1. Enter a Flow Name
  2. Select the WhatsApp Account
  3. Choose a Category (e.g., APPOINTMENT_BOOKING, LEAD_GENERATION)
  4. Add Screens to define the flow structure
  5. Add Fields for each screen

Supported Field Types

Field Type Description
TextInput Single-line text input
TextArea Multi-line text input
Dropdown Select from predefined options
DatePicker Date selection
RadioButtonsGroup Single selection from radio buttons
CheckboxGroup Multiple selection checkboxes
OptIn Consent checkbox
TextHeading Display heading text
TextBody Display body text

Flow Actions

Available actions from the WhatsApp Flow form:

Sending Flow Messages

# Send a flow message
message = frappe.get_doc({
    "doctype": "WhatsApp Message",
    "to": "+1234567890",
    "content_type": "flow",
    "flow": "My Booking Flow",  # Link to WhatsApp Flow
    "flow_cta": "Open Booking Form",
    "message": "Please fill out the booking form below"
})
message.insert()

Note: Draft flows can only be tested with phone numbers registered as test numbers in the Meta Business Manager. Published flows are available to all users.

Sync from Meta

Keep your Frappe data synchronized with your Meta Business Account.

Syncing Templates

  1. Go to WhatsApp Templates list view
  2. Click the Sync from Meta button
  3. All templates from active WhatsApp accounts are imported/updated

The sync will:

Syncing Flows

  1. Go to WhatsApp Flow list view
  2. Click the Sync from Meta button
  3. Select the WhatsApp Account to sync from
  4. All flows are imported/updated

The sync will:

Tip: Use bulk sync to quickly import all flows and templates after setting up a new WhatsApp Account.

API Documentation

POST /api/method/frappe_whatsapp.api.send_message

Send a WhatsApp message to a recipient.

Request Body

{
    "to": "+1234567890",
    "message": "Hello from Frappe WhatsApp!",
    "template": "order_confirmation",  // optional
    "parameters": ["ORD-001", "John Doe"]  // optional
}
GET /api/method/frappe_whatsapp.api.get_message_status

Get the delivery status of a sent message.

Query Parameters

  • message_id - WhatsApp message ID
POST /api/method/frappe_whatsapp.webhook

Webhook endpoint for receiving WhatsApp messages and status updates. This is automatically handled by the app.

Examples

Python API Usage

Send a simple text message:

import frappe
from frappe_whatsapp.api import send_whatsapp_message

# Send a text message
response = send_whatsapp_message(
    to="+1234567890",
    message="Hello! Your order has been confirmed."
)

print(f"Message ID: {response.get('message_id')}")

Send a template message with parameters:

from frappe_whatsapp.api import send_whatsapp_message

# Send template message
response = send_whatsapp_message(
    to="+1234567890",
    template="order_shipped",
    parameters=[
        "ORD-12345",           # Order number
        "John Doe",            # Customer name
        "2024-01-15",         # Delivery date
        "https://track.example.com/ORD-12345"  # Tracking URL
    ]
)

Server Script Example

Automatically send WhatsApp notification on Sales Order submission:

# Server Script - On Submit
if doc.doctype == "Sales Order" and doc.customer_whatsapp:
    from frappe_whatsapp.api import send_whatsapp_message
    
    send_whatsapp_message(
        to=doc.customer_whatsapp,
        template="order_confirmation",
        parameters=[
            doc.name,
            doc.customer_name,
            str(doc.grand_total),
            doc.delivery_date.strftime("%B %d, %Y")
        ]
    )

Handling Incoming Messages

Process incoming WhatsApp messages using hooks:

# In your app's hooks.py
doc_events = {
    "WhatsApp Message": {
        "after_insert": "your_app.utils.process_whatsapp_message"
    }
}

# In your_app/utils.py
def process_whatsapp_message(doc, method):
    if doc.message_type == "received":
        # Process incoming message
        if "order status" in doc.message.lower():
            # Send automated response
            send_order_status(doc.from_number)

Troubleshooting

Common Issues

Webhook Verification Failed

Messages Not Sending

Template Messages Not Working

Debug Mode: Enable debug mode in WhatsApp Settings to log detailed API requests and responses for troubleshooting.

Contributing

We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is licensed under the MIT License. See the LICENSE file for details.