NEXEVES Mega Menu

Integration of ERPNext with WhatsApp

 · 9 min read

Integration of ERPNext with WhatsApp (Technical Guide) ERPNext Illustration

Integrating ERPNext with WhatsApp enables companies to automate notifications, send invoices, share order updates, and provide real-time customer support. This technical guide explains how ERPNext can connect with WhatsApp Cloud API, including setup, authentication, message templates, workflows, and automation using server scripts.

1. Introduction

WhatsApp is one of the most widely used communication platforms for customers. Integrating it with ERPNext allows you to turn ERP events (Sales Orders, Invoices, Support Tickets, Delivery Notes, etc.) into instant WhatsApp messages. Using the WhatsApp Cloud API from Meta, ERPNext can send and, optionally, receive messages, making your ERP system a central hub for customer communication and automation.

2. What You Can Automate with WhatsApp + ERPNext

WhatsApp integration with ERPNext is not just for basic notifications. You can design full communication workflows for sales, support, collections, and delivery. The table below shows some common automation possibilities:

Automation Description
Sales Notifications Automatically send Sales Order or Sales Invoice details to customers when submitted.
Payment Alerts Send payment due reminders, payment received confirmations, and follow-ups.
Ticket Updates Notify customers when a support ticket is created, assigned, or resolved.
Delivery Updates Send dispatch and tracking updates when Delivery Notes are submitted.
WhatsApp Chatbot Build simple command-based chatbots to fetch order status or create tickets.

3. System Requirements

Before starting the integration, make sure your ERPNext and environment support the required components.

Component Requirement
ERPNext Version Any recent stable version (v14, v15, v16) with Frappe framework support.
API Type Meta WhatsApp Cloud API (Graph API).
Account Facebook (Meta) Developer Account with WhatsApp Business setup.
Access WhatsApp Business Phone Number ID and Access Token.
Skills Needed Knowledge of Python, Frappe Server Scripts, REST API, and basic JSON handling.

4. WhatsApp Cloud API Architecture

The WhatsApp Cloud API is exposed via HTTP endpoints (Graph API). ERPNext acts as a client that calls these endpoints whenever a specific event takes place in the system. Optionally, you can configure Webhooks so that WhatsApp sends incoming messages back into ERPNext.

ERPNext (Event: SO/Invoice/Ticket) ↓ Server Script / Python Method (in Custom App) ↓ WhatsApp Cloud API (HTTP POST) ↓ WhatsApp Message to Customer Customer Reply (Optional) ↓ WhatsApp Webhook → ERPNext Endpoint ↓ Create Ticket / Log Message / Trigger Workflow

5. Step-by-Step WhatsApp Cloud API Setup

Follow these steps to configure the WhatsApp Cloud API in Meta (Facebook Developer Console).

Step 1: Create a Meta Developer Account

  1. Go to the Meta developer portal (developer.facebook.com).
  2. Log in with your Facebook account.
  3. Navigate to “My Apps” and click “Create App”.

Step 2: Add WhatsApp Product

  1. Select the appropriate app type (usually “Other”).
  2. Choose “WhatsApp” as the product to add to your app.
  3. Complete basic setup and confirm your Business Account.

Step 3: Generate Access Token

  1. In the WhatsApp product section, go to “API Setup”.
  2. Get the temporary token first and test with Meta’s test phone number.
  3. Generate a permanent access token with the required permissions.

Step 4: Collect Required Credentials

You will need the following information to configure ERPNext:

  • Phone Number ID
  • WhatsApp Business Account ID
  • Permanent Access Token
  • Graph API Endpoint Version (for example, v17.0)

6. Saving WhatsApp Credentials in ERPNext

Create a custom Single Doctype in ERPNext named WhatsApp Settings to store credentials. Using a Single Doctype makes it easy to access settings across scripts.

Field Name Field Type Description / Value
Token Password Permanent Access Token from Meta.
Phone Number ID Data Phone Number ID used by WhatsApp API.
WhatsApp Business ID Data WhatsApp Business Account ID.
Default Country Code Data Optional. Used for formatting phone numbers (e.g., 91 for India).

7. Sending a Test Message from ERPNext

Once the credentials are saved, create a Server Script to send a simple text message using WhatsApp Cloud API. This helps validate connectivity and token configuration.

Example: Server Script (API Type)

import requests
import frappe

@frappe.whitelist()
def send_whatsapp_test(phone, msg):
    settings = frappe.get_single("WhatsApp Settings")

    url = f"https://graph.facebook.com/v17.0/{settings.phone_number_id}/messages"

    payload = {
        "messaging_product": "whatsapp",
        "to": phone,
        "type": "text",
        "text": {"body": msg}
    }

    headers = {
        "Authorization": f"Bearer {settings.token}",
        "Content-Type": "application/json"
    }

    response = requests.post(url, json=payload, headers=headers)
    return response.json()

You can test this by calling the whitelisted function from the browser console or a simple Custom Button on any doctype.

8. Creating WhatsApp Templates

For outbound messages (especially marketing or notification type), Meta requires pre-approved message templates. These templates define the structure and variables used in messages.

Template Type Example Content
Order Update "Your order {{1}} is confirmed and will be shipped by {{2}}."
Invoice Share "Your invoice {{1}} is generated. Total amount: {{2}}."
Payment Reminder "Reminder: Your payment of {{1}} for invoice {{2}} is due on {{3}}."
Support Ticket "Your support ticket {{1}} has been created. Our team will contact you shortly."

9. Mapping Templates Inside ERPNext

To reuse templates easily, you can create a child table in WhatsApp Settings called WhatsApp Template Mapping. This mapping allows you to link a template name used in ERPNext to the actual template name on Meta.

Field Description
ERP Template Name Friendly name used internally (e.g., Order_Confirmation).
Meta Template Name Name registered in Meta (e.g., order_confirmation).
Number of Parameters How many placeholders ({{1}}, {{2}}, etc.) are used.
Language Template language (e.g., en, en_US, etc.).

10. Auto-Send WhatsApp Message After Sales Order Submission

A common use case is to send a WhatsApp message when a Sales Order is submitted. You can configure this using a Server Script with the event After Submit on the Sales Order doctype.

Workflow

User Creates Sales Order → User Clicks Submit ↓ ERPNext Validates and Saves Document ↓ Server Script Triggered (After Submit Event) ↓ Script Reads Customer WhatsApp Number + Template ↓ Script Calls WhatsApp Cloud API ↓ Customer Receives Order Confirmation on WhatsApp

Example: Event-Based Server Script

if doc.get("customer_mobile"):
    frappe.call(
        "your_app.whatsapp_api.send_template_message",
        {
            "phone": doc.customer_mobile,
            "template": "Order_Confirmation",
            "params": [doc.name, doc.transaction_date]
        }
    )

The above code assumes you have a helper method send_template_message defined in your custom app that constructs the payload and calls the WhatsApp API.

11. Adding Customer WhatsApp Field

To ensure every customer has a WhatsApp number linked, you can add a custom field in the Customer doctype.

Field Label Field Type Notes
WhatsApp Number Data Store full number with country code (e.g., 9198xxxxxx).
Is WhatsApp Enabled? Check Optional field to indicate that this customer wants WhatsApp communication.

You can fetch this field into Sales Order, Sales Invoice, and other transaction doctypes for easy access while sending messages.

12. Creating a Custom WhatsApp Log Doctype

Logging WhatsApp requests and responses is essential for debugging and audit trails. Create a doctype like WhatsApp Log to store message status.

Field Type Description
Message ID Data Unique message identifier returned by WhatsApp.
To Number Data Customer WhatsApp number.
Payload Long Text JSON request payload sent to WhatsApp.
Response Long Text JSON response received from WhatsApp.
Status Select Sent / Delivered / Failed / Pending.
Error Data Error code or message (if any).

13. Sending PDF (Invoice / Sales Order / Delivery Note)

In many cases, you will want to send the actual document (e.g., invoice PDF) via WhatsApp. You can generate the PDF using ERPNext's print engine and then send it using the WhatsApp Cloud API document type.

Steps to Send a PDF

  1. Generate the PDF with frappe.attach_print.
  2. Convert the file data to Base64 string if required (for some flows).
  3. Prepare the WhatsApp document payload.
  4. Call the API endpoint with the prepared payload.

Example: Python Snippet

import base64
import requests
import frappe

def send_invoice_pdf_via_whatsapp(doc):
    settings = frappe.get_single("WhatsApp Settings")

    pdf_file = frappe.attach_print("Sales Invoice", doc.name, print_format="Standard")
    filedata = base64.b64encode(pdf_file[1]).decode()

    url = f"https://graph.facebook.com/v17.0/{settings.phone_number_id}/messages"

    payload = {
        "messaging_product": "whatsapp",
        "to": doc.customer_mobile,
        "type": "document",
        "document": {
            "filename": f"{doc.name}.pdf",
            "document": filedata,
            "caption": f"Your Invoice {doc.name}"
        }
    }

    headers = {
        "Authorization": f"Bearer {settings.token}",
        "Content-Type": "application/json"
    }

    response = requests.post(url, json=payload, headers=headers)
    return response.json()

14. Creating a WhatsApp Button in ERPNext Forms

You can add a custom button on forms like Sales Invoice so that users can manually trigger WhatsApp messages from the ERPNext UI.

Client Script Example for Sales Invoice

frappe.ui.form.on("Sales Invoice", {
    refresh(frm) {
        if (!frm.doc.__islocal && frm.doc.customer_mobile) {
            frm.add_custom_button("Send WhatsApp", () => {
                frappe.call({
                    method: "my_app.whatsapp.send_invoice",
                    args: { name: frm.doc.name },
                    callback: function(r) {
                        if (r.message) {
                            frappe.msgprint("WhatsApp message sent.");
                        }
                    }
                });
            });
        }
    }
});

15. Automatic Payment Reminder System

You can configure a Scheduled Job to run daily and find pending invoices which are overdue or close to the due date, then send WhatsApp reminders automatically.

Reminder Criteria Example

Condition Action
Invoice Overdue by > 0 Days Send first reminder WhatsApp template.
Invoice Overdue by > 7 Days Send escalation reminder template.
Invoice Due in 3 Days Send upcoming due date reminder.
Payment Received Send thank you / acknowledgment message.

16. WhatsApp Webhook Integration (Optional)

If you want to receive replies from customers and push them into ERPNext, configure a Webhook endpoint in your Meta settings. This endpoint will be a whitelisted method in ERPNext or an API route in your custom app.

High-Level Webhook Workflow

Customer Sends WhatsApp Message ↓ Meta WhatsApp Cloud API Webhook ↓ Your ERPNext Endpoint (Webhook URL) ↓ Parse JSON Payload ↓ Create or Update Document (e.g., Support Ticket, WhatsApp Log)

17. Auto-Create Support Ticket from WhatsApp

One powerful use case is converting incoming WhatsApp messages into support tickets in ERPNext.

Example Mapping

Customer Message Pattern ERPNext Action
Any new incoming message from unknown or known number Create a new Support Ticket with the message as the description.
Message contains "status" and an order number Fetch order status and send WhatsApp reply.
Message contains "help" or "support" Create a high priority support ticket and notify the team.

18. WhatsApp Chatbot Inside ERPNext

You can create a simple rule-based chatbot using Python to respond to specific commands sent by customers. The logic can reside in your webhook handler.

Simple Command Examples

Customer Command System Response
STATUS SO-0001 Fetch Sales Order SO-0001 and send its status (e.g., To Deliver, Completed).
INVOICE INV-0005 Send summary of invoice INV-0005 and PDF via WhatsApp.
SUPPORT Create a support ticket and send ticket ID to the customer.

19. Error Handling & Logging

Proper error handling ensures that failures are visible and can be corrected quickly. Whenever you call the WhatsApp API, you should capture the HTTP status code and error message from the response and store them in the WhatsApp Log.

Common Error Types

Error Code (Example) Meaning Resolution
400 / 401 Authorization failed or bad request. Check access token, header format, and JSON payload.
470 Template not approved or incorrect template name. Verify that the template is approved and names match exactly.
131021 Invalid phone number format. Ensure correct country code and number format.
500 Internal server error at API side. Retry after some time or log for review.

20. Security Best Practices

Since WhatsApp integration deals with tokens and customer contact data, security should be treated seriously.

  • Store the access token in a Password field in Single Doctype.
  • Limit access to WhatsApp Settings to system managers or admins only.
  • Do not log tokens in plain text anywhere (logs, print statements, etc.).
  • Use whitelisted methods only where necessary, and restrict them via role permissions.
  • Rotate tokens periodically and update ERPNext settings accordingly.

21. Performance Optimization

For high message volumes, sending WhatsApp messages synchronously can slow down user operations. Offload heavy work to background jobs.

  • Use frappe.enqueue to send messages asynchronously in the background.
  • Batch sending notifications where possible, instead of per-row operations.
  • Compress or optimize PDFs to reduce file size before sending.
  • Monitor queue workers and scale up if message volume increases.

22. Real Business Use Cases

Different industries can leverage WhatsApp integration in ERPNext in different ways.

Industry Use Case
Retail Send order confirmations, offers, and delivery updates directly to customers.
Manufacturing Notify customers about production completion and dispatch schedules.
Trading / Distribution Share sales invoices, credit notes, and payment reminders.
Service & Support Create and update support tickets, share resolutions, and collect feedback.

23. Future Enhancements

Once the basic integration is stable, you can extend it further with advanced capabilities.

  • Multi-language template support based on customer preferred language.
  • Campaign-style WhatsApp messages for marketing (following compliance rules).
  • AI-based intent detection to route messages automatically (e.g., to sales or support).
  • Detailed analytics dashboard in ERPNext showing message success rates and engagement.

Conclusion

Integrating ERPNext with WhatsApp using the WhatsApp Cloud API transforms your ERP from a back-office system into a real-time communication engine. With proper setup of settings, templates, server scripts, and Webhooks, you can automate order confirmations, invoice sharing, payment reminders, and support communication. This technical guide covered the architecture, steps, workflows, code examples, and best practices required to implement a robust and scalable WhatsApp integration for your ERPNext instance.


No comments yet.

Add a comment
Ctrl+Enter to add comment

NEXEVES Footer