Receive WhatsApp Media Messages Using JAVA

    Overview

    This guide shows how to receive WhatsApp text messages on a phone number registered against your WhatsApp Business Account. Typical use cases for receiving messages include customer support,  opt-in and opt-out messages, and other customer interactions.

    You can start receiving WhatsApp text messages using our APIs. Follow these instructions.

    Prerequisites

    To get started, you need a Plivo account — sign up with your work email address if you don’t have one already. If this is your first time using Plivo APIs, follow our instructions to set up a Java development environment.

    To receive incoming messages, you must have an onboarded WhatsApp account with inbound-capable numbers registered against it. If a number is in connected state, it can receive incoming messages.

    Create an Server to receive messages

    Create a file called WhatsappMessagereceive.java and paste into it this code.

    package com.example.Plivo.Whatsapp;
    
    import com.plivo.api.exceptions.PlivoXmlException;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @SpringBootApplication
    public class PlivoWhatsappApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(PlivoWhatsappApplication.class, args);
        }
    
        @GetMapping(value = "/reply_whatsapp/")
        public String getBody(
                @RequestParam String From,
                @RequestParam String To,
                @RequestParam String Media0,
                @RequestParam(name = "Body", required = false) String Body,
        ) throws PlivoXmlException {
            System.out.printf("Media Message Received - From: %s, To: %s, Media Attachment: %s\n", From, To, Media0);
    
            if (Body != null) {
                System.out.printf("Text: %s\n", Body);
            }
    
            return "message received";
        }
    }
    

    Configure a webhook URL in your WhatsApp Business Account

    Add or update a webhook URL against a WhatsApp Business Account. Once you’ve done this, you should be able to receive incoming messages.

    Test

    Topics Involved