tawn33y / whatsapp-cloud-api

A Node.js library for creating bots and sending/receiving messages using the Whatsapp Cloud API.
https://www.npmjs.com/package/whatsapp-cloud-api
GNU General Public License v3.0
182 stars 51 forks source link

Does not output error on invalid phone number ID #58

Open hamza-shezad opened 12 months ago

hamza-shezad commented 12 months ago

in this simple app:

import { createBot } from "whatsapp-cloud-api";

const WA_PHONE_NUMBER_ID = process.env.WA_PHONE_NUMBER_ID;
const WA_CLOUD_API_ACCESS_TOKEN = process.env.WA_CLOUD_API_ACCESS_TOKEN;
const WA_WEBHOOK_TOKEN = process.env.WA_WEBHOOK_TOKEN;

if (!WA_PHONE_NUMBER_ID) {
    throw new Error("Invalid WA_PHONE_NUMBER_ID");
}

if (!WA_CLOUD_API_ACCESS_TOKEN) {
    throw new Error("Invalid WA_CLOUD_API_ACCESS_TOKEN");
}

if (!WA_WEBHOOK_TOKEN) {
    throw new Error("Invalid WA_WEBHOOK_TOKEN");
}

const wa = createBot(WA_PHONE_NUMBER_ID, WA_CLOUD_API_ACCESS_TOKEN);

wa.startExpressServer({ webhookPath: "/whatsapp/webhook", webhookVerifyToken: WA_WEBHOOK_TOKEN })
    .then(() => console.log("WhatsApp Bot started"))
    .catch((error) => console.error(error));

wa.on("text", async (message) => {
    console.log(`Got message: ${message.data.text}`);
    await wa.sendText(message.from, "Got message.");
});

using export WA_PHONE_NUMBER_ID="111111111111111" (valid ID used in app, hidden here), the application runs without errors and successfully sends messages. however, with export WA_PHONE_NUMBER_ID="111111111111111\n" (notice extra \n, could be any invalid ID), no error is output but the application fails to send messages.

an error output is expected. if i make a curl request:

>  curl -X POST "https://graph.facebook.com/v17.0/${WA_PHONE_NUMBER_ID}/messages" \
-H "Authorization: Bearer $WA_CLOUD_API_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"messaging_product": "whatsapp", "recipient_type": "individual", "to": "xxxxxxxxxxxx", "type": "text", "text": {"body": "Hello"}}'

i get a 400 error with the following message:

{
  "error": {
    "message": "Unsupported post request. Object with ID '111111111111111\\n' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
    "type": "GraphMethodException",
    "code": 100,
    "error_subcode": 33,
    "fbtrace_id": "xxxxxx"
  }
}
tommygarces commented 12 months ago

Perhaps using a try...catch inside the wa.on like this:

wa.on("text", async (message) => {
    try {
        console.log(`Got message: ${message.data.text}`);
        await wa.sendText(message.from, "Got message.");
    } catch(error) {
        console.error(error);
    };
});
hamza-shezad commented 12 months ago

if it throws an exception, it should show up, but it doesn't. however, i will test using a try-catch later