whatsapp-cloud-api-express
v3.1.0
Published
A set of Node.js and Express.js functions for sending/receiving messages using the Whatsapp Cloud API. Contains typescript declarations.
Downloads
83
Maintainers
Readme
whatsapp-cloud-api-express
A set of Node.js and Express.js functions for sending/receiving Whatsapp messages using the Whatsapp Cloud API.
Features:
All features in here, plus:
🔥 Added a way to listen for message status changes in messages. This allows to listen for
delivered
,failed
,read
,... statuses on the sent messages.🔥 Added
sendReaction
function to react to a message.🔥 Added the ability to reply to a message.
🔥 Made the webhook able to run on serverless environments (like Google Cloud Functions).[^1]
🔥 Don't get hacked (receive fake messages that your users never sent): you can provide your facebook app secret so the library will make sure all messages come from facebook servers.
✅ Added
to_phone_number
so you can identify which of your whatsapp phone numbers was destined to receive the message, this is useful if you have multiple whatsapp numbers on the same facebook app.✅ Added support for type
button
in incoming messages. Which is generated when the user "replies" from a template button.✅ Added a logging callback for each message sent so you can log each sent message easily.
✅ Changed the architecture so we can use the webhook (reciever) and the sender separately.
✅ Added 'parameters' type for template header component.
[^1]: This is because on the webhook now we wait for callbacks to finish before the response is sent (sendStatus
), this was done because on serverless environments code is not guaranteed to be kept alive after the response is sent.
Install
npm install whatsapp-cloud-api-express
How to use it?
You can use this library only to send Whatsapp messages or only to receive Whatsapp messages or you can do both.
Beforehand you should get some values from the Facebook developers website, you can use the part (1) of this amazing tutorial by @tawn33y.
Receiving messages
The webhook part of the API is implemented as an express router. The webhook is the part that allows you to listen for new messages incoming to your bot. You can use it like this:
app.use(
'/webhook/whatsapp', // you can change this path to whatever you want,
// but make sure to change it on the Facebook Developer Console too
getWebhookRouter({
// fill your own values here:
webhookVerifyToken: 'your_whatsapp_webhook_verification_token',
onNewMessage,
appSecret: 'your_facebook_app_secret', // optional, you can set null
onStatusChange, // optional
logAllEntrantRequests, // optional
})
);
Don't forget to start the express server with app.listen(3000)
(you can change the port of course) in case you are not using a serverless environment.
You will need to verify the webhook with Facebook. You can either deploy this to a server or deploy locally and use ngrok, the @tawn33y tutorial above has a section about using ngrok and verifying.
This library has been tested on v15.0, v17.0 and v18.0 of the webhook Cloud API.
Sending messages
First, create a sender like this:
const sender = createMessageSender(
// fill your own values here:
process.env.NUMBER_ID ?? '',
process.env.ACCESS_TOKEN ?? ''
);
To send a message you can use the following functions:
sendText(to, text, [options])
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| to | String
| | WhatsApp ID or phone number for the person you want to send a message to. |
| text | String
| | The text of the text message. |
| [options] | Object
| | |
| [options.preview_url] | Boolean
| | By default, WhatsApp recognizes URLs and makes them clickable, but you can also include a preview box with more information about the link. Set this field to true if you want to include a URL preview box. |
sendProduct(to, catalogId, [options])
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| to | String
| | WhatsApp ID or phone number for the person you want to send a message to. |
| catalogId | String
| | The ID of the catalog containing the product. |
| [options] | Object
| | |
| [options.body] | String
| | The text to be displayed in the message body. |
| [options.footerText] | String
| | The text to be displayed in the message footer. |
| [options.productRetailerId] | String
| | The ID of the specific product to be displayed. |
sendProductList(to, catalogId, headerText, bodyText, sections, [options])
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| to | String
| | WhatsApp ID or phone number for the person you want to send a message to. |
| catalogId | String
| | The ID of the catalog containing the products. |
| headerText | String
| | The text to be displayed in the message header. |
| bodyText | String
| | The text to be displayed in the message body. |
| sections | Array
| | An array of section objects, each containing a title and an array of product IDs. |
| [options] | Object
| | |
| [options.footerText] | String
| | The text to be displayed in the message footer. |
sendCatalog(to, bodyText, [options])
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| to | String
| | WhatsApp ID or phone number for the person you want to send a message to. |
| bodyText | String
| | The text to be displayed in the message body. |
| [options] | Object
| | |
| [options.footerText] | String
| | The text to be displayed in the message footer. |
| [options.thumbnailProductRetailerId] | String
| | The ID of the product to be used as the thumbnail for the catalog message. |
Here is an "almost complete" example of the integration using Google Cloud Functions and Firestore to display the messages using this: https://gist.github.com/j05u3/b3ad1d5d9106a918941587e03c1919b1, let me know if you have any questions/doubts ✌️.
Real world use cases
I built monaguillo.org using this library. If you have built something with this library and want to share it, let me know and I can add it here 💪.
I also built an open-source chats visualization frontend here that you can use to visualize your chats, it's compatible with this library ✌️.
Some recommendations
If you are using serverless I suggest to set min instances (in Google Cloud Functions) or reserved concurrency (in AWS) to at least 1 (~4 USD or less in monthly cost) so your bot responds fast without being affected by cold starts.
In the webhook if you are not providing your facebook app secret (
appSecret
) then at least make sure to only allowlist the Facebook IPs in your serverless environment. See here for the IPs.Make sure your
onNewMessage
function resolves in a 'reasonable time'. Not sure how long yet, but in a project where we were sleeping one minute Whatsapp servers started retrying the call to the webhook.
Local development
If you make local changes to this repo and then want to test your local version in your own project you can use npm run build
and then npm pack
in the root of this repo, it will generate a .tgz
file that you can copy to your project next to your package.json
and in your package.json
you can add the dependency like this:
"dependencies": {
"whatsapp-cloud-api-express": "file:./whatsapp-cloud-api-express-1.0.1.tgz"
}
Don't forget that serverless environments like Google Cloud Functions only upload files in the folder in which your package.json
is, so you better place the .tgz
file next to it if you want to deploy it to a serverless environment.
If you want to publish a new version you can use npm run cm
and follow the instructions.
Attribution
This project was based on https://github.com/j05u3/whatsapp-cloud-api which is a fork of https://github.com/tawn33y/whatsapp-cloud-api. Thanks to @tawn33y and the community for the hard work.
This project was started using the template: https://github.com/ryansonshine/typescript-npm-package-template.