WhatsApp Business API has been available for a long but the access was provided to selected businesses only or we had to purchase it via designated third-party vendors.

After a long wait, finally WhatsApp Business API is made accessible to all the businesses!

This will open up opportunities for many small-scale businesses who would like to do WhatsApp Automation for their customer support or user queries.

In this blog, we are going to cover, how to get access to WhatsApp Business API and create a flask application that can receive user WhatsApp messages and responds to them.

Here we learn how we can get different types of responses from the bot such as:

  • Text
  • Image
  • Video
  • Document
  • Audio

Steps to integrate WhatsApp API

The following are the steps to integrate the WhatsApp Business API to Automate the messages.

Create an App

Step 1: To get started, first register as a developer on the https://developers.facebook.com/  and click on the “Get Started” button in the top right corner. If you already logged in to Facebook you will be directed to this screen, here click on continue.

Step 2: Check for your email ID and click on “Confirm Email”.

Step 3: Then select an option that is relevant to you. Here we select the developer.

Step 4: Next, you will be redirected to the developer dashboard. Here you need to create an app on your developer account. To create an app, click on the “Create App” button.

Step 5: Next, you need to select a Business as an app type and click on the “Next” button.

Step 6: Now, provide a name for your app, then provide your email ID, and select your business account. Click on the “Create app” button. [Note: business account must have approved business]

Step 7: Enter your password and click on “Submit”.

Step 8: Next, you need to select the product that you want to add to your app. Scroll down to WhatsApp and click on “Setup”.

Step 9: Next, you will be redirected to the getting started page, If you don’t select the business account while creating an app. Facebook will ask you for this.

If you don’t redirect to getting started for some reason, click on WhatsApp on the left side panel and click on “Getting Started”.

On the getting started page Facebook will generate a temporary access token, which is valid for only 24 hours. And also provide a testing phone number, to send a message to your phone number.

Add Mobile Number

Step 10: Next, you need to add your mobile number to send a message on your mobile number.

To add your number click on the “To” dropdown, here we have 2 mobile numbers added that’s why It showing up here. If you don’t have any, you can add a mobile number by clicking on the add phone number. Facebook will send you an OTP on your WhatsApp to verify the number. Once the number is verified successfully, it will show up here.

Select your number from the dropdown. Your selected mobile number will also show up in the ‘to’ field in the curl request. Next click on the send message.

If everything was set up properly you will receive a hello word message from the temporarily mobile that is provided by Facebook.

Create and connect Flask App for sending and receiving messages

Step 11: Now, let’s connect it with the Flask app to receive a message on our server when users send any message.

For that, we need to set up the webhook, on our app in the developer dashboard. In my case, Facebook has added the webhook by default. If Facebook doesn’t add by default, click on the “Add Product” on the left panel and select Webhooks from the app list.

Step 12: Next you need to configure the webhook with WhatsApp.

Click on “Whatsapp” on the left panel and select the “Configuration” tab. Here select configure a webhook.

Step 13: To configure a webhook you need a server where we can receive the response from Facebook for user Messages. For this, I am using Ngrok for this example. If you are using any other services as your server, make sure you have proper HTTPS to receive the requests from Facebook.

Start the Ngrok on your system and paste the Ngrok URL in the “Callback URL” box with some endpoint, that we are going to create on our flask app.

And also add some unique string of your choice in the “Verify Token” box as a token.

Step 14: Now we need to set up the Flask app to receive the token verification request. This is the simple Flask app to verify your token. Make sure you add your verification token to the code (the verification token would be any string that you want to set), that you have added to the configurations in the previous step and run the flask app.

from flask import Flask, request
app = Flask(__name__)
 
@app.route('/receive_msg', methods=['POST','GET'])
def webhook():
   if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
       if not request.args.get("hub.verify_token")== "YOUR VARIFICATION TOKEN":
           return "Verification token missmatch", 403
       return request.args['hub.challenge'], 200
   return "Hello world", 200
 
if __name__ == "__main__":
   app.run(debug=True)

Step 15: Now the server is ready to receive and send the response back with the verification token. This is important to send the verification token back to verify the token.

Then click on the “Verify and Save” button. This will send a request to our server, and once it receives the response with the token your settings will be saved.

Step 16: Next click on the manage button to subscribe to “messages” that will send user messages on our server whenever any user sends a response back.

Here click on the subscribe button in the row of the messages. This will enable the service for us.

Step 17: Now we need to modify the flask app that we have created, to receive and send a message to the user. Replace your existing code with the below code. In the below code example replace “VERIFICATION_TOKEN” with your temporary access token that is mentioned in step 9.

from flask import Flask, request
import requests
 
app = Flask(__name__)
 
@app.route('/')
def index():
   return "Hello"
 
def send_msg(msg):
   headers = {
       'Authorization': 'Bearer VERIFICATION_TOKEN',
   }
   json_data = {
       'messaging_product': 'whatsapp',
       'to': 'MOBILE_NUMBER',
       'type': 'text',
       "text": {
           "body": msg
       }
   }
   response = requests.post('https://graph.facebook.com/v13.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
   print(response.text)
 
 
@app.route('/receive_msg', methods=['POST','GET'])
def webhook():
   print(request)
   res = request.get_json()
   print(res)
   try:
       if res['entry'][0]['changes'][0]['value']['messages'][0]['id']:
           send_msg("Thank you for the response.")
   except:
       pass
   return '200 OK HTTPS.'
 
  
if __name__ == "__main__":
   app.run(debug=True)

Step 18: Here replace VERIFICATION_TOKEN with your verification token, you can find that on the Getting Started page. For MOBILE_NUMBER add your mobile which you have registered while following this tutorial. And also replace the PHONE_NUMBER_ID with your phone number ID that you can find on the getting started page and run the flask app.

Now come back to the getting started page of the WhatsApp app and click on the “Send” button.

You will receive the response on your flask app at the receive_msg endpoint for all the events such as message send, message delivery, and the message read.

Step 19: When the user sends a message back, you will get the message on your flask app.

Here is the user response on our server.

This is the message that we have sent to the user from our flask app. First, you will get the message ID in the response from Facebook. And once the message is sent you will receive the sent message notification.

Also, when the user reads your message you can receive the read notification in your flask app.

Step 20: Send different forms of files through the bot.

We can also send different files to the end user, such as images, videos, audio, and document files through our chatbot. This can be done by sharing the file URL in the media section. Also, Meta’s WhatsApp API provides templates for sending custom messages with buttons, links, locations, etc… Check this link for more information regarding templates and message types.

In the media section, we need to pass the file’s URL; in the body section, we are passing the text that we want to send.

It will try to read the message sent by the user and when it encounters a specific message it will respond to it with the reply that we had fed to it. Please refer to media to know more about supported media types by Whatsapp API.

  1. Send image file.

Add the below function if the user asks/message for an “Image” then it will return an image file in response to the user.

def send_image(image_url):
    headers = {
        'Authorization': 'Bearer VERIFICATION_TOKEN',
    }
    json_data = {
        'messaging_product': 'whatsapp',
        'to': 'MOBILE_NUMBER',           # example 91<your number>
        'type': 'image',  # Set the message type to 'image'
        "image": {
            "link": image_url,  # Provide the URL of the image to send
            "caption": "Welcome to Pragnakalp Techlabs"
        }
    }
    response = requests.post(
        'https://graph.facebook.com/v17.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
    print(response.text)

Output response.

  1. Send audio file.

Similarly, you can send an audio file using the below function.

def send_audio(audio_url):
    headers = {
        'Authorization': 'Bearer VERIFICATION_TOKEN',
    }
    json_data = {
        'messaging_product': 'whatsapp',
        'to': 'MOBILE_NUMBER',   # example 91<your number>
        'type': 'audio',
        "audio": {
            "link": audio_url
        }

    }
    response = requests.post(
        'https://graph.facebook.com/v17.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
    print(response.text)

If you send the message as “Audio” you will receive an audio file.

  1. Send video file.

Here is the function of sending video files

def send_video(video_url):

    headers = {
        'Authorization': 'Bearer VERIFICATION_TOKEN',
    }
    json_data = {
        'messaging_product': 'whatsapp',
        'to': 'MOBILE_NUMBER', # example 91<your number>
        'type': 'video',
        "video": {
            "link": video_url
        }
    }
    response = requests.post(
        'https://graph.facebook.com/v17.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
    print(response.text)

If you send the message as “Video” you will receive a video file.

  1. Send PDF file.

Use the below function to receive a file in the response. You can send any kind of file (.doc, .txt, .docx, .pdf, etc…)

def send_document(document_url):

    headers = {
        'Authorization': 'Bearer VERIFICATION_TOKEN',
    }
    json_data = {
        'messaging_product': 'whatsapp',
        'to': 'MOBILE_NUMBER',   # example 91<your number>
        'type': 'document',
        "document": {
            "link": document_url
        }
    }
    response = requests.post(
        'https://graph.facebook.com/v17.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
    print(response.text)

If you send the message as “Document” you will receive a PDF file.

  1. Send location file.

Use the below function to receive a specific location in the response, You just need to add the latitude and longitude of the place that you want to send.

def send_location():

    headers = {
        'Authorization': 'Bearer VERIFICATION_TOKEN',
    }
    json_data = {
        "messaging_product": "whatsapp",
        "to": 'MOBILE_NUMBER',   # example 91<your number>
        "type": "location",
        "location": {
                "longitude": 72.571365,
                "latitude": 23.022505,
                "name": "Ahmedabad",
                "address": "Pragnakalp Techlabs"
        }
    }
    response = requests.post(
        'https://graph.facebook.com/v17.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
    print(response.text)

If you send the message as “Location” you will receive the location as shown below.

  1. Send response with button options.

Here is the function to send a message with buttons.

def send_button():
    headers = {
        'Authorization': 'Bearer VERIFICATION_TOKEN',
        'Content-Type': 'application/json'
    }
    json_data = {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": 'MOBILE_NUMBER', # example 91<your number>
        "type": "interactive",
        "interactive": {
            "type": "button",
            "body": {
                "text": "What is your favourite color?"
            },
            "action": {
                "buttons": [
                    {
                        "type": "reply",
                        "reply": {
                            "id": "UNIQUE_BUTTON_ID_1",
                            "title": "Purple"
                        }
                    },
                    {
                        "type": "reply",
                        "reply": {
                            "id": "UNIQUE_BUTTON_ID_2",
                            "title": "Balck"
                        }
                    },
                    {
                        "type": "reply",
                        "reply": {
                            "id": "UNIQUE_BUTTON_ID_3",
                            "title": "Pink"
                        }
                    }
                ]
            }
        }
    }

    response = requests.post(
        'https://graph.facebook.com/v17.0/PHONE_NUMBER_ID/messages', headers=headers, json=json_data)
    print(response.text)

If you send the message as “Question” you will receive the below response.

You can make your customized message replies as we have shown in the above examples.

Here is the full code version of our “receive_msg” endpoint.

@app.route('/receive_msg', methods=['POST', 'GET'])
def webhook():
    print(request)
    res = request.get_json()
    print(res)
    try:
        user_message = res['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']
    except:
        pass
    try:
        if user_message == "Image":
            image_url = "https://miro.medium.com/v2/resize:fit:2400/1*WHyNk7-hyp5ZgjKkYrR-Aw.jpeg"
            send_image(image_url)

        if user_message == "Audio":
            audio_url = "https://dl.espressif.com/dl/audio/gs-16b-1c-8000hz.amr"
            send_audio(audio_url)
            send_msg("Your sample audio")

        if user_message == "Video":
            video_url = "http://techslides.com/demos/sample-videos/small.mp4"
            send_video(video_url)

        if user_message == "Document":
            document_url = "https://www.africau.edu/images/default/sample.pdf"
            send_document(document_url)

        if user_message == "Question":
            send_button()

        if user_message == "Location":
            send_location()

    except:
        pass
    return '200 OK HTTPS.'

Hope that this tutorial will help you to Automate messages on WhatsApp by using WhatsApp Business API. We will explore other functionalities related to WhatsApp Automation using WhatsApp Business API.

Feel free to comment your doubts/questions. We would be glad to help you.

Categories: Automation Chatbots Development Python WhatsApp Bot

3 Replies to “Automate Messages using WhatsApp Business API & Flask – Part 1”

  1. A part 2 of this tutorial will be added to the blog?

  2. I am doing the same this as you mentioned but the verification part continuously show that the callback url or verification code is not correct and enter same token on whatsapp webhook console as well as in flask app code. Help me out on this sir.

  3. How do I send messages using the app made instead of facebook console?

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*