Contact US
+1 (815) 261-0737

How to Set Up Twilio WhatsApp Integration in Salesforce?

Picture of Muskan
Muskan

July 24 2025

Integrating the Twilio WhatsApp API with Salesforce enables businesses to streamline customer communication by sending and receiving WhatsApp Messages in Salesforce. This powerful Twilio Salesforce WhatsApp integration allows for real-time, personalized engagement, making it ideal for customer support, marketing, and automation. 

In this blog, we’ll guide you through setting up WhatsApp for Salesforce, including code samples, best practices, troubleshooting tips, and how to enable the Message Blink feature for enhanced messaging.

Prerequisites

  • Twilio Account: Sign up for a Twilio account at twilio.com. You’ll need your Account SID, Auth Token, and WhatsApp-enabled number or sandbox.
  • Salesforce Account: Ensure you have a Salesforce Developer or Enterprise account with administrative privileges.
  • Development Tools: Install VS Code and the Salesforce CLI for development.
  • WhatsApp Business API Access: Set up a WhatsApp Business Account via Twilio and get approval for WhatsApp API access.

Step-by-Step Setup for Twilio WhatsApp API

1. Configure Your Twilio Account

  1. Create a Twilio Account:
    • Register at twilio.com and verify your email and phone number.
    • In the Twilio Console, go to Messaging > WhatsApp and activate the WhatsApp sandbox.
    • Send a test message from your WhatsApp number to the Twilio sandbox number (e.g., +18152610737) using the provided code (e.g., join <sandbox-code>).
  2. Retrieve Credentials:
    • Note your Account SID, Auth Token, and WhatsApp-enabled number from Account > API Credentials in the Twilio Console.

2. Set Up Salesforce CLI and Extensions

  1. Install the Salesforce CLI.
  2. In VS Code, install the Salesforce Extension Pack:
    • Open VS Code, go to Extensions, search for “Salesforce Extension Pack,” and install.
    • Authorize your Salesforce Org via the Command Palette (Ctrl+Shift+P or Command+Shift+P on Mac) with SFDX: Authorize an Org.

3. Add Remote Site Settings in Salesforce

To enable Salesforce to communicate with the Twilio WhatsApp API:

  1. Log in to Salesforce and navigate to Setup.
  2. In Quick Find, search for Remote Site Settings and click New Remote Site.
  3. Add:
    • Remote Site Name: TwilioAPI
    • Remote Site URL: https://api.twilio.com
    • (Optional) https://graph.facebook.com for WhatsApp Cloud API features.
  4. Click Save.

4. Create an Apex Class for Sending WhatsApp Messages

Develop an Apex class to send WhatsApp Messages in Salesforce:

  1. In VS Code, select SFDX: Create Apex Class, name it TwilioWhatsApp, and save it in force-app/main/default/classes.
  2. Add the following code:

public class TwilioWhatsApp {

    public static void sendWhatsAppMessage(String toNumber, String messageBody) {

        String accountSid = ‘YOUR_TWILIO_ACCOUNT_SID’;

        String authToken = ‘YOUR_TWILIO_AUTH_TOKEN’;

        String fromNumber = ‘whatsapp:+14155238886’; // Twilio sandbox number

        toNumber = ‘whatsapp:’ + toNumber; // Format recipient number

        

        Http http = new Http();

        HttpRequest request = new HttpRequest();

        request.setEndpoint(‘https://api.twilio.com/2010-04-01/Accounts/’ + accountSid + ‘/Messages.json’);

        request.setMethod(‘POST’);

        request.setHeader(‘Authorization’, ‘Basic + EncodingUtil.base64Encode(Blob.valueOf(accountSid + ‘:’ + authToken)));

        request.setHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);

        String body = ‘To=’ + EncodingUtil.urlEncode(toNumber, ‘UTF-8’) + 

                      ‘&From=’ + EncodingUtil.urlEncode(fromNumber, ‘UTF-8’) + 

                      ‘&Body=’ + EncodingUtil.urlEncode(messageBody, ‘UTF-8’);

        request.setBody(body);

        

        HttpResponse response = http.send(request);

        if (response.getStatusCode() == 201) {

            System.debug(‘Message sent successfully: + response.getBody());

        } else {

            System.debug(‘Error sending message: + response.getBody());

        }

    }

}

  1. Replace YOUR_TWILIO_ACCOUNT_SID and YOUR_TWILIO_AUTH_TOKEN with your Twilio credentials.

5. Build a Lightning Web Component (LWC) for User Interaction

Create an LWC to send WhatsApp messages from Salesforce:

  1. In VS Code, select SFDX: Create Lightning Web Component and name it sendWhatsAppMessage.
  2. Add the following to sendWhatsAppMessage.js:

import { LightningElement } from ‘lwc’;

import sendWhatsAppMessage from ‘@salesforce/apex/TwilioWhatsApp.sendWhatsAppMessage’;

 

export default class SendWhatsAppMessage extends LightningElement {

    phoneNumber;

    message;

 

    handlePhoneChange(event) {

        this.phoneNumber = event.target.value;

    }

 

    handleMessageChange(event) {

        this.message = event.target.value;

    }

 

    async sendMessage() {

        try {

            await sendWhatsAppMessage({ toNumber: this.phoneNumber, messageBody: this.message });

            alert(‘Message sent successfully!’);

        } catch (error) {

            alert(‘Error sending message: + error.body.message);

        }

    }

}

  1. Create sendWhatsAppMessage.html for the UI:

<template>

    <lightning-card title=”Send WhatsApp Message”>

        <div class=”slds-m-around_medium”>

            <lightning-input label=”Phone Number” type=”tel” onchange={handlePhoneChange}></lightning-input>

            <lightning-input label=”Message” type=”text” onchange={handleMessageChange}></lightning-input>

            <lightning-button label=”Send” onclick={sendMessage}></lightning-button>

        </div>

    </lightning-card>

</template>

  1. Deploy the LWC using SFDX: Deploy Source to Org.

6. (Optional) Install Twilio for Salesforce

For a pre-built solution:

  1. Install the Twilio for Salesforce package from the Salesforce AppExchange.
  2. In Salesforce, go to Setup > Twilio Configuration, enter your Twilio credentials, and assign Twilio Administrator or Twilio User permission sets. 

Note: This package primarily supports SMS. For WhatsApp, custom Apex or third-party apps like Ulgebra are required.

7. Configure WhatsApp Business API

  1. Ensure your WhatsApp Business Account is approved by Meta for API access.
  2. In the Twilio Console, configure your WhatsApp sender under Messaging > WhatsApp.
  3. Set a Status Callback URL (e.g., https://your-salesforce-org/services/apexrest/twilio/callback) to track message delivery.

8. Handle Incoming Messages

To receive WhatsApp Messages in Salesforce:

  1. In the Twilio Console, set a Webhook URL (e.g., https://your-salesforce-org/services/apexrest/twilio/inbound) under Messaging > WhatsApp > Integration.
  2. Create an Apex REST service:

@RestResource(urlMapping=’/twilio/inbound/*’)

global class TwilioInboundMessage {

    @HttpPost

    global static void handleIncomingMessage() {

        RestRequest req = RestContext.request;

        String fromNumber = req.params.get(‘From’);

        String messageBody = req.params.get(‘Body’);

        // Log message to a custom object

        WhatsApp_Message__c msg = new WhatsApp_Message__c(

            From_Number__c = fromNumber,

            Message_Body__c = messageBody,

            Received_Date__c = Datetime.now()

        );

        insert msg;

    }

}

  1. Add the webhook URL to Salesforce’s Remote Site Settings.

9. Enable Message Blink for Enhanced Messaging

To make your WhatsApp messages stand out, consider using Message Blink, a feature that enhances message visibility through dynamic formatting or notifications. While Twilio’s WhatsApp API doesn’t natively support Message Blink, you can simulate it by:

  1. Using Rich Media: Include images, buttons, or quick replies in your messages (supported by WhatsApp Business API templates).
    • Example: Add a media URL in the Apex class:


String body = ‘To=’ + EncodingUtil.urlEncode(toNumber, ‘UTF-8’) + 

              ‘&From=’ + EncodingUtil.urlEncode(fromNumber, ‘UTF-8’) + 

              ‘&Body=’ + EncodingUtil.urlEncode(messageBody, ‘UTF-8’) + 

                  ‘&MediaUrl=’ + EncodingUtil.urlEncode(‘https://example.com/image.jpg’, ‘UTF-8’);

  1. Custom Notifications: Use Salesforce Flows to trigger browser notifications or in-app alerts when a message is sent or received, mimicking a “blink” effect.
  2. Third-Party Tools: Explore tools like Ulgebra or MessageBird (integrated via Twilio) for advanced formatting options.

Contact Twilio support or check their WhatsApp API documentation for updates on Message Blink support.

10. Test and Deploy

  1. Deploy all components (Apex class, LWC, REST service) using Salesforce CLI or a change set.
  2. Test the integration:
    • Open the LWC in Salesforce, enter a US phone number (e.g., +12025550123) and a test message.
    • Verify the message appears on WhatsApp.
    • Check Twilio’s Monitor > Logs for delivery status.
  3. For inbound messages, reply from WhatsApp and confirm the message is logged in Salesforce.

Troubleshooting Common Issues

Here are common issues and solutions for Twilio WhatsApp Salesforce integration:

  • Messages Not Sent:
    • Cause: Incorrect Twilio credentials or phone number format.
    • Solution: Verify Account SID and Auth Token in the Apex class. Ensure the recipient number is in E.164 format (e.g., +12025550123).
  • Inbound Messages Not Received:
    • Cause: Misconfigured webhook URL or missing Remote Site Settings.
    • Solution: Confirm the webhook URL in Twilio Console matches the Salesforce Apex REST endpoint. Add https://api.twilio.com and your Salesforce org URL to Remote Site Settings.
  • API Error 3008 (Unknown Number):
    • Cause: The recipient hasn’t opted in or the number is invalid.
    • Solution: Ensure users opt in via WhatsApp (e.g., send join <sandbox-code> to the Twilio sandbox number). Verify the number is WhatsApp-enabled.
  • Messages Not Visible in Salesforce:
    • Cause: Apex REST service not deployed or custom object misconfigured.
    • Solution: Check the TwilioInboundMessage class is active and the WhatsApp_Message__c object exists with correct fields.
  • Rate Limits Exceeded:
    • Cause: Exceeding Twilio’s messaging limits in the sandbox.
    • Solution: Upgrade to a production WhatsApp number via Twilio’s Self-Signup Guide.
  • Debugging Tips:
    • Use Salesforce Debug Logs to monitor Apex execution.
    • Check Twilio’s Monitor > Logs for API response details.
    • Test with a US-based number to ensure compatibility with the US market.

Best Practices for WhatsApp for Salesforce

  • Secure Credentials: Store Twilio Account SID and Auth Token in Salesforce Named Credentials to avoid hardcoding.
  • User Opt-In: WhatsApp mandates explicit opt-in. Collect consent via web forms, SMS, or QR codes to comply with policies.
  • Scalability: Use Salesforce Flows or Process Builder for automated messaging workflows (e.g., sending order confirmations).
  • Sandbox vs. Production: Test in Twilio’s WhatsApp sandbox, then transition to a production number for live use.
  • Monitoring: Regularly check Twilio logs and Salesforce debug logs to ensure smooth operation.

Conclusion

The Twilio Salesforce WhatsApp integration empowers US businesses to deliver personalized, real-time customer experiences through WhatsApp for Salesforce. By leveraging the Twilio WhatsApp API, you can send and receive WhatsApp Messages in Salesforce, automate workflows, and enhance customer engagement. 

Adding features like Message Blink can further improve message visibility and interaction rates.

Ready to transform your customer communication? Follow this guide to set up your Twilio WhatsApp Salesforce integration and start engaging your US audience today!

Resources

Post Tags :

Share :

Table of Content

FAQs

Frequently Asked Questions