In this quickstart, you'll create an app that uses the WhatsApp Business Platform with Twilio to send and receive messages. You don't need to wait for WhatsApp sender registration because you'll use the Twilio Sandbox for WhatsApp as your sender.
You'll access the Programmable Messaging REST API and build an app using your preferred programming language with the Twilio server-side SDKs.
Select your programming language and complete the prerequisites:
-
Get a WhatsApp account and install WhatsApp on your device.
-
Install Python.
-
Install Flask and Twilio's Python SDK. To install using pip, run:
pip install flask twilio
-
Get a WhatsApp account and install WhatsApp on your device.
-
Install Node.js.
-
Install Express and the Twilio Node.js SDK:
npm install express twilio
-
Install and set up ngrok.
-
Get a WhatsApp account and install WhatsApp on your device.
-
Install PHP.
-
Install dependencies with Composer:
-
Install Composer.
-
Install the Twilio PHP SDK:
composer require twilio/sdk composer install
-
-
Install and set up ngrok.
- Get a WhatsApp account and install WhatsApp on your device.
- Download Visual Studio 2019 or later.
- Install and set up ngrok.
- Get a WhatsApp account and install WhatsApp on your device.
- Install Java Standard Edition (SE) Development Kit.
- Download the Twilio Java SDK fat jar file with all dependencies:
- Navigate to the Maven repository for the Twilio Java SDK.
- Click the most recent version number.
- In the Files row, click View All.
- Click the file ending in
jar-with-dependencies.jar. - Create a project directory for this quickstart and move the fat jar from your downloads into the new project directory.
- Install IntelliJ IDEA Community Edition.
- Install and set up ngrok.
- Get a WhatsApp account and install WhatsApp on your device.
- curl is installed by default on macOS, Windows, and on most Linux distributions. Run
curl --versionfrom your terminal to check.
- Get a WhatsApp account and install WhatsApp on your device.
- Install Go.
- Install and set up ngrok.
- Get a WhatsApp account and install WhatsApp on your device.
- Install Ruby.
- Install Sinatra and the Twilio Ruby SDK. Run the following command to create a Gemfile and add and install the gems:
bundle init && bundle add sinatra twilio-ruby - Install and set up ngrok.
The Twilio Sandbox for WhatsApp (the Sandbox) acts as your WhatsApp sender. You can test messaging without waiting for your WhatsApp sender registration and verification.
- Sign up for Twilio.
- Activate and connect to the Twilio Sandbox for WhatsApp:
- Go to the Try WhatsApp page in the Console, acknowledge the terms, and click Confirm.
- To connect your WhatsApp account to the Sandbox, send
join <your sandbox code>to the Sandbox number, or scan the QR code with your mobile device and send the prepopulated message. The Sandbox replies to confirm that you've joined.
To disconnect from the Sandbox, reply to the message with stop or switch to a different Sandbox by messaging join <other sandbox keyword>.
You need your Twilio account credentials to send requests. Follow these steps to get your account credentials and set them as environment variables.
- Go to the Twilio Console.
- Copy your Account SID and set it as an environment variable using the following command. Replace ACCOUNT_SID with your Account SID.
export TWILIO_ACCOUNT_SID=ACCOUNT_SID - Copy your Auth Token and set it as an environment variable using the following command. Replace AUTH_TOKEN with your Auth Token.
export TWILIO_AUTH_TOKEN=AUTH_TOKEN
- Go to the Twilio Console.
- Copy your Account SID and set it as an environment variable using the following command. Replace ACCOUNT_SID with your Account SID.
set TWILIO_ACCOUNT_SID=ACCOUNT_SID - Copy your Auth Token and set it as an environment variable using the following command. Replace AUTH_TOKEN with your Auth Token.
set TWILIO_AUTH_TOKEN=AUTH_TOKEN
- Go to the Twilio Console.
- Copy your Account SID and set it as an environment variable using the following command. Replace ACCOUNT_SID with your Account SID.
$Env:TWILIO_ACCOUNT_SID="ACCOUNT_SID"
- Copy your Auth Token and set it as an environment variable using the following command. Replace AUTH_TOKEN with your Auth Token.
$Env:TWILIO_AUTH_TOKEN="AUTH_TOKEN"
Send a message using one of the pre-approved message templates(/docs/whatsapp/sandbox#business-initiated-messages-and-templates) available from the Sandbox. This quickstart uses the Appointment Reminder template. Learn more about business-initiated messages and templates.
Warning
WhatsApp Business Platform requires the use of a message template for business-initiated messages. Each time a user sends your business a message, you have a 24-hour customer service window in which to send free-form outbound messages without a template. Learn more about customer service windows.
Follow these steps to send a message from the Sandbox number to your personal WhatsApp account:
-
Create and open a new file called
send_whatsapp.pyanywhere on your machine and paste in the following code:Send a message with WhatsApp, Twilio, and Python
# Download the helper library from https://www.twilio.com/docs/python/install import os from twilio.rest import Client import json # Find your Account SID and Auth Token at twilio.com/console # and set the environment variables. See http://twil.io/secure account_sid = os.environ["TWILIO_ACCOUNT_SID"] auth_token = os.environ["TWILIO_AUTH_TOKEN"] client = Client(account_sid, auth_token) message = client.messages.create( from_="whatsapp:+14155238886", to="whatsapp:+16285550100", content_sid="HXb5b62575e6e4ff6129ad7c8efe1f983e", content_variables=json.dumps({"1": "22 July 2026", "2": "3:15pm"}), ) print(message.body)
-
Replace the value for
towith thewhatsapp:prefix and your personal WhatsApp number in E.164 format. For example,whatsapp:+16285550100. -
Save your changes and run this command from your terminal in the directory that contains
send_whatsapp.py:python send_whatsapp.py
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
-
Create and open a new file called
send_whatsapp.jsanywhere on your machine and paste in the following code:Send a message with WhatsApp, Twilio, and Node.js
// Download the helper library from https://www.twilio.com/docs/node/install const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio"; // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; const client = twilio(accountSid, authToken); async function createMessage() { const message = await client.messages.create({ contentSid: "HXb5b62575e6e4ff6129ad7c8efe1f983e", contentVariables: JSON.stringify({ 1: "22 July 2026", 2: "3:15pm" }), from: "whatsapp:+14155238886", to: "whatsapp:+16285550100" }); console.log(message.body); } createMessage();
-
Replace the value for
towith thewhatsapp:prefix and your personal WhatsApp number in E.164 format. For example,whatsapp:+16285550100. -
Save your changes and run the following command from your terminal in the directory that contains
send_whatsapp.js:node send_whatsapp.js
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
-
Create and open a new file called
send_whatsapp.phpin the project directory and paste in the following code:Send a message with WhatsApp, Twilio, and PHP
<?php // Update the path below to your autoload.php, // see https://getcomposer.org/doc/01-basic-usage.md require_once "/path/to/vendor/autoload.php"; use Twilio\Rest\Client; // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure $sid = getenv("TWILIO_ACCOUNT_SID"); $token = getenv("TWILIO_AUTH_TOKEN"); $twilio = new Client($sid, $token); $message = $twilio->messages->create( "whatsapp:+16285550100", // To [ "from" => "whatsapp:+14155238886", "contentSid" => "HXb5b62575e6e4ff6129ad7c8efe1f983e", "contentVariables" => json_encode([ "1" => "22 July 2026", "2" => "3:15pm", ]), ] ); print $message->body;
-
Replace the first argument to
$twilio->messages->create()with your personal WhatsApp number in E.164 format, prefixed bywhatsapp:. For example,whatsapp:+16285550100. -
Replace line 5 of
send_whatsapp.phpwith the following:require __DIR__ . '/vendor/autoload.php';
-
Save your changes and run this command from your terminal in the directory that contains
send_whatsapp.php:php send_whatsapp.php
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
-
Create and set up a new project in Visual Studio:
- Open Visual Studio and click Create a new project.
- Click Console App (.NET Framework).
- Use the NuGet Package Manager to install the Twilio REST API SDK.
-
Open the file in your new Visual Studio project called
Program.csand paste in the following code, replacing the existing template code:Send a message with WhatsApp, Twilio, and C# (.NET Framework)
// Install the C# / .NET helper library from twilio.com/docs/csharp/install using System; using Twilio; using Twilio.Rest.Api.V2010.Account; using System.Threading.Tasks; using System.Collections.Generic; using Newtonsoft.Json; class Program { public static async Task Main(string[] args) { // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"); string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN"); TwilioClient.Init(accountSid, authToken); var message = await MessageResource.CreateAsync( from: new Twilio.Types.PhoneNumber("whatsapp:+14155238886"), to: new Twilio.Types.PhoneNumber("whatsapp:+16285550100"), contentSid: "HXb5b62575e6e4ff6129ad7c8efe1f983e", contentVariables: JsonConvert.SerializeObject( new Dictionary<string, Object>() { { "1", "22 July 2026" }, { "2", "3:15pm" } }, Formatting.Indented)); Console.WriteLine(message.Body); } }
-
Replace the value for
to: new Twilio.Types.PhoneNumberwith thewhatsapp:prefix and your personal WhatsApp number in E.164 format. For example,whatsapp:+16285550100. -
Save your changes and run your project in Visual Studio.
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
-
Create and open a new file called
Example.javain the same directory as the fat jar file and paste in the following code:import com.twilio.type.PhoneNumber; import java.util.HashMap; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Message; import org.json.JSONObject; public class Example { public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID"); public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN"); public static void main(String[] args) { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Message message = Message.creator( new PhoneNumber("whatsapp:+16285550100"), new PhoneNumber("whatsapp:+14155238886"), (String) null ) .setContentSid("HXb5b62575e6e4ff6129ad7c8efe1f983e") .setContentVariables(new JSONObject(new HashMap<String, Object>() {{ put("1", "22 July 2026"); put("2", "3:15pm"); }}).toString()) .create(); System.out.println(message.getSid()); } }
-
Replace the value for the first phone number (the recipient) with the
whatsapp:prefix and your personal WhatsApp number in E.164 format. For example,whatsapp:+16285550100. -
Save your changes and compile the code from your terminal in the directory that contains
Example.java. Replace10.9.0with the version of your fat jar file.javac -cp twilio-10.9.0-jar-with-dependencies.jar Example.java
-
Run the code. Replace
10.9.0with the version of your fat jar file.On Linux or macOS, run:
java -cp .:twilio-10.9.0-jar-with-dependencies.jar Example
On Windows, run:
java -cp ".;twilio-10.9.0-jar-with-dependencies.jar" Example
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
-
Copy and paste the following code into your terminal:
Send a message with WhatsApp, Twilio, and curl
CONTENT_VARIABLES_OBJ=$(cat << EOF { "1": "22 July 2026", "2": "3:15pm" } EOF ) curl -X POST "https://api.twilio.com/2010-04-01/Accounts/$TWILIO_ACCOUNT_SID/Messages.json" \ --data-urlencode "From=whatsapp:+14155238886" \ --data-urlencode "To=whatsapp:+16285550100" \ --data-urlencode "ContentSid=HXb5b62575e6e4ff6129ad7c8efe1f983e" \ --data-urlencode "ContentVariables=$CONTENT_VARIABLES_OBJ" \ -u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
-
Replace the value for
Towith thewhatsapp:prefix and your personal WhatsApp number in E.164 format. For example,whatsapp:+16285550100. -
Press Enter to send the request.
The JSON body of the request prints to your terminal.
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
-
Create and set up your Go project.
-
Create a new Go project by running the following command:
go mod init twilio-example
-
Install the Twilio Go SDK:
go get github.com/twilio/twilio-go
-
-
Create and open a new file called
send_whatsapp.goin your Go project directory and paste in the following code:Send a message with WhatsApp, Twilio, and Go
// Download the helper library from https://www.twilio.com/docs/go/install package main import ( "encoding/json" "fmt" "github.com/twilio/twilio-go" api "github.com/twilio/twilio-go/rest/api/v2010" "os" ) func main() { // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure // Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment client := twilio.NewRestClient() ContentVariables, ContentVariablesError := json.Marshal(map[string]interface{}{ "1": "22 July 2026", "2": "3:15pm", }) if ContentVariablesError != nil { fmt.Println(ContentVariablesError) os.Exit(1) } params := &api.CreateMessageParams{} params.SetFrom("whatsapp:+14155238886") params.SetTo("whatsapp:+16285550100") params.SetContentSid("HXb5b62575e6e4ff6129ad7c8efe1f983e") params.SetContentVariables(string(ContentVariables)) resp, err := client.Api.CreateMessage(params) if err != nil { fmt.Println(err.Error()) os.Exit(1) } else { if resp.Body != nil { fmt.Println(*resp.Body) } else { fmt.Println(resp.Body) } } }
-
Replace the value for
params.SetTowith thewhatsapp:prefix and your personal WhatsApp number in E.164 format. For example,whatsapp:+16285550100. -
Save your changes and run this command in the directory that contains
send_whatsapp.go:go run send_whatsapp.go
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
-
Create and open a new file called
send_whatsapp.rbanywhere on your machine and paste in the following code:Send a message with WhatsApp, Twilio, and Ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install require 'rubygems' require 'twilio-ruby' # Find your Account SID and Auth Token at twilio.com/console # and set the environment variables. See http://twil.io/secure account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] @client = Twilio::REST::Client.new(account_sid, auth_token) message = @client .api .v2010 .messages .create( from: 'whatsapp:+14155238886', to: 'whatsapp:+16285550100', content_sid: 'HXb5b62575e6e4ff6129ad7c8efe1f983e', content_variables: { '1' => '22 July 2026', '2' => '3:15pm' }.to_json ) puts message.body
-
Replace the value for
towith thewhatsapp:prefix and your personal WhatsApp number in E.164 format. For example,whatsapp:+16285550100. -
Save your changes and run this command from your terminal in the directory that contains
send_whatsapp.rb:ruby send_whatsapp.rb
After a few moments, you receive a WhatsApp message from the Sandbox to your personal WhatsApp account.
When someone replies to one of your WhatsApp messages, you receive a webhook request from Twilio. To handle this request, you need to configure the webhook, create a web application that responds to an incoming message with TwiML, and expose your application to the internet.
Follow these steps to have the Sandbox reply to a WhatsApp message that you send from your personal WhatsApp account:
-
Create and open a new file called
reply_whatsapp.pyanywhere on your machine and paste in the following code:from flask import Flask, request, Response from twilio.twiml.messaging_response import MessagingResponse app = Flask(__name__) @app.route("/reply_whatsapp", methods=['POST']) def reply_whatsapp(): # Create a new Twilio MessagingResponse resp = MessagingResponse() resp.message("Message received! Hello again from the Twilio Sandbox for WhatsApp.") # Return the TwiML (as XML) response return Response(str(resp), mimetype='text/xml') if __name__ == "__main__": app.run(port=3000)
Save the file.
-
In a new terminal window, run the following command to start the Python development server on port 3000:
python reply_whatsapp.py
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when the Sandbox receives a WhatsApp message:
-
Open the Try WhatsApp page in the Twilio Console.
-
Click Sandbox settings.
-
In the Sandbox Configuration section, in the When a message comes in field, enter the temporary forwarding URL from your ngrok console with
/reply_whatsappappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/reply_whatsapp. -
Click Save.
-
-
With the Python development server and ngrok running, send a WhatsApp message to the Sandbox number from your personal WhatsApp account.
An HTTP request shows in your ngrok console, and you receive the response message in your personal WhatsApp account.
-
Create and open a new file called
server.jsanywhere on your machine and paste in the following code:Respond to an incoming WhatsApp message with Node.js
const express = require("express"); const { MessagingResponse } = require("twilio").twiml; const app = express(); app.post("/whatsapp", (req, res) => { const twiml = new MessagingResponse(); twiml.message( "Message received! Hello again from the Twilio Sandbox for WhatsApp." ); res.type("text/xml").send(twiml.toString()); }); app.listen(3000, () => { console.log("Express server listening on port 3000"); });
-
In a new terminal window, start the Node.js development server on port 3000 by running this command in the directory that contains
server.js:node server.js
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when the Sandbox receives a WhatsApp message:
-
Open the Try WhatsApp page in the Twilio Console.
-
Click Sandbox settings.
-
In the Sandbox Configuration section, in the When a message comes in field, enter the temporary forwarding URL from your ngrok console with
/whatsappappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/whatsapp. -
Click Save.
-
-
With the Node.js development server and ngrok running, send a WhatsApp message to the Sandbox number from your personal WhatsApp account.
An HTTP request shows in your ngrok console, and you receive the response message in your personal WhatsApp account.
-
Create and open a new file called
reply_whatsapp.phpin the same directory assend_whatsapp.phpand paste in the following code:<?php require_once "vendor/autoload.php"; use Twilio\TwiML\MessagingResponse; // Set the content-type to XML to send back TwiML from the PHP SDK header("content-type: text/xml"); $response = new MessagingResponse(); $response->message( "Message received! Hello again from the Twilio Sandbox for WhatsApp." ); echo $response;
Save the file.
-
In a new terminal window, start the PHP development server on port 3000 by running this command:
php -S localhost:3000 reply_whatsapp.php
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when the Sandbox receives a WhatsApp message:
-
Open the Try WhatsApp page in the Twilio Console.
-
Click Sandbox settings.
-
In the Sandbox Configuration section, in the When a message comes in field, enter the temporary forwarding URL from your ngrok console.
For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app. -
Click Save.
-
-
With the PHP development server and ngrok running, send a WhatsApp message to the Sandbox number from your personal WhatsApp account.
An HTTP request shows in your ngrok console, and you receive the response message in your personal WhatsApp account.
-
Create a new ASP.NET MVC Project in Visual Studio:
- Open Visual Studio and click Create a new project.
- Click ASP.NET Web Application (.NET Framework).
- Click MVC to select the project type.
- Use the NuGet Package Manager to install the Twilio.AspNet.Mvc package.
-
Create a new controller:
- Open the project directory.
- Right-click on the
Controllersfolder. - Select Add > Controller... > MVC 5 Controller - Empty.
- Name the file
WhatsappController.cs.
-
Paste the following code into
WhatsappController.cs:// Code sample for ASP.NET MVC on .NET Framework 4.6.1+ // In Package Manager, run: // Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor using Twilio.AspNet.Common; using Twilio.AspNet.Mvc; using Twilio.TwiML; namespace WebApplication1.Controllers { public class WhatsappController : TwilioController { public TwiMLResult Index(WhatsappRequest incomingMessage) { var messagingResponse = new MessagingResponse(); messagingResponse.Message("Message received! Hello again from the Twilio Sandbox for WhatsApp."); return TwiML(messagingResponse); } } }
Save the file.
-
In Visual Studio, run the application by clicking the play arrow. Your web browser opens on a localhost URL. Note the port number; for example, if the URL opens on
https://localhost:44360, your port number is44360. -
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost. Replace
PORTwith the port number from your application.ngrok http PORT
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when the Sandbox receives a WhatsApp message:
-
Open the Try WhatsApp page in the Twilio Console.
-
Click Sandbox settings.
-
In the Sandbox Configuration section, in the When a message comes in field, enter the temporary forwarding URL from your ngrok console with
/whatsappappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/whatsapp. -
Click Save.
-
-
With the application and ngrok running, send a WhatsApp message to the Sandbox number from your personal WhatsApp account.
An HTTP request shows in your ngrok console, and you receive the response message in your personal WhatsApp account.
-
Create and set up the IntelliJ project.
-
Open IntelliJ IDEA Community Edition.
-
Create a new project with either Maven or Gradle as the build system.
-
Add the following dependencies to your Maven or Gradle build file:
com.twilio.sdk:twiliocom.sparkjava:spark-coreorg.slf4j
To learn more about the dependencies, see SparkJava and Simple Logging Facade 4 Java (SLF4J).
-
Select the
javafolder undersrc>main. -
To create a new Java class, click File > New > Java Class. Name the class
WhatsappApp.
-
-
In the new
WhatsappApp.javafile that IntelliJ creates, paste in the following code:Respond to an incoming WhatsApp message with Java
import com.twilio.twiml.MessagingResponse; import com.twilio.twiml.messaging.Body; import com.twilio.twiml.messaging.Message; import static spark.Spark.*; public class WhatsAppApp { public static void main(String[] args) { get("/", (req, res) -> "Hello Web"); post("/whatsapp", (req, res) -> { res.type("application/xml"); Body body = new Body .Builder("Message received! Hello again from the Twilio Sandbox for WhatsApp.") .build(); Message whatsapp = new Message .Builder() .body(body) .build(); MessagingResponse twiml = new MessagingResponse .Builder() .message(whatsapp) .build(); return twiml.toXml(); }); } }
-
Right-click on the WhatsappApp class in the project outline and choose Run 'WhatsappApp.main()'.
The Java spark web application server starts listening on port 4567.
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 4567
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when the Sandbox receives a WhatsApp message:
-
Open the Try WhatsApp page in the Twilio Console.
-
Click Sandbox settings.
-
In the Sandbox Configuration section, in the When a message comes in field, enter the temporary forwarding URL from your ngrok console with
/whatsappappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/whatsapp. -
Click Save.
-
-
With the Java development server and ngrok running, send a WhatsApp message to the Sandbox number from your personal WhatsApp account.
An HTTP request shows in your ngrok console, and you receive the response message in your personal WhatsApp account.
Although we're sure it's possible to run a server from your command line, we suggest exploring how to set up your environment, send messages, and respond to messages with TwiML in the programming language of your choice.
To respond to messages, you'll set up a webhook that triggers when the Sandbox receives a WhatsApp message. You can configure webhooks by connecting the Sandbox to an app you've already built for handling incoming messages, or build a new one for WhatsApp messages.
-
Create and open a new file called
server.goin your Go project directory and paste in the following code:Respond to an incoming WhatsApp message with Go
package main import ( "net/http" "github.com/gin-gonic/gin" "github.com/twilio/twilio-go/twiml" ) func main() { router := gin.Default() router.POST("/whatsapp", func(context *gin.Context) { message := &twiml.MessagingMessage{ Body: "Message received! Hello again from the Twilio Sandbox for WhatsApp.", } twimlResult, err := twiml.Messages([]twiml.Element{message}) if err != nil { context.String(http.StatusInternalServerError, err.Error()) } else { context.Header("Content-Type", "text/xml") context.String(http.StatusOK, twimlResult) } }) router.Run(":3000") }
-
Install the Gin Framework:
go get -u github.com/gin-gonic/gin
-
Install the TwiML dependency:
go get github.com/twilio/twilio-go/twiml@latest
-
In a new terminal window, start the Go development server on port 3000 by running this command in the directory that contains
server.go:go run server.go
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when the Sandbox receives a WhatsApp message:
-
Open the Try WhatsApp page in the Twilio Console.
-
Click Sandbox settings.
-
In the Sandbox Configuration section, in the When a message comes in field, enter the temporary forwarding URL from your ngrok console with
/whatsappappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/whatsapp. -
Click Save.
-
-
With the Go development server and ngrok running, send a WhatsApp message to the Sandbox number from your personal WhatsApp account.
An HTTP request shows in your ngrok console, and you receive the response message in your personal WhatsApp account.
-
Create and open a new file called
reply_whatsapp.rbin the same directory asGemfileand paste in the following code:require 'twilio-ruby' require 'sinatra' # disable HostAuthorization for development only configure :development do set :host_authorization, { permitted_hosts: [] } end post '/whatsapp' do twiml = Twilio::TwiML::MessagingResponse.new do |r| r.message(body: 'Message received! Hello again from the Twilio Sandbox for WhatsApp.') end twiml.to_s end
Save the file.
-
In a new terminal window, start the Ruby development server on port 4567 by running this command:
ruby reply_whatsapp.rb
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 4567
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when the Sandbox receives a WhatsApp message:
-
Open the Try WhatsApp page in the Twilio Console.
-
Click Sandbox settings.
-
In the Sandbox Configuration section, in the When a message comes in field, enter the temporary forwarding URL from your ngrok console with
/whatsappappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/whatsapp. -
Click Save.
-
-
With the Ruby development server and ngrok running, send a WhatsApp message to the Sandbox number from your personal WhatsApp account.
An HTTP request shows in your ngrok console, and you receive the response message in your personal WhatsApp account.
The WhatsApp Business Platform with Twilio uses the same REST API resources as the Twilio Programmable Messaging API. Many Twilio Messaging use cases apply to WhatsApp:
- Learn more about testing with the Twilio Sandbox for WhatsApp
- Send appointment reminders
- Create SMS conversations