Wisdom
  • Welcome
  • core
    • Flyway
    • Bean Validation
    • Lombok
    • Webclient
      • Generic Webclient Api
      • SSL Certificate
    • Application Event Publisher
    • REST API's Design
      • Http Methods and Status Codes
      • Resource Naming and URL Structure
      • Request / Response Design
      • Versioning Strategies
      • Filtering and Searching In API
    • Spring Boot Mail Integration
      • Sendgrid
    • Template Engines
      • Java Template Engine [JTE]
  • security
    • Complete Guide to URL Matchers in Spring Security: Types, Examples, Pros, Cons, and Best Use Cases
    • Passwordless Login With Spring Security 6
      • Spring Security OneTimeToken
        • One Time Token with default configuration
        • One Time Token with custom configuration
        • One Time Token With Jwt
  • others
    • How to Integrate WhatsApp for Sending Messages in Your Application
  • java
    • Interview Questions
      • Constructor
      • Serialization
      • Abstract Class
    • GSON
      • Type Token
      • Joda Datetime Custom Serializer and Deserializer
  • Nginx
    • Core Concepts and Basics
    • Deep Dive on NGINX Configuration Blocks
    • Deep Dive on NGINX Directives
    • Deep Dive into Nginx Variables
    • Nginx as a Reverse Proxy and Load Balancer
    • Security Hardening in NGINX
    • Performance Optimization & Tuning in NGINX
    • Dynamic DNS Resolution in Nginx
    • Advanced Configuration & Use Cases in NGINX
    • Streaming & Media Delivery in NGINX
    • Final Configuration
  • Angular
    • How to Open a PDF or an Image in Angular Without Dependencies
    • Displaying Colored Logs with Search Highlighting in Angular 6
    • Implementing Auto-Suggestion in Input Field in Angular Template-Driven Forms
    • Creating an Angular Project Using npx Without Installing It Globally
    • Skip SCSS and Test Files in Angular with ng generate
  • Javascript
    • When JavaScript's Set Falls Short for Ensuring Uniqueness in Arrays of Objects
    • Demonstrating a Function to Get the Last N Months in JavaScript
    • How to Convert Numbers to Words in the Indian Numbering System Using JavaScript
    • Sorting Based on Multiple Criteria
  • TYPESCRIPT
    • Using Omit in TypeScript
Powered by GitBook
On this page
  1. others

How to Integrate WhatsApp for Sending Messages in Your Application

PreviousOne Time Token With JwtNextInterview Questions

Last updated 4 months ago

Integrating WhatsApp messaging into your application enables seamless communication with users directly through their WhatsApp accounts. In this guide, we’ll demonstrate how to achieve this using Java Spring Boot, and we’ll also provide a link to a video on creating a WhatsApp Business account.

Prerequisites

  1. WhatsApp Business Account: Create a WhatsApp Business account. Follow this to get started.

  2. WhatsApp Cloud API: Set up the WhatsApp Cloud API via the Facebook Developer portal.

  3. JWT Token: Obtain an authentication token for accessing the API.

  4. Environment Configuration: Ensure your application has environment variables for whatsapp.api and jwt.token.


Key Components of the Integration

1. Define Template and Request DTOs

The TemplateDto and RequestDto classes allow you to structure the message payload as required by the WhatsApp API.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TemplateDto {
    private String name;
    private LanguageDto language;
    private List<ComponentDto> components;

    public TemplateDto(LanguageDto language, List<ComponentDto> components) {
        this.name = AppConstant.TEMPLATE; // Customizable template name
        this.language = language; // Customizable language
        this.components = components;
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class RequestDto {
    private String messaging_product = "whatsapp";
    private String recipient_type = "individual";
    private String to;
    private String type = "template";
    private TemplateDto template;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ParameterDto {

    private String type;
    private String text;

    public ParameterDto(String text) {
        this.type = "text";
        this.text = text;
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LanguageDto {

    private String code = "en_US";

}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ComponentDto {

    private String type;
    private String sub_type;
    private int index;
    private List<ParameterDto> parameters;

    public ComponentDto(List<ParameterDto> parameters) {
        this.type = "body";
        this.parameters = parameters;
    }

    public ComponentDto(String subType, List<ParameterDto> parameters) {
        this.type = subType;
        this.sub_type = "url";
        this.index = 0;
        this.parameters = parameters;
    }

}
  • Template Name: Set the default or a custom template name via AppConstant.TEMPLATE.

  • Language: Customize the message language in the LanguageDto.


2. Build the Service

The CommunicationService manages the message payload creation and sending process.

@Service
public class CommunicationService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${whatsapp.api}")
    private String whatsAppAPI;

    @Value("${jwt.token}")
    private String jwtToken;

    @Autowired
    AppUserRepo appUserRepo;

    public void getMessageRequestDto(Ticket savedTicket, List<AppUser> assignedUsers) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(jwtToken);

        List<ParameterDto> bodyParams = List.of(
                        new ParameterDto("name"),
                        new ParameterDto("text")
                        );
        List<ComponentDto> componentDtos = List.of(new ComponentDto(bodyParams));

        RequestDto req = new RequestDto();
        req.setTo("91" + <your_phone_number>);
        req.setTemplate(new TemplateDto(new LanguageDto(), componentDtos));

        this.sendWhatsAppMessage(req, httpHeaders);
    }

    private void sendWhatsAppMessage(RequestDto requestDto, HttpHeaders httpHeaders) {
        HttpEntity<RequestDto> requestEntity = new HttpEntity<>(requestDto, httpHeaders);
        try {
            ResponseEntity<RequestDto> response = restTemplate.postForEntity(whatsAppAPI, requestEntity, RequestDto.class);
            response.getStatusCode();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Steps to Send a WhatsApp Message

  1. Prepare the Payload:

    • Define the template components (e.g., message body parameters).

    • Customize the template name and language.

  2. Set Up HTTP Headers:

    • Include the Bearer token for authentication.

  3. Send the Request:

    • Use RestTemplate to post the payload to the WhatsApp API.

  4. Handle Responses:

    • Handle API responses and exceptions appropriately.


Customization

  • Template Name: You can modify the name in TemplateDto to use a different template for each type of message.

  • Language: Use LanguageDto to customize the message's language.


Testing the Integration

  • Verify the API by sending test messages.

  • Ensure that your WhatsApp Business account and Cloud API setup are complete.


Conclusion

With this integration, you can streamline communication with users via WhatsApp. Follow the guide linked above to create a WhatsApp Business account, then implement the provided code in your project for a smooth messaging experience.

video guide