Integrating WhatsApp API into a Spring Boot application can enable your app to send and receive messages via WhatsApp, which is useful for chatbots, notifications, and customer support services. This guide will walk you through how to integrate the WhatsApp Business API in a Spring Boot application, using Twilio’s WhatsApp API as an example.
Prerequisites:
- WhatsApp Business API Account: You need a WhatsApp Business API provider. Twilio is widely used for this purpose, so you’ll need a Twilio account.
- Spring Boot Application: You should have a Spring Boot application ready to integrate with the API.
- Maven: Ensure your Spring Boot project uses Maven for dependency management.
Step 1: Set Up a Twilio Account
- Create an Account: Visit Twilio's website and sign up for an account.
- Set Up WhatsApp Sandbox: Twilio provides a WhatsApp sandbox for development purposes. After setting up the account, activate the sandbox by going to the Twilio Console.
-
Obtain Your API Credentials: You’ll need the following:
- Account SID
- Auth Token
- WhatsApp-enabled phone number provided by Twilio (sandbox number during development).
Step 2: Add Dependencies
Add the following dependencies to your pom.xml
file:
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Twilio API dependency -->
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>9.0.0</version>
</dependency>
</dependencies>
Step 3: Configure Properties
Add the Twilio credentials to your application.properties
file:
twilio.account.sid=YOUR_ACCOUNT_SID
twilio.auth.token=YOUR_AUTH_TOKEN
twilio.whatsapp.number=whatsapp:+14155238886
Replace YOUR_ACCOUNT_SID
and YOUR_AUTH_TOKEN
with the actual values from your Twilio Console, and replace whatsapp:+14155238886
with the Twilio WhatsApp Sandbox number or your live number.
Step 4: Create a TwilioService Class
This service will handle sending messages using the Twilio API.
package com.example.whatsapp.service;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class TwilioService {
@Value("${twilio.account.sid}")
private String accountSid;
@Value("${twilio.auth.token}")
private String authToken;
@Value("${twilio.whatsapp.number}")
private String fromWhatsAppNumber;
public TwilioService() {
// Initialize Twilio with account credentials
Twilio.init(accountSid, authToken);
}
public String sendWhatsAppMessage(String to, String messageBody) {
// Send a message via Twilio's API
Message message = Message.creator(
new PhoneNumber("whatsapp:" + to), // Recipient's WhatsApp number
new PhoneNumber(fromWhatsAppNumber), // Twilio WhatsApp number
messageBody) // Message body
.create();
return message.getSid(); // Return message SID to track status
}
}
Step 5: Create a Controller
Now, create a REST controller to expose an endpoint for sending WhatsApp messages.
package com.example.whatsapp.controller;
import com.example.whatsapp.service.TwilioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/whatsapp")
public class WhatsAppController {
@Autowired
private TwilioService twilioService;
@PostMapping("/send")
public String sendWhatsAppMessage(@RequestParam("to") String to,
@RequestParam("message") String message) {
return twilioService.sendWhatsAppMessage(to, message);
}
}
Step 6: Test the API
-
Run the Spring Boot Application: Start your Spring Boot application with the
mvn spring-boot:run
command. -
Send a WhatsApp Message: You can send a POST request to the API using tools like Postman or
curl
.
curl -X POST "http://localhost:8080/api/whatsapp/send" \
-d "to=whatsapp:+123456789" \
-d "message=Hello, this is a test message from WhatsApp API!"
Replace +123456789
with the recipient's WhatsApp number. You should receive the message on WhatsApp.
Step 7: Handle Incoming Messages (Optional)
If you want to receive and process incoming messages, you can configure a webhook on the Twilio console and set up a Spring Boot endpoint to handle incoming requests.
For example:
- Add an endpoint in your controller:
@PostMapping("/receive")
public ResponseEntity<String> receiveWhatsAppMessage(@RequestBody MultiValueMap<String, String> body) {
String from = body.getFirst("From");
String messageBody = body.getFirst("Body");
// Process the message here (e.g., log, save to DB)
System.out.println("Received message: " + messageBody + " from " + from);
return ResponseEntity.ok("Message received");
}
- Set Webhook: In your Twilio console, set this endpoint as the webhook URL for incoming WhatsApp messages.
Step 8: Deploy (Optional)
Once your application is ready, you can deploy it to a cloud platform like Heroku or AWS, and configure your Twilio console to use the deployed URL for sending and receiving messages.
Conclusion
This guide provides a simple integration of the WhatsApp API in a Spring Boot application using Twilio. You can expand on this by adding more features, such as:
- Message templates for sending structured messages.
- Handling media files.
- Storing chat history in a database.
Top comments (0)