1. Overview
WhatsApp Messenger is the leading messaging platform in the world, making it an essential tool for businesses to connect with their users.
By communicating over WhatsApp, we can enhance customer engagement, provide efficient support, and build stronger relationships with our users.
In this tutorial, we’ll explore how to send WhatsApp messages using Twilio within a Spring Boot application. We’ll walk through the necessary configuration, and implement functionality to send messages and handle user replies.
2. Setting up Twilio
To follow this tutorial, we’ll first need a Twilio account and a WhatsApp Business Account (WABA).
We’ll need to connect both of these accounts together by creating a WhatsApp Sender. Twilio offers a detailed setup tutorial that can be referenced to guide us through this process.
Once we set up our WhatsApp Sender successfully, we can proceed with sending messages to and receiving messages from our users.
3. Setting up the Project
Before we can use Twilio to send WhatsApp messages, we’ll need to include an SDK dependency and configure our application correctly.
3.1. Dependencies
Let’s start by adding the Twilio SDK dependency to our project’s pom.xml file:
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>10.4.1</version>
</dependency>
3.2. Defining Twilio Configuration Properties
Now, to interact with the Twilio service and send WhatsApp messages to our users, we need to configure our account SID and auth token to authenticate API requests. We’ll also need the messaging service SID to specify which messaging service, using our WhatsApp-enabled Twilio phone number, we want to use for sending the messages.
We’ll store these properties in our project’s application.yaml file and use @ConfigurationProperties to map the values to a POJO, which our service layer references when interacting with Twilio:
@Validated
@ConfigurationProperties(prefix = "com.baeldung.twilio")
class TwilioConfigurationProperties {
@NotBlank
@Pattern(regexp = "^AC[0-9a-fA-F]{32}$")
private String accountSid;
@NotBlank
private String authToken;
@NotBlank
@Pattern(regexp = "^MG[0-9a-fA-F]{32}$")
private String messagingSid;
// standard setters and getters
}
We’ve also added validation annotations to ensure all the required properties are configured correctly. If any of the defined validations fail, it results in the Spring ApplicationContext failing to start up. This allows us to conform to the fail fast principle.
Below is a snippet of our application.yaml file, which defines the required properties that’ll be mapped to our TwilioConfigurationProperties class automatically:
com:
baeldung:
twilio:
account-sid: ${TWILIO_ACCOUNT_SID}
auth-token: ${TWILIO_AUTH_TOKEN}
messaging-sid: ${TWILIO_MESSAGING_SID}
Accordingly, this setup allows us to externalize the Twilio properties and easily access them in our application.
3.3. Initializing Twilio at Startup
To invoke the methods exposed by the SDK successfully, we need to initialize it once at startup. To achieve this, we’ll create a TwilioInitializer class that implements the ApplicationRunner interface:
@Component
@EnableConfigurationProperties(TwilioConfigurationProperties.class)
class TwilioInitializer implements ApplicationRunner {
private final TwilioConfigurationProperties twilioConfigurationProperties;
// standard constructor
@Override
public void run(ApplicationArguments args) {
String accountSid = twilioConfigurationProperties.getAccountSid();
String authToken = twilioConfigurationProperties.getAuthToken();
Twilio.init(accountSid, authToken);
}
}
Using constructor injection, we inject an instance of our TwilioConfigurationProperties class we created earlier. Then we use the configured account SID and auth token to initialize the Twilio SDK in the run() method.
This ensures that Twilio is ready to use when our application starts up. This approach is better than initializing the Twilio client in our service layer each time we need to send a message.
4. Sending WhatsApp Messages
Now that we’ve defined our properties, let’s create a WhatsAppMessageDispatcher class and reference them to interact with Twilio.
For this demonstration, we’ll take an example where we want to notify our users whenever we publish a new article on our website. We’ll send them a WhatsApp message with a link to the article, so they can easily check it out.
4.1. Configuring Content SID
To restrict businesses from sending unsolicited or spammy messages, WhatsApp requires that all business-initiated notifications be templated and pre-registered. These templates are identified by a unique content SID, which must be approved by WhatsApp before we can use it in our application.
For our example, we’ll configure the following message template:
New Article Published. Check it out : {{ArticleURL}}
Here, {{ArticleURL}} is a placeholder that’ll be replaced with the actual URL of the newly published article when we send out the notification.
Now, let’s define a new nested class inside our TwilioConfigurationProperties class to hold our content SID:
@Valid
private NewArticleNotification newArticleNotification = new NewArticleNotification();
class NewArticleNotification {
@NotBlank
@Pattern(regexp = "^HX[0-9a-fA-F]{32}$")
private String contentSid;
// standard setter and getter
}
We again add validation annotations to ensure that we configure the content SID correctly and it matches the expected format.
Similarly, let’s add the corresponding content SID property to our application.yaml file:
com:
baeldung:
twilio:
new-article-notification:
content-sid: ${NEW_ARTICLE_NOTIFICATION_CONTENT_SID}
4.2. Implementing the Message Dispatcher
Now that we’ve configured our content SID, let’s implement the service method to send out notifications to our users:
public void dispatchNewArticleNotification(String phoneNumber, String articleUrl) {
String messagingSid = twilioConfigurationProperties.getMessagingSid();
String contentSid = twilioConfigurationProperties.getNewArticleNotification().getContentSid();
PhoneNumber toPhoneNumber = new PhoneNumber(String.format("whatsapp:%s", phoneNumber));
JSONObject contentVariables = new JSONObject();
contentVariables.put("ArticleURL", articleUrl);
Message.creator(toPhoneNumber, messagingSid)
.setContentSid(contentSid)
.setContentVariables(contentVariables.toString())
.create();
}
In our dispatchNewArticleNotification() method, we’re using the configured messaging SID and content SID to send out a notification to the specified phone number. We’re also passing the article URL as a content variable, which will be used to replace the placeholder in our message template.
It’s important to note that we can also configure a static message template without any placeholders. In such case, we can simply omit the call to the setContentVariables() method.
5. Handling WhatsApp Replies
Once we’ve sent out our notifications, our users might reply with their thoughts or questions. When a user replies to our WhatsApp business account, a 24-hour session window is initiated during which we can communicate with our users using free-form messages, without the need for pre-approved templates.
To automatically handle user replies from our application, we need to configure a webhook endpoint in our Twilio messaging service. The Twilio service calls this endpoint whenever a user sends a message. We receive multiple parameters in the configured API endpoint that we can use to customize our response.
Let’s see how we can create such an API endpoint in our Spring Boot application.
5.1. Implementing the Reply Message Dispatcher
First, we’ll create a new service method in our WhatsAppMessageDispatcher class to dispatch a free-form reply message:
public void dispatchReplyMessage(String phoneNumber, String username) {
String messagingSid = twilioConfigurationProperties.getMessagingSid();
PhoneNumber toPhoneNumber = new PhoneNumber(String.format("whatsapp:%s", phoneNumber));
String message = String.format("Hey %s, our team will get back to you shortly.", username);
Message.creator(toPhoneNumber, messagingSid, message).create();
}
In our dispatchReplyMessage() method, we send a personalized message to the user, addressing them by their username and letting them know that our team will get back to them shortly.
It’s worth noting that we can even send multimedia messages to our users during the 24-hour session.
5.2. Exposing the Webhook Endpoint
Next, we’ll expose a POST API endpoint in our application. The path of this endpoint should match the webhook URL we’ve configured in our Twilio messaging service:
@PostMapping(value = "/api/v1/whatsapp-message-reply")
public ResponseEntity<Void> reply(@RequestParam("ProfileName") String username,
@RequestParam("WaId") String phoneNumber) {
whatsappMessageDispatcher.dispatchReplyMessage(phoneNumber, username);
return ResponseEntity.ok().build();
}
In our controller method, we accept the ProfileName and WaId parameters from Twilio. These parameters contain the username and phone number of the user who sent the message, respectively. We then pass these values to our dispatchReplyMessage() method to send a response back to the user.
We’ve used the ProfileName and WaId parameters for our example. But as mentioned previously, Twilio sends multiple parameters to our configured API endpoint. For example, we can access the Body parameter to retrieve the text content of the user’s message. We could potentially store this message in a queue and route it to the appropriate support team for further processing.
6. Testing the Twilio Integration
Now that we’ve implemented the functionality to send WhatsApp messages using Twilio, let’s look at how we can test this integration.
Testing external services can be challenging, as we don’t want to make actual API calls to Twilio during our tests. This is where we’ll use MockServer, which will allow us to simulate the outgoing Twilio calls.
6.1. Configuring the Twilio REST Client
In order to route our Twilio API requests to MockServer, we need to configure a custom HTTP client for the Twilio SDK.
We’ll create a class in our test suite that creates an instance of TwilioRestClient with a custom HttpClient:
class TwilioProxyClient {
private final String accountSid;
private final String authToken;
private final String host;
private final int port;
// standard constructor
public TwilioRestClient createHttpClient() {
SSLContext sslContext = SSLContextBuilder.create()
.loadTrustMaterial((chain, authType) -> true)
.build();
HttpClientBuilder clientBuilder = HttpClientBuilder.create()
.setSSLContext(sslContext)
.setProxy(new HttpHost(host, port));
HttpClient httpClient = new NetworkHttpClient(clientBuilder);
return new Builder(accountSid, authToken)
.httpClient(httpClient)
.build();
}
}
In our TwilioProxyClient class, we create a custom HttpClient that routes all requests through a proxy server specified by the host and port parameters. We also configure the SSL context to trust all certificates, as MockServer uses a self-signed certificate by default.
6.2. Configuring the Test Environment
Before we write our test, we’ll create an application-integration-test.yaml file in our src/test/resources directory with the following content:
com:
baeldung:
twilio:
account-sid: AC123abc123abc123abc123abc123abc12
auth-token: test-auth-token
messaging-sid: MG123abc123abc123abc123abc123abc12
new-article-notification:
content-sid: HX123abc123abc123abc123abc123abc12
These dummy values bypass the validation we’d configured earlier in our TwilioConfigurationProperties class.
Now, let’s set up our test environment using the @BeforeEach annotation
@Autowired
private TwilioConfigurationProperties twilioConfigurationProperties;
private MockServerClient mockServerClient;
private String twilioApiPath;
@BeforeEach
void setUp() {
String accountSid = twilioConfigurationProperties.getAccountSid();
String authToken = twilioConfigurationProperties.getAuthToken();
InetSocketAddress remoteAddress = mockServerClient.remoteAddress();
String host = remoteAddress.getHostName();
int port = remoteAddress.getPort();
TwilioProxyClient twilioProxyClient = new TwilioProxyClient(accountSid, authToken, host, port);
Twilio.setRestClient(twilioProxyClient.createHttpClient());
twilioApiPath = String.format("/2010-04-01/Accounts/%s/Messages.json", accountSid);
}
In our setUp() method, we create an instance of our TwilioProxyClient class, passing in the host and port of the running MockServer instance. This client is then used to set a custom RestClient for the Twilio SDK. We also store the API path for sending messages in the twilioApiPath variable.
6.3. Validating the Twilio Request
Finally, let’s write a test case to verify that our dispatchNewArticleNotification() method sends the expected request to Twilio:
// Set up test data
String contentSid = twilioConfigurationProperties.getNewArticleNotification().getContentSid();
String messagingSid = twilioConfigurationProperties.getMessagingSid();
String contactNumber = "+911001001000";
String articleUrl = RandomString.make();
// Configure mock server expectations
mockServerClient
.when(request()
.withMethod("POST")
.withPath(twilioApiPath)
.withBody(new ParameterBody(
param("To", String.format("whatsapp:%s", contactNumber)),
param("ContentSid", contentSid),
param("ContentVariables", String.format("{\"ArticleURL\":\"%s\"}", articleUrl)),
param("MessagingServiceSid", messagingSid)
))
)
.respond(response()
.withStatusCode(200)
.withBody(EMPTY_JSON));
// Invoke method under test
whatsAppMessageDispatcher.dispatchNewArticleNotification(contactNumber, articleUrl);
// Verify the expected request was made
mockServerClient.verify(request()
.withMethod("POST")
.withPath(twilioApiPath)
.withBody(new ParameterBody(
param("To", String.format("whatsapp:%s", contactNumber)),
param("ContentSid", contentSid),
param("ContentVariables", String.format("{\"ArticleURL\":\"%s\"}", articleUrl)),
param("MessagingServiceSid", messagingSid)
)),
VerificationTimes.once()
);
In our test method, we first set up the test data and configure MockServer to expect a POST request to the Twilio API path with specific parameters in the request body. We also instruct MockServer to respond with a 200 status code and an empty JSON body when this request is made.
Next, we invoke our dispatchNewArticleNotification() method with the test data and verify that the expected request was made to MockServer exactly once.
By using MockServer to simulate the Twilio API, we ensure that our integration works as expected without actually sending any messages or incurring any costs.
7. Conclusion
In this article, we explored how to send WhatsApp messages using Twilio from a Spring Boot application.
We walked through the necessary configurations and implemented the functionality to send templated notifications to our users with dynamic placeholders.
Finally, we handled user replies to our notifications by exposing a webhook endpoint to receive the reply data from Twilio and created a service method to dispatch a generic non-templated reply message.
As always, all the code examples used in this article are available over on GitHub.