Home > Software engineering >  How to extract data URL from image binary data received from WhatsApp API?
How to extract data URL from image binary data received from WhatsApp API?

Time:11-08

Requirement

I am using WhatsApp API to receive and send messages. Now, someone sent me an image and the response I am getting by API is in the form of binary data as shown in the screenshot below.

enter image description here

(and ofcourse the binary data is far more lengthy than the screenshot)

My requirement is to convert this string to Data URL so that I can display it in the browser.

#######################################################################

What I have tried

I have tried the following as per googling for a bit but it is not helping.

const extractedImage = `data:${mimeType};base64,${Buffer.from(response.data).toString("base64")}`;
// where response.data gives the binary data of image and mimeType is image/jpeg

The string after the above conversion is as displayed below.

enter image description here

The Data URL is not valid and I am getting a blank output. Please guide me how to resolve this problem.

CodePudding user response:

I am using whatsapp cloud API from backend through node js, you can refer my solution and convert it to your use case.

You should not get the response like this. The ideal response from the whatsApp API when we receive media messages is like this.

{
"entry": [
    {
        "changes": [
            {
                "field": "messages",
                "value": {
                    "contacts": [
                        {
                            "profile": {
                                "name": "XXXXXXX"
                            }
                        }
                    ],
                    "messages": [
                        {
                            "from": "XXXXXXXXXX",
                            "id": "wamid.aisjdoiajsodiajsodasd\u003d",
                            "timestamp": "1657527108",
                            "type": "image"
                        }
                    ],
                    "metadata": {}
                }
            }
        ],
        "id": "124071984791824"
    }
],
"object": "whatsapp_business_account"

}

From there you can get the image id through accessing objects like this.

 let media_id=req.body.entry[0].changes[0].value.messages[0].image.id;

From there you have to call this link to get the URL for the media_id we have. then you have to use that URL to download the media from this link here.

CodePudding user response:

I have figured out the solution.

Just needed to mention

responseType: "arrayBuffer", responseEncoding: "binary"

while making the Axios API call and also adding "binary" parameter while converting to "base64"

Buffer.from(response.data, "binary").toString("base64");

Reference -> Check out the last comment by Andrew here

  • Related