How to Integrate WhatsApp for Sending Messages in Your Application

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 video guide 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.

Last updated