Whatsapp Cloud API Integration with Spring Boot and Kotlin

Table of Contents
Representational image for WhatsApp Cloud API

Messaging apps like WhatsApp have become an integral part of our daily lives. To harness the power of WhatsApp cloud API for communication purposes within our applications, integrating WhatsApp into existing software solutions is becoming increasingly popular. 

A pivotal player in this landscape is the WhatsApp Business Platform, tailored to support businesses at scale. This robust messaging solution equips enterprises with essential tools to automate responses to customer inquiries and showcase product catalogs seamlessly. Noteworthy facilitator in this integration journey is the Cloud API, hosted by Meta.

The Cloud API, hosted by Meta, is a key player in integrating WhatsApp Business into apps. It makes sending and receiving messages super easy. The WhatsApp  Cloud API can smoothly handle surges in demand, ensuring a reliable communication system as businesses grow. This integration not only boosts customer engagement but also showcases the powerful communication features of WhatsApp in today’s business strategies.

This article outlines a step-by-step process for integrating WhatsApp into a Spring Boot application built using Kotlin.

WhatsApp Cloud API Integration

The WhatsApp cloud API integration process consists of several stages that require setting up a Facebook Business Manager account, creating a developer app, configuring Webhooks, and implementing APIs to send and receive messages. Here’s what you need to know.

Step 1 : Before WhatsApp Cloud API integration Create a Facebook Business Manager Account

If you don’t already have one, head over to the Meta Business account. and sign up for a free account. Once signed up, verify your email address and follow the prompts to complete your profile setup.

Creating a Facebook business account on Meta for WhatsApp Cloud API Integration

Step 2 : Make your Account a Business Account

After completing your basic details, go to Settings > Page Roles > Edit > Change Role and select Business Manager. Then click Request to Become Admin. Wait for one day as it takes around a day for the page to convert from Personal to Business.

Enable two-factor authentication on your account.

Step 3 : Sign Up & Log In to Facebook Developer Platform

Go to Meta for Developers and log in using your newly created business manager credentials.

Follow the prompts to set up your developer environment, including adding your project details and defining roles for other users who may collaborate on your project.

Step 4 : Create an app on Meta for Developers for WhatsApp Cloud API integration

Once complete, create an app on Meta for Developers. Start by visiting Meta for Developers and clicking My Apps. Then, click Create App and select Business as the app type.

Provide the requested details, including the app name and contact email address, and select your business account from the dropdown. Once the app is created, scroll down and click Set up from the WhatsApp card, as shown below:

Creating a Facebook business account on Meta for WhatsApp Cloud API Integration

This will take you to the Getting Started page, which contains all of the information you need for your Java app to start sending WhatsApp messages. Additionally — and most importantly — this page provides a temporary access token and the pre-populated cURL command that’s necessary for sending your first test message.

Creating a Facebook business account on Meta for WhatsApp

Now create a new Spring Boot application for WhatsApp Cloud API Integration

Now that your app is created in the Meta for Developers console, open IntelliJ and create your new Spring Boot application using Spring Initializr

Use the above-shown details in the main class of your application.
Your code will look something like this –

package com.whatsappIntegration.whatsappChatbot

import org.springframework.boot.autoconfigure.SpringBootApplication

import org.springframework.boot.runApplication

import java.io.IOException

import java.net.URI

import java.net.URISyntaxException

import java.net.http.HttpClient

import java.net.http.HttpRequest

import java.net.http.HttpResponse

@SpringBootApplication

class WhatsappChatbotApplication

fun main(args: Array<String>) {

runApplication<WhatsappChatbotApplication>(*args)

Spring boot application Code screenshot

Let’s break this down.

Note:- Some parts of this code need to be replaced with your own details. These are marked with chevrons, like <YOUR PHONE NUMBER ID>.

Make sure the number you’re sending a message to includes the country code and is formatted correctly.

First, you’re creating an HTTP request using a builder. You’re supplying the builder with the URI and the two header properties.

Then, you’re using the POST function, so the builder knows it’s a POST request. This is also where you set the payload body. Here, you can copy and paste the body provided on the Getting Started page — just remember to escape the double quotation marks.

And then, you’re creating a new HTTP client to send your request. The HttpResponse<String> object captures the response and provides functions to access things like the response status code and body. Now you just need to run your application.

If everything is configured correctly, a WhatsApp message similar to the one below should have been sent to the target phone number. Note that Meta’s provided example template sets the message’s cont

Whatsapp message screenshot

Now that your example message works, you can send a simple text message without using a message template.

For this to work, you need to reply to the initial message that was sent using this template. The contents of the reply don’t matter. Once that’s finished, you can modify your POST request to provide a simple text message payload:

As you can see, the type property has now been changed to text. You also replace the template object with a text object specifying the desired message.

Rerun the application, You’ll see a second WhatsApp text message arrived

Whatsapp message screenshot

Creating Your Message Template

Next-up, you’ll create your own message template for sending more rich and more personalized messages, containing an image and a call to action.

From the Getting Started page in the Meta for Developers console, step two features a link to create your own message template. Click this and then click Create Message Template. First, select Transactional as the message category, and then provide a name and a language.

WhatsApp message template creation process screenshot

Start building the template by choosing an Image as the Header, filling in the Body, and dynamically using parameters to change the message’s content.

WhatsApp message template creation process screenshot

Add a Footer and a Call To Action

Finally, add a Footer and a Call To Action. For this tutorial, use the Visit Website call to action, which allows you to provide a URL. This adds the call to action to the bottom of the message, as shown in the preview in the image above.

WhatsApp message template creation process screenshot

To ensure your template is accepted, make sure it follows the proposed guidelines and that you’ve provided sample data. You can provide data using the Add Sample button at the top of the page.

The approval process can take a bit of time, so while you’re waiting, modify the code in preparation to use this new template:

Make changes to the POST section

Again, you only need to make changes to the POST section of your HTTP request builder and modify the request body to use the new template — similar to the very first example. The difference with your new template is that it uses two components: a header and a body.

Within the components array, start by specifying your header component and declaring your image parameters. This enables you to provide an image URL for each message, which is useful if you have different images for different user segments.

The body component contains the text that should replace the parameter placeholder ({{1}}) you added while building the template. Now that it’s set up, check that the message template has been approved in the console. If so, run the code again.

To Receive Messages and send custom messages according to the user’s response.

Step 5 : Configure Webhooks

In order to enable receiving messages, you must configure webhooks.

First, add a GET and POST API to your application with “/webhook” as the URI. 

Configuring webhook a Code screenshot for WhatsApp Cloud API Integration
Configuring wehbook a Code screenshot for WhatsApp Cloud API Integration

These two endpoints will enable us to send messages as per user response.

For example: In the send Custom Message method we can override implementation to send messages as per the user response.

Create payload for the WhatsApp Messages to have flexibility:

Configuring wehbook a Code screenshot for WhatsApp Cloud API Integration
Configuring wehbook a Code screenshot for WhatsApp Cloud API Integration

Note- For interaction with users we can use modified code snippets from the main function inside a Post API to send custom messages.

Configuring wehbook a Code screenshot for WhatsApp Cloud API Integration

Next, navigate back to the Facebook Developer Console and select your app from the list of registered apps. Navigate to the Messenger tab and locate the Setup section under the General heading. Click the Webhooks option and enter the URL generated by your application during the previous step (eghttp://localhost:8080/MyApp/webhook).

Add a verification token to ensure secure data transmission between your server and Facebook’s servers.

Step 6 : Run your Spring Boot application

Now, run your Spring Boot application, and verify that your server responds correctly to both GET and POST requests sent to the “/webhook” endpoint. You’re now ready to start exchanging messages via WhatsApp!

Key challenges

1. Business Account Creation

  •  Avoid using personal accounts and create a dedicated business account for WhatsApp Business API integration.
  • Note that a newly created account may take up to one day to be approved and activated as a business account.

2. Webhook Configuration

  • WhatsApp Business API requires a secured URL (HTTPS) for webhook configuration.
  • When running the application locally, obtaining a secured URL can be challenging.
  • Utilise ngrok as a solution to generate an HTTPS URL for the localhost development environment.

3. Using ngrok

  • Install ngrok on your system to facilitate secure tunnelling to your localhost.
  • Execute the following command in the terminal ngrok http <port>
  • Replace `<port>` with the actual port number on which your Spring Boot       application is running.

To recap on the best practices for integrating the Cloud API into an application

  1. Use message templates for starting business-initiated conversations instead of plain text messages. This ensures proper context and allows for future messaging capabilities within the same conversation.
  1. Utilise async calls provided by the HTTP client library to avoid blocking the main thread while waiting for responses. The `client.sendAsync()` method enables non-blocking behaviour.
  1. Securely store sensitive authentication credentials rather than hardcoding them directly into your application. Consider using permanent access tokens or obtaining temporary ones from the API.
  1. Implement error-handling mechanisms to address unexpected situations. Analyse potential issues based on Meta’s documentation and devise appropriate fallback strategies. Logging errors for later examination might prove beneficial too.
  1. Continuously refine your integration strategy over time. Keep up with new features introduced by the Meta Messenger Platform and assess whether they align with your product roadmap. Iteratively improve your implementation where necessary.

Wrapping up

In summary, this tutorial has provided a detailed guide on how to integrate a Spring Boot application with the WhatsApp Cloud API using Kotlin. We started by creating a business manager account, configuring our application with the required settings, setting up webhooks, and finally testing the application. Along the way, we encountered some challenges such as business account creation, securing webhooks, and implementing ngrok. 

By adhering to best practices like utilizing message templates, avoiding blocking threads through async calls, securing authentication credentials, implementing error handling mechanisms, and continuously refining our strategy, we can enhance the reliability and scalability of our Kotlin app’s interaction with the WhatsApp  Cloud API. It is essential to test thoroughly in different environments and scenarios to validate the effectiveness of our approach. With these steps, businesses can seamlessly leverage the power of WhatsApp Business API integrated with their Spring Boot applications using Kotlin.

Share this blog

Tags

What do you think?

Contact Us Today for
Inquiries & Assistance

We are happy to answer your queries, propose solution to your technology requirements & help your organization navigate its next.
Your benefits:
What happens next?
1
We’ll promptly review your inquiry and respond
2
Our team will guide you through solutions
3

We will share you the proposal & kick off post your approval

Schedule a Free Consultation

Related articles