Introduction: Why Use WhatsApp Messaging with MSG91 in Spring Boot?
In today’s fast-paced digital landscape, businesses rely on instant communication to engage with customers. WhatsApp Business API, powered by MSG91, provides a seamless way to send automated WhatsApp messages for notifications, OTPs, promotions, and more.
In this guide, we’ll walk you through integrating MSG91’s API in a Spring Boot application to send WhatsApp messages programmatically.
Setting Up WhatsApp Messaging with MSG91 in Spring Boot
To get started, follow these steps:
Create an MSG91 Account
- Sign up at MSG91 and log in.
- Navigate to API Settings and generate your unique API key.
Get WhatsApp Message Templates Approved
MSG91 requires pre-approved templates for WhatsApp messages. These templates ensure compliance with WhatsApp Business policies and prevent spam.
Example template for OTP verification:
Hello {{name}}, your OTP for login is {{otp}}. Do not share this code with anyone.
🔹 Ensure placeholders like {{name}} and {{otp}} are used for dynamic values.
Configuring Spring Boot for WhatsApp Messaging with MSG91
Before integrating MSG91 WhatsApp API, configure your Spring Boot project.
Add Required Dependencies
In your pom.xml, add the following:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
🔹 Spring Boot Starter Web enables RESTful communication. 🔹 org.json helps construct JSON payloads for MSG91 API requests.
Configure MSG91 API Credentials
Store your API credentials in application.properties
for security:
msg91.apiKey=your_api_key
msg91.endpointUrl=https://api.msg91.com/api/v5/whatsapp/whatsapp-outbound-message/bulk/
msg91.integratedNumber=your_integrated_number
Implementing WhatsApp Messaging with MSG91 in Spring Boot
Create a service class Msg91Service.java to manage API requests and message templates.
Writing the MSG91 Service
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.json.JSONObject;
@Service
public class Msg91Service {
@Value("${msg91.apiKey}")
private String apiKey;
@Value("${msg91.endpointUrl}")
private String endpointUrl;
@Value("${msg91.integratedNumber}")
private String integratedNumber;
public String sendMessage(String templateName, String mobileNumber, String... params) {
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("authkey", apiKey);
JSONObject payload = constructPayload(templateName, mobileNumber, params);
HttpEntity<String> requestEntity = new HttpEntity<>(payload.toString(), headers);
return restTemplate.postForObject(endpointUrl, requestEntity, String.class);
} catch (Exception e) {
throw new RuntimeException("Error while sending message via MSG91", e);
}
}
private JSONObject constructPayload(String templateName, String mobileNumber, String... params) {
JSONObject payload = new JSONObject();
payload.put("integrated_number", integratedNumber);
payload.put("content_type", "template");
JSONObject messagingPayload = new JSONObject();
messagingPayload.put("messaging_product", "whatsapp");
messagingPayload.put("type", "template");
JSONObject templateObj = new JSONObject();
templateObj.put("name", templateName);
JSONObject languageObj = new JSONObject();
languageObj.put("code", "en");
templateObj.put("language", languageObj);
JSONObject toAndComponents = new JSONObject();
toAndComponents.put("to", new String[]{mobileNumber});
JSONObject components = new JSONObject();
for (int i = 0; i < params.length; i++) {
JSONObject component = new JSONObject();
component.put("type", "text");
component.put("value", params[i]);
components.put("body_" + (i + 1), component);
}
toAndComponents.put("components", components);
templateObj.put("to_and_components", new JSONObject[]{toAndComponents});
messagingPayload.put("template", templateObj);
payload.put("payload", messagingPayload);
return payload;
}
}
Testing WhatsApp Messaging with MSG91 in Spring Boot
Expose an API endpoint to trigger WhatsApp messages.
@RestController
@RequestMapping("/api/messages")
public class MessageController {
@Autowired
private Msg91Service msg91Service;
@PostMapping("/sendOtp")
public ResponseEntity sendOtp(@RequestParam String mobileNumber) {
String otp = generateOtp();
msg91Service.sendMessage("otp_template", mobileNumber, otp);
return ResponseEntity.ok("OTP sent successfully");
}
private String generateOtp() {
return String.valueOf((int) (Math.random() * 9000) + 1000);
}
}
Monitoring and Optimizing WhatsApp Messaging with MSG91
- Error Logging: Capture errors while sending messages for debugging.
- Retries: Implement retry logic for failed messages.
- Delivery Reports: Monitor MSG91’s response to track message success.
Final Thoughts on WhatsApp Messaging with MSG91 in Spring Boot
Integrating MSG91’s WhatsApp API with Spring Boot allows businesses to send automated messages efficiently. This guide provided a step-by-step approach to setup, configuration, and implementation.
By leveraging this real-time messaging solution, businesses can enhance customer engagement, automate notifications, and improve response times.
Start integrating WhatsApp messaging into your application today! 🚀
Further Resources on WhatsApp Messaging with MSG91
For more insights, check out these useful guides:
- Spring Boot Messaging Best Practices
- WhatsApp Business API Documentation
- Integrating MSG91 with Cloud Services
- Optimizing API Calls for WhatsApp Messaging
For more insights, check out these useful guides:
- Spring Boot Messaging Best Practices
- WhatsApp Business API Documentation
- Integrating MSG91 with Cloud Services
- Optimizing API Calls for WhatsApp Messaging
For more insights, check out these useful guides:
- Spring Boot Messaging Best Practices
- WhatsApp Business API Documentation
- Integrating MSG91 with Cloud Services
- Optimizing API Calls for WhatsApp Messaging
- MSG91 API Documentation
- Spring Boot Messaging Guide
- Best Practices for WhatsApp Business API
- Building Secure APIs with Spring Boot
- Optimizing Cloud Messaging Services