Building a Web Service WhatsApp Cloud API & Flask: Webhook Configuration - Part 2
Tags: flask, python
Published: 2022-06-06 13:50:42

In the [first part of the article](https://koladev.xyz/posts/flask-whatsapp-cloud-api-1/), we took some time to configure the WhatsApp application to make requests and start sending messages.

In this article, we'll focus on deploying the application and configuring the flask application for webhook notifications. 

## Adding the webhook route
We need to add a route first to receive requests from Meta servers and validate the request. 
In the `app/main.py`, add a new variable called `VERIFY_TOKEN`. This variable will be used to validate requests from Meta servers. 
It's the authentication token for webhook. 
And then add the route.

```python
@app.route("/webhook/", methods=["POST", "GET"])
def webhook_whatsapp():
    """__summary__: Get message from the webhook"""

    if request.method == "GET":
        if request.args.get('hub.verify_token') == VERIFY_TOKEN:
            return request.args.get('hub.challenge')
        return "Authentication failed. Invalid Token."

    client = WhatsAppWrapper()

    response = client.process_webhook_notification(request.get_json())
    
    # Do anything with the response
    # Sending a message to a phone number to confirm the webhook is working

    return jsonify({"status": "success"}, 200)
```

The `webhook` route can accept `GET` and `POST` requests. The `GET` request is essential for the authentication challenge. After that, each `POST` request is treated as a notification. 
We process it and can do anything with the result. Here's the code for the `process_webhook_notification` method.

```python
...
    def process_webhook_notification(self, data):
        """_summary_: Process webhook notification
        For the moment, this will return the type of notification
        """

        response = []

        for entry in data["entry"]:

            for change in entry["changes"]:
                response.append(
                    {
                        "type": change["field"],
                        "from": change["value"]["metadata"]["display_phone_number"],
                    }
                )
        # Do whatever with the response
        return response
```

And this is it. You can learn more about the structure of the JSON object with the following [documentation](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/set-up-webhooks).
Let's configure the application for deployment on Heroku.

## Deploying on Heroku

Create a file called `Procfile` at the beginning of the project. 

```txt
web: gunicorn wsgi:app
```

Once it's added, create a file called `runtime.txt` that will contain the python version that Heroku will use.
```
python-3.10.4
```
To create the application on Heroku, I am using the command cli. Feel free to use the UI dashboard if you are more comfortable. Also, make sure to have created a git repository of the project.

First of all login. 
```bash
heroku login
```
After that create an application. 
```bash
heroku create whatsapp-api-app
```
Once the application is created, let's set the environment files before pushing. Use the `heroku config:set VARIABLE_NAME=VARIABLE_VALUE` command to add the environment variables.

After that, push the branch and deploy. 

```bash
git push heroku main
```
The application is deployed and let's add configure the webhook URL for the WhatsApp application configuration. 

## Configuring Webhook on the WhatsApp application
To use Webhook, you need to configure the service into the application first. In the application dashboard, configure the Webhook feature.

![Choosing webhook config](https://cdn.hashnode.com/res/hashnode/image/upload/v1654522850173/qobc2Fdyb.png)

Once it's chosen, configure the webhook URL with your Heroku project and finally add the token.

![Configuring url and verify token](https://cdn.hashnode.com/res/hashnode/image/upload/v1654523041822/eL6g0Acw8.png)

And once the configuration is validated, you will start receiving notifications on the application deployed on Heroku.

Next article, we'll dive deeper into sending different types of messages, images, or even stickers. 

*Article posted using [bloggu.io](https://bloggu.io). Try it for free.*