whatsapp-cloud-api-examples
v1.0.0
Published
Examples for using @phoscoder/whatsapp-cloud-api
Downloads
129
Maintainers
Readme
WhatsApp Cloud API Examples
This directory contains examples demonstrating how to use the @phoscoder/whatsapp-cloud-api package in a Node.js project.
Setup
Install dependencies:
npm installConfigure environment variables:
- Copy
.env.exampleto.env - Fill in your WhatsApp Cloud API credentials from Facebook Developer Portal
cp .env.example .env- Copy
Get your credentials:
- Go to Facebook Developer Portal
- Create a new app or select an existing one
- Add WhatsApp Messenger product
- Get your TOKEN and PHONE_NUMBER_ID
- Verify your test recipient phone number
Examples
1. Basic Usage (basic-usage.js)
Demonstrates how to send different types of messages:
- Text messages
- Images
- Videos
- Documents
- Location
- Interactive buttons
- Template messages
Run it:
node basic-usage.jsMake sure to:
- Update the
TOKEN,PHONE_NUMBER_ID, andRECIPIENTvariables - Uncomment the function you want to test in the main execution block
2. Webhook Example (webhook-example.js)
Demonstrates how to set up a webhook server to receive incoming messages and events.
Run it:
node webhook-example.jsFeatures:
- Handles incoming text messages
- Responds to different commands (hello, help, menu)
- Handles media messages (images, videos, audio, documents)
- Handles location messages
- Handles interactive message responses
- Tracks message delivery status
Setting up the webhook:
- Deploy your webhook to a public server (or use ngrok for local testing)
- Go to Facebook Developer Portal
- Configure webhook settings:
- Webhook URL:
https://your-domain.com/webhook - Verify Token: Use the same token from your
.envfile
- Webhook URL:
- Subscribe to webhook fields (messages, message_status, etc.)
Using with Environment Variables
Both examples support environment variables. Create a .env file:
WHATSAPP_TOKEN=your_actual_token
PHONE_NUMBER_ID=your_phone_number_id
VERIFY_TOKEN=your_verify_token
LISTEN_PORT=3000
TEST_RECIPIENT=recipient_phone_numberThen modify the examples to use:
require('dotenv').config();
const TOKEN = process.env.WHATSAPP_TOKEN;
const PHONE_NUMBER_ID = process.env.PHONE_NUMBER_ID;Important Notes
Media URLs: When sending media, the URL must be publicly accessible and return the correct content-type header.
Phone Number Format: Use international format without '+' or '00' prefix (e.g.,
255757902132for a Tanzanian number).Template Messages: Template messages must be pre-approved in the Facebook Business Manager before you can use them.
Rate Limits: Be aware of WhatsApp Cloud API rate limits. Check the official documentation for details.
Media Download: Media URLs from
getMedia()are only valid for 5 minutes. Download and store them immediately if needed.
Resources
Support
If you encounter any issues, please open an issue on the GitHub repository.
