whatsapp-business-java-api

Whatsapp Business java api SDK

Java CI with Maven CodeQL Javadoc License: MIT codecov

Whatsapp business api SDK, written in java. This SDK implements the Official Whatsapp Cloud API and WhatsApp Business Management API. These allows you to:

The WhatsApp Business API allows medium and large businesses to communicate with their customers at scale. Using the API, businesses can build systems that connect thousands of customers with agents or bots, enabling both programmatic and manual communication. Additionally, you can integrate the API with numerous backend systems, such as CRM and marketing platforms.The library is designed to be simple and flexible, making it ideal for a wide range of use cases.

This SDK supports WhatsApp Business API versions from v16.0 onwards. See api changelog

:warning: This project is still under construction. Contributions are welcome.


See javadoc


:hammer_and_wrench: Installation

:warning: this library is compatible with java 17+.

Maven

1. Add the JitPack repository to your build file:

	<repositories>
		<repository>
		    <id>jitpack.io</id>
		    <url>https://jitpack.io</url>
		</repository>
	</repositories>

2. Add the following Maven dependency to your project’s pom.xml:

   <dependency>
      <groupId>com.github.Bindambc</groupId>
      <artifactId>whatsapp-business-java-api</artifactId>
      <version>v0.4.1</version>
   </dependency>

Gradle:

1. Add it in your root build.gradle at the end of repositories:

	allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

2. Add the dependency

	dependencies {
	        implementation 'com.github.Bindambc:whatsapp-business-java-api:v0.4.1'
	}

3. Install library into your Maven’s local repository by running mvn install

Alternatively, you can clone this repository and run the examples.

:arrow_heading_up: back


:eyes: Overview

There are two client classes that can be used to interact with the API:

  1. WhatsappBusinessCloudApi, a synchronous/blocking WhatsApp Business Platform Cloud API client;

    Send and receive messages using a cloud-hosted version of the WhatsApp Business Platform. The Cloud API allows you to implement WhatsApp Business APIs without the cost of hosting of your own servers and also allows you to more easily scale your business messaging.

 WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestUtils.TOKEN);

 WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi(ApiVersion.V19_0);
  1. WhatsappBusinessManagementApi, a synchronous/blocking WhatsApp Business Management API client;

    The WhatsApp Business Management API allows you to programmatically manage your WhatsApp Business Account assets, such as message templates and phone numbers.

WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

WhatsappBusinessManagementApi whatsappBusinessCloudApi = factory.newBusinessManagementApi(ApiVersion.V19_0);

These can be instantiated through the corresponding factory method of WhatsappApiFactory, by passing the token, which can be created following the instructions at whatsapp.

:arrow_heading_up: back


:eyes: Proxy

You can add a proxy to the api by calling the method setHttpProxy(...) of class WhatsappApiServiceGenerator

public static void setHttpProxy(String host, int port, String username, String pwd)

Call this method before create the api instance like:

// Set http proxy with credentials before the creation of the api instance
WhatsappApiServiceGenerator.setHttpProxy("<YOUR_PROXY_HOST>", "<YOUR_PROXY_PORT>", "<YOUR_PROXY_USERNAME>", "<YOUR_PROXY_PWD>");

// Create the api instance
WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

:scroll: Examples (Proxy):

Direct proxy without authentication credentials:

   WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestConstants.TOKEN);

        // Set http proxy without credentials before the creation of the api instance
        WhatsappApiServiceGenerator.setHttpProxy("localhost", 8080, null,null);
        
        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();
        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildTextMessage(new TextMessage()//
                        .setBody(Formatter.bold("Hello world!") + "\nSome code here: \n" + Formatter.code("hello world code here"))//
                        .setPreviewUrl(false));

        MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

        System.out.println(messageResponse);

With authentication credentials:

 WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestConstants.TOKEN);

        // Set http proxy with credentials before the creation of the api instance
        WhatsappApiServiceGenerator.setHttpProxy("localhost", 8080, "username", "password");
        
        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();
        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildTextMessage(new TextMessage()//
                        .setBody(Formatter.bold("Hello world!") + "\nSome code here: \n" + Formatter.code("hello world code here"))//
                        .setPreviewUrl(false));

        MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

        System.out.println(messageResponse);

:arrow_heading_up: back

:scroll: Examples (Sending messages)

Sending a simple text message:

 	WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestUtils.TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();
	
        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildTextMessage(new TextMessage()//
                        .setBody(Formatter.bold("Hello world!") + "\nSome code here: \n" + Formatter.code("hello world code here"))//
                        .setPreviewUrl(false));


        whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

Result:

image

:arrow_heading_up: back


Sending a message with buttons (template):

	WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestConstants.TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildTemplateMessage(//
                        new TemplateMessage()//
                                .setLanguage(new Language(LanguageType.PT_BR))//
                                .setName("schedule_confirmation3")//
                                .addComponent(//
                                        new Component(ComponentType.BODY)//
                                                .addParameter(new TextParameter("Mauricio"))//
                                                .addParameter(new TextParameter("04/11/2022"))//
                                                .addParameter(new TextParameter("14:30")))//

                );

        whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

Result:

image

:arrow_heading_up: back


Sending a message with a contact

 	WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestUtils.TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();
        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildContactMessage(new ContactMessage()//
                        .addContacts(new ContactsItem()//
                                .addPhones(new PhonesItem()//
                                        .setPhone(PHONE_NUMBER_1)//
                                        .setType(AddressType.HOME))//
                                .setName(new Name()//
                                        .setFormattedName("Mauricio Binda")//
                                        .setFirstName("Mauricio"))//
                        ));


        whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

Result:

image

:arrow_heading_up: back


Sending an interactive message with buttons:

 	WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestUtils.TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();
	
        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildInteractiveMessage(InteractiveMessage.build() //
                        .setAction(new Action() //
                                .addButton(new Button() //
                                        .setType(ButtonType.REPLY)
                                        .setReply(new Reply() //
                                                .setId("UNIQUE_BUTTON_ID_1") //
                                                .setTitle("BUTTON_TITLE_1"))) //
                                .addButton(new Button() //
                                        .setType(ButtonType.REPLY)
                                        .setReply(new Reply() //
                                                .setId("UNIQUE_BUTTON_ID_2") //
                                                .setTitle("BUTTON_TITLE_2")))
                        ) //
                        .setType(InteractiveMessageType.BUTTON) //
                        .setBody(new Body() //
                                .setText("Body message")) //
                );

        MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

        System.out.println(messageResponse);

Result:

image

:arrow_heading_up: back


Sending an interactive message with a list:

 	WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TestUtils.TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();
	
        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildInteractiveMessage(InteractiveMessage.build() //
                        .setAction(new Action() //
                                .setButtonText("BUTTON_TEXT") //
                                .addSection(new Section() //
                                        .setTitle("Title 1") //
                                        .addRow(new Row() //
                                                .setId("SECTION_1_ROW_1_ID") //
                                                .setTitle("Title 1") //
                                                .setDescription("SECTION_1_ROW_1_DESCRIPTION")) //
                                        .addRow(new Row() //
                                                .setId("SECTION_1_ROW_2_ID") //
                                                .setTitle("Title 2") //
                                                .setDescription("SECTION_1_ROW_2_DESCRIPTION")) //
                                        .addRow(new Row() //
                                                .setId("SECTION_1_ROW_3_ID") //
                                                .setTitle("Title 3") //
                                                .setDescription("SECTION_1_ROW_3_DESCRIPTION")) //
                                ) //
                                .addSection(new Section() //
                                        .setTitle("Title 2") //
                                        .addRow(new Row() //
                                                .setId("SECTION_2_ROW_1_ID") //
                                                .setTitle("Title 1") //
                                                .setDescription("SECTION_2_ROW_1_DESCRIPTION")) //
                                        .addRow(new Row() //
                                                .setId("SECTION_2_ROW_2_ID") //
                                                .setTitle("Title 2") //
                                                .setDescription("SECTION_2_ROW_2_DESCRIPTION")) //
                                        .addRow(new Row() //
                                                .setId("SECTION_2_ROW_3_ID") //
                                                .setTitle("Title 3") //
                                                .setDescription("SECTION_2_ROW_3_DESCRIPTION")) //
                                )
                        ) //
                        .setType(InteractiveMessageType.LIST) //
                        .setHeader(new Header() //
                                .setType(HeaderType.TEXT) //
                                .setText("Header Text")) //
                        .setBody(new Body() //
                                .setText("Body message")) //
                        .setFooter(new Footer() //
                                .setText("Footer Text")) //
                );

        MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

        System.out.println(messageResponse);

Result:

image

image

:arrow_heading_up: back


Sending an audio message:

		WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

		WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

		var audioMessage = new AudioMessage()//
		.setId("6418001414900549");

		var message = MessageBuilder.builder()//
		.setTo(PHONE_NUMBER_1)//
		.buildAudioMessage(audioMessage);


		MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

Result:

image

:arrow_heading_up: back


Sending a document message:


		WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

		WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

		var documentMessage = new DocumentMessage()//
		.setId("1238834210396519")// media id (uploaded before)
		.setCaption("Media Object details from developers.facebook.com")//
		.setFileName("Media oject.pdf");

		var message = MessageBuilder.builder()//
		.setTo(PHONE_NUMBER_1)//
		.buildDocumentMessage(documentMessage);


		MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

Result:

image

:arrow_heading_up: back


		WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

		WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

		var imageMessage = new ImageMessage()//
		.setLink("https://upload.wikimedia.org/wikipedia/pt/4/45/Yoda.jpg").setCaption("See this image, please");

		var message = MessageBuilder.builder()//
		.setTo(PHONE_NUMBER_1)//
		.buildImageMessage(imageMessage);


		MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

image

:arrow_heading_up: back


Sending an image message:

		WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

		WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

		var imageMessage = new ImageMessage()//
		.setId("186057067456357")// media id (uploaded before)
		.setCaption("See this image, please");

		var message = MessageBuilder.builder()//
		.setTo(PHONE_NUMBER_1)//
		.buildImageMessage(imageMessage);


		MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

Result:

image

:arrow_heading_up: back


Sending a sticker message:

	WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

        var stickerMessage = new StickerMessage()//
                .setId("527984052814860");// media id (uploaded before)


        var message = MessageBuilder.builder()//
                .setTo(PHONE_NUMBER_1)//
                .buildStickerMessage(stickerMessage);


        MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

Result:

image

:arrow_heading_up: back


Sending a video message:

		WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

		WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

		var videoMessage = new VideoMessage()//
		.setId("1236364143659727")// media id (uploaded before)
		.setCaption("See this video");


		var message = MessageBuilder.builder()//
		.setTo(PHONE_NUMBER_1)//
		.buildVideoMessage(videoMessage);


		MessageResponse messageResponse = whatsappBusinessCloudApi.sendMessage(PHONE_NUMBER_ID, message);

:arrow_heading_up: back


:scroll: Examples (WhatsApp Business Management API)

Create a message template

        WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

        WhatsappBusinessManagementApi whatsappBusinessCloudApi = factory.newBusinessManagementApi();

        var template = new MessageTemplate();

        template.setName("schedule_confirmation3")//
                .setCategory(Category.TRANSACTIONAL)//
                .setLanguage(Language.PT_BR)//
                .addComponent(new HeaderComponent()//
                        .setText("Confirmação de Atendimento")//
                        .setFormat(HeaderFormat.TEXT))//
                .addComponent(new BodyComponent()//
                        .setText("Olá " + Formatter.bold("1") + ", passando aqui para confirmar seu horário no dia " + Formatter.bold("2") + " as " + Formatter.bold("3h") + ".\nVocê confirma que comparecerá?")//
                        .setExample(new Example()//
                                .addBodyTextExamples("Maria", "04/11/2022", "13:30")//
                        ))//
                .addComponent(new ButtonComponent()//
                        .addButton(new QuickReplyButton("SIM"))//
                        .addButton(new QuickReplyButton("NÃO"))//
                        .addButton(new QuickReplyButton("REMARCAR")//
                        )


                )//
                .addComponent(new FooterComponent().setText("Utilize um dos botões abaixo para a confirmação"))


        ;

        var response = whatsappBusinessCloudApi.createMessageTemplate(WABA_ID, template);


:heavy_plus_sign: See more examples here.

:arrow_heading_up: back


:arrow_down: WebHooks

Webhooks are triggered when a customer performs an action or the status for a message a business sends a customer changes.

WebHook objects are mapped on WebHookEvent class

See Whatsapp api documentation for more details. Example:

//payload = the webhook payload json sent by Whatsapp
//using WebHook.constructEvent() to deserialize event
WebHookEvent event = WebHook.constructEvent(payload);

See an example here

You get a webhooks notification:

1- When a customer performs an action

2- When the status for a message received by a business changes (includes pricing information)

3- When WhatsApp Business Management API updates:

:arrow_heading_up: back


:paperclip: Media

You can use 4 different endpoints to manage your media:

See the examples:

Uploading media

        WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();


        var fileName = "starwars.png";

        byte[] fileContent = Files.readAllBytes(Paths.get("src/test/resources/" + fileName));


        var response = whatsappBusinessCloudApi.uploadMedia(PHONE_NUMBER_ID, fileName, FileType.PNG, fileContent);

        System.out.println(response);

:arrow_heading_up: back

Retrieving the URL for a specific media

        WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

        var response = whatsappBusinessCloudApi.retrieveMediaUrl("1227829768162607");

        System.out.println(response);

:arrow_heading_up: back

Deleting a specific media

        WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

        //delete media
        var response = whatsappBusinessCloudApi.deleteMedia("723050006231302");

        System.out.println(response);

:arrow_heading_up: back

Downloading media from a media URL

        WhatsappApiFactory factory = WhatsappApiFactory.newInstance(TOKEN);

        WhatsappBusinessCloudApi whatsappBusinessCloudApi = factory.newBusinessCloudApi();

        // retrieve the media file url
        var mediaUrl = whatsappBusinessCloudApi.retrieveMediaUrl("723050006231302");

        //call downloadMediaFile() -> return a MediaFile object with the file name and content (byte[])
        var mediaFile = whatsappBusinessCloudApi.downloadMediaFile(mediaUrl.url());

        //write the file in the folder "/examples/"
        Files.write(Path.of("src/test/java/com/whatsapp/api/examples/" + mediaFile.fileName()), mediaFile.content());

:arrow_heading_up: back

:loudspeaker: Call to Action

We hope that you’ve found this documentation helpful and that you’re excited to start using the WhatsApp Business Java API! Whether you’re a developer looking to integrate WhatsApp Business functionality into your application or a user interested in contributing to the project, there are many ways to get involved.

Try out the API today and see how it can enhance your messaging capabilities. We’d also love to hear your feedback and suggestions for how we can improve the library, so please feel free to open an issue or submit a pull request on our GitHub page.

Thank you for your interest in the WhatsApp Business Java API! We look forward to working with you.

:hammer_and_wrench: Get Involved

Contributing:

We welcome contributions from anyone who is interested in helping to improve this project. If you would like to contribute, here are a few ways you can get involved:

Report issues: If you find a bug or have a suggestion for how to improve the library, please open an issue on the project’s GitHub page.

Submit pull requests: If you have code changes you’d like to contribute, please submit a pull request on the project’s GitHub page. Before submitting, please make sure your changes adhere to the project’s code style and that all tests pass.

Spread the word: If you find the library useful, please tell others about it! You can share the project on social media, write a blog post about it, or mention it in a conference talk.

By contributing to this project, you will be helping to make it better for everyone who uses it. Thank you for your support!