Send Automated WhatsApp Messages Using JavaScript The Ultimate Guide

December 4, 2024

Today, we’ll show you the ultimate guide to sending different types of WhatsApp messages using JavaScript

Effective communication is vital for project coordination, community engagement, and responsive customer support. Wassenger enhances this process by providing seamless management and interaction tools within WhatsApp messages. With its intuitive API and automation features, sending messages, videos, images, documents, and voice memos becomes simple and efficient.

In this article you will find:

  • Send Image Message 🖼️
  • Send Video Messages 📹
  • Send Document Messages 📄
  • Send Audio Voice Record 🎙️
  • Send a Media Message with an Uploaded File 📤
  • Send a GIF Message 🎞️
  • Send a Poll Message 📊
  • Send a Scheduled Date and Time Message 📅
  • Send Dynamic Native Button Messages 🔘
  • Send a List of Items to Select From 📝
  • Send a Message with Text Formatting ✍️
  • Send a Location Message with Coordinates 📍
  • Send a Location Message with the Address 🗺️
  • Send a Message with Variables 🔄
  • Send Messages with Links 🔗
  • Send Contact Card Messages 📇
  • Reply to a Message 💬
  • Forward a Message 🔁
  • Send a Catalogue Message 📒
  • Send a Message in Real-Time with No Enqueueing ⏱️
  • Send a Message with Maximum Retries 🔄
  • Send a Message with the Expiration Time ⏳
  • Send a Message Within a Time and Day Range 🕰️
  • Send a Message Reaction 😊
  • Remove a Message Reaction 🚫
  • Send a Message on Behalf of an Agent and Assign a Chat 👤
  • Send a Message and Resolve the Chat ✅
  • Send a Message and Add a Chat Label 🏷️

🤩 🤖 Wassenger is a complete communication platform and API solution for WhatsApp. Explore more than 100+ API use cases and automate anything on WhatsApp by signing up for a free trial and getting started in minutes!

Requirements

  • To have a WhatsApp number already linked to the platform and online.
  • Message recipient phone number with international prefix in E164 format. Example: +12345678900. Validate the phone number format here.

API endpoint

We will use the following API endpoint to send messages to a group:

Prepare the request

Target API URL using the POST method

https://api.wassenger.com/v1/messages

Required HTTPS headers > Obtain your API key here

Content-Type: application/json
Token: $API_TOKEN

Use body in JSON format

{
  "phone": "+1234567890",
  "message": "Hello world, this is a sample message"
}

🖥️ Looking for a code example? Go to the API live tester and get ready-to-use code examples in 15+ programming languages, including JavaScript, PHP, C#, Java, Ruby, Go, Powershell, cURL and more.

Send text messages using JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","message":"Hello world, this is a sample message"}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

🤩 🤖 Wassenger is a complete API solution for WhatsApp. Sign up for a 7-day free trial and get started in minutes!

More examples of group messages with JavaScript

For full samples, visit our API Live Tester

Send image message with JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","message":"This is a caption for an image message","media":{"url":"https://picsum.photos/seed/picsum/600/400","expiration":"7d","viewOnce":false}}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send video messages with JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","message":"This is a caption for a video message","media":{"url":"https://download.samplelib.com/mp4/sample-5s.mp4","expiration":"7d"}}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send document messages with JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","media":{"url":"https://www.africau.edu/images/default/sample.pdf","expiration":"30d"}}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send audio voice record with JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","media":{"url":"https://download.samplelib.com/mp3/sample-9s.mp3","format":"ptt"}}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send a media message with an uploaded file using JavaScript

*{{UPLOADED FILE ID}}* : Replace this expression with the specific value

  • You can upload the file here
  • The file ID will look something like this: 57443b8773c036f2bae0cd96

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","message":"This is a caption for an image message","media":{"file":"{{UPLOADED FILE ID}}"}}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send a GIF message with JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","message":"This is a sample caption for a GIF message","media":{"url":"https://i.giphy.com/vKHKDIdvxvN7vTAEOM.mp4","format":"gif"}}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send a poll message with JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","poll":{"name":"Vote for your favorite color","options":["Red","Green","Blue","Yellow","Grey","Black","Orange","Purple","White"]}}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send a scheduled date and time message with JavaScript

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","message":"This is a scheduled message to be sent to a phone number in 10 minutes","deliverAt":"2024-11-27T10:39:41.308Z"}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send dynamic native button messages with JavaScript

WhatsApp no longer accepts native button messages. Buttons messages will be automatically converted into raw text equivalent messages. Learn more here

// IMPORTANT NOTICE: // Performing HTTPS requests to the API from a JavaScript in a web browser is // forbidden by default due to cross-origin security policies (CORS). // More information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Communicating directly from JavaScript in a web browser with the API // is considered security bad practice and completely discouraged // as this will expose your API secret key, enabling a third-party user // to easily steal your key and have full privilege access to your account via API. // // We strongly recommend to do not expose the API key in the web browser JavaScript code. // Always use your server to communicate with the API without exposing the API key.

const url = 'https://api.wassenger.com/v1/messages'; const options = { method: 'POST', headers: {'Content-Type': 'application/json', Token: 'ENTER API KEY HERE'}, body: '{"phone":"+1234567890","message":"This is a message with dynamic reply buttons","header":"Optional message header","footer":"Optional message footer","buttons":[{"id":"id1","text":"Say hello"},{"id":"id2","text":"Say goodbye"},{"id":"id3","text":"Get help"}]}' };

try { const response = await fetch(url, options); const data = await response.json(); console.log(data); } catch (error) { console.error(error); }

Send a list of items to select from with JavaScript

WhatsApp no longer accepts list messages. List messages will be automatically converted into raw text equivalent messages. Learn more here

// IMPORTANT: // Do not expose your API key in browser JavaScript due to CORS and security risks // Always communicate with the API from your server to protect the API key

const url = 'https://api.wassenger.com/v1/messages' const apiKey = 'ENTER API KEY HERE' // Replace with your API key

// Define the message payload const messagePayload = { phone: "+1234567890", list: { button: "Select one option", description: "Select which type of vehicle you are interested in", title: "Motor Business", footer: "Since 1990", sections: [ { title: "Select a car type", rows: [ { title: "Coupe", id: "a1", description: "This a description for coupe cars" }, { title: "Sports", id: "a2", description: "This a description for sports cars" }, { title: "SUV", id: "a3", description: "This a description for SUV cars" }, { title: "Minivan", id: "a4", description: "This a description for minivan cars" }, { title: "Crossover", id: "a5", description: "This a description for crossover cars" }, { title: "Wagon", id: "a6", description: "This a description for wagon cars" } ] }, { title: "Select a motorbike type", rows: [ { title: "Touring", id: "b1", description: "Designed to excel at covering long distances" }, { title: "Cruiser", id: "b3", description: "Harley-Davidsons largely define the cruiser category" }, { title: "Standard", id: "b3", description: "Motorcycle intended for use on streets and commuting" } ] } ] } }

// Define the request options const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: apiKey }, body: JSON.stringify(messagePayload) // Convert payload to JSON }

async function sendMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message Sent Successfully", data) } catch (error) { console.error("Error Sending Message", error) } }

// Call the function to send the message sendMessage()

Send a message with text formatting using JavaScript

// IMPORTANT: // Avoid exposing your API key in client-side JavaScript due to CORS and security risks. // Always handle API requests from your server to protect sensitive information.

const url = 'https://api.wassenger.com/v1/messages'

const apiKey = 'ENTER API KEY HERE' // Replace with your API key

// Define the message payload const messagePayload = { phone: "+1234567890", message: "This message is formatted using _italic format_, *bold format*, strikethrough format and ```monospace format```" }

// Define the request options const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: apiKey }, body: JSON.stringify(messagePayload) // Convert payload to JSON format }

async function sendMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully", data) } catch (error) { console.error("Error sending message", error) } }

// Call the function to send the message sendMessage()

Send a message with location coordinates using JavaScript

Learn more about how to send location messages with coordinates in this tutorial

// IMPORTANT: // Avoid exposing your API key in client-side JavaScript due to CORS and security risks. // Always handle API requests from your server to protect sensitive information.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", location: { coordinates: [40.7583748, -73.9891184] }, message: "This is a location message using coordinates" }) // Message payload }

async function sendMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully", data) } catch (error) { console.error("Error sending message", error) } }

// Call the function to send the message sendMessage()

Send location message with address using JavaScript

Learn more about how to send location messages with addresses in this tutorial

// IMPORTANT: // Avoid exposing your API key in client-side JavaScript to prevent unauthorized access. // Always handle API requests through your server for better security.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", location: { address: "Santa Claus Main Post Office, Tähtikuja 1, 96930 Arctic Circle, Finland" }, message: "This is a location message using an address" }) // Message payload }

async function sendLocationMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully", data) } catch (error) { console.error("Error sending message", error) } }

// Execute the function to send the message sendLocationMessage()

Send a message with variables using JavaScript

Learn more about how to send messages with template variables in this tutorial.

// IMPORTANT: // Avoid exposing your API key in client-side JavaScript to prevent unauthorized access. // Always handle API requests through your server for better security.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", message: `Dear {{ contact.name | customer }}, Thanks for contacting us! We will answer your query shortly.

Your message was received on {{ date.humanize.full }}` }) // Message payload }

async function sendPersonalizedMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully", data) } catch (error) { console.error("Error sending message", error) } }

// Execute the function to send the message sendPersonalizedMessage()

Send a message with a URL using JavaScript

Learn more about how to send messages with URL links in this tutorial

// IMPORTANT NOTICE: // Avoid exposing your API key in client-side JavaScript to prevent unauthorized access. // More info on CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // Always use your server as a proxy to handle API requests securely.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ phone: "+1234567890", message: "Check out this cool link: https://www.youtube.com" }) // JSON payload }

async function sendMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully:", data) } catch (error) { console.error("Error sending message:", error) } }

// Execute the function to send the message sendMessage()

Send contact card messages with JavaScript

Learn more about how to send contact card messages in this tutorial

// IMPORTANT NOTICE: // Avoid exposing your API key in client-side JavaScript to prevent unauthorized access. // CORS security policies prevent browser-based requests to this API. // Learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Recommendation: // Always use a server-side implementation to securely handle API requests.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ phone: "+1234567890", contacts: [ { phone: "+1234567890", name: "John Doe" } ] }) // JSON payload }

async function sendContactMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Contact message sent successfully:", data) } catch (error) { console.error("Error sending contact message:", error) } }

// Execute the function to send the contact message sendContactMessage()

Reply to a message with JavaScript

{{MESSAGE ID}} : Replace with the actual WhatsApp message ID to forward (18, 20, 22 or 32 hexadecimal value)

// IMPORTANT NOTICE: // Avoid exposing your API key in client-side JavaScript to prevent unauthorized access. // CORS policies restrict browser-based requests to this API for security reasons. // More info: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Recommendation: // Use a secure server-side implementation to handle API requests.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number quote: "{{MESSAGE ID}}", // Replace with the actual message ID message: "This message is a reply to another message within the same chat" }) }

async function sendReplyMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Reply message sent successfully:", data) } catch (error) { console.error("Error sending reply message:", error) } }

// Execute the function to send the reply message sendReplyMessage()

Forward a message with JavaScript

{{MESSAGE ID}} : Replace with the actual WhatsApp message ID to reply to (18, 20, 22 or 32 hexadecimal value)

// IMPORTANT NOTICE: // Avoid exposing your API key in client-side JavaScript to prevent unauthorized access. // Cross-Origin Resource Sharing (CORS) policies restrict browser-based requests to this API for security reasons. // More info: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Recommendation: // Use a secure server-side implementation to handle API requests.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number forward: { message: "{{MESSAGE ID}}", // Replace with the message ID to forward chat: "+1234567890" // Replace with the target chat ID }, message: "The given message by ID will be forwarded to another chat" }) }

async function forwardMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message forwarded successfully:", data) } catch (error) { console.error("Error forwarding message:", error) } }

// Execute the function to forward the message forwardMessage()

Send a catalogue message with JavaScript

{{PRODUCT CATALOG ID TO SEND}} : Replace this expression with the specific value

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser. // This exposes your API key and poses a security risk by allowing unauthorized access. // More info: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS // // Recommendation: // Use a secure server-side implementation to handle API requests without exposing your API key.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number product: "{{PRODUCT CATALOG ID TO SEND}}" // Replace with the product catalog ID }) }

async function sendProductMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Product message sent successfully:", data) } catch (error) { console.error("Error sending product message:", error) } }

// Call the function to send the product message sendProductMessage()

Send a message in real-time with no enqueueing using JavaScript

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in the browser is a major security risk and is strongly discouraged. // Always use a secure server-side implementation to handle API requests safely.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ live: true, // Indicates real-time delivery if session is online phone: "+1234567890", // Recipient's phone number message: "This message will be delivered in real-time if the session is online, otherwise the API will return an error" }) }

async function sendRealTimeMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully:", data) } catch (error) { console.error("Error sending message:", error) } }

// Call the function to send the real-time message sendRealTimeMessage()

Send a message with maximum retries using JavaScript

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in the browser is a major security risk and is strongly discouraged. // Always use a secure server-side implementation to handle API requests safely.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ retries: 2, // Maximum retry attempts if message delivery fails phone: "+1234567890", // Recipient's phone number message: "This message will be retried only twice. If the delivery fails twice, it will be flagged as deleted, removed from the queue, and not delivered" }) }

async function sendMessageWithRetries() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully:", data) } catch (error) { console.error("Error sending message:", error) } }

// Call the function to send the message sendMessageWithRetries()

Send a message with the expiration time using JavaScript

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in the browser is a serious security risk and is strongly discouraged. // Always handle API communication securely from a server-side implementation.

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ expiration: { seconds: 90 }, // Expiration time in seconds for the message phone: "+1234567890", // Recipient's phone number message: "This message will be deleted if it cannot be delivered within 90 seconds after being queued. This ensures time-sensitive messages are not delivered later than required." }) }

async function sendTimeSensitiveMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully:", data) } catch (error) { console.error("Error sending message:", error) } }

// Call the function to send the message sendTimeSensitiveMessage()

🤩 🤖 Wassenger is a complete API solution for WhatsApp. Sign up for a 7-day free trial and get started in minutes!

Send a message within a time and day range using JavaScript

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in the browser is a serious security risk and is strongly discouraged. // Always handle API communication securely from a server-side implementation. // More details: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number message: "Restricted message example that will only be delivered between 9 am to 5 pm from Monday to Friday. If the message cannot be delivered within those time ranges, it will wait in the queue.", restrict: { start: 9, // Start time in hours (9 AM) end: 17, // End time in hours (5 PM) timezone: "CEST", // Central European Summer Time weekdays: [1, 2, 3, 4, 5] // Monday to Friday } }) }

async function sendRestrictedMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully:", data) } catch (error) { console.error("Error sending message:", error) } }

// Call the function to send the message sendRestrictedMessage()

Send a message reaction using JavaScript

{{WHATSAPP MESSAGE ID}} : Replace this expression with the specific value

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in browser JavaScript is a serious security risk and strongly discouraged. // Always handle API communication securely on your server to prevent exposing your API key. // More details: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number reaction: "👍", // Reaction emoji reactionMessage: "{{WHATSAPP MESSAGE ID}}" // Replace with the WhatsApp message ID }) }

async function sendReaction() { try { const response = await fetch(url, options) const data = await response.json() console.log("Reaction sent successfully:", data) } catch (error) { console.error("Error sending reaction:", error) } }

// Call the function to send the reaction sendReaction()

Remove message reaction:

{{WHATSAPP MESSAGE ID}} : Replace this expression with the specific value

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in browser JavaScript is a serious security risk and strongly discouraged. // Always handle API communication securely on your server to prevent exposing your API key. // Learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number reaction: "-", // Remove reaction indicator reactionMessage: "{{MESSAGE WHATSAPP ID}}" // Replace with the message ID }) }

async function removeReaction() { try { const response = await fetch(url, options) const data = await response.json() console.log("Reaction removed successfully:", data) } catch (error) { console.error("Error removing reaction:", error) } }

// Call the function to execute the removal removeReaction()

Send a message on behalf of an agent and assign a chat using JavaScript

{{USER ID}} : Replace with the actual user ID (24 hexadecimal value)

{{ASSIGNED USER ID}} : Replace with the actual user ID to assign the chat (24 hexadecimal value)

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in browser JavaScript is a security risk and strongly discouraged. // Always handle API communication securely on your server to protect your API key. // Learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', Token: 'ENTER API KEY HERE' // Replace with your API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number agent: "{{USER ID}}", // Replace with the user ID of the agent message: "This message is sent via API on behalf of an agent. The chat will also be assigned to the agent after message delivery.", actions: [ { action: "chat:assign", // Action type params: { agent: "{{ASSIGNED USER ID}}" // Replace with the user ID to assign the chat } } ] }) }

async function sendAgentMessage() { try { const response = await fetch(url, options) const data = await response.json() console.log("Message sent successfully:", data) } catch (error) { console.error("Error sending message:", error) } }

// Call the function to execute the API request sendAgentMessage()

Send a message and resolve the chat with JavaScript

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in browser JavaScript is a security risk and strongly discouraged. // Always handle API communication securely on your server to protect your API key. // Learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', // Specify JSON data format Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number message: "Once this message is delivered, the chat will be reported as resolved in the web chat interface.", actions: [ { action: "chat:resolve" // Action to mark the chat as resolved } ] }) }

async function resolveChatMessage() { try { const response = await fetch(url, options) // Send the POST request const data = await response.json() // Parse the JSON response console.log("Chat resolved successfully:", data) } catch (error) { console.error("Error resolving chat:", error) } }

// Execute the function to send the API request resolveChatMessage()

Send a message and add a chat label with JavaScript

// IMPORTANT NOTICE: // Avoid making API requests directly from JavaScript in a web browser due to CORS restrictions. // Exposing your API key in browser JavaScript is a security risk and strongly discouraged. // Always handle API communication securely on your server to protect your API key. // Learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

const url = 'https://api.wassenger.com/v1/messages'

const options = { method: 'POST', headers: { 'Content-Type': 'application/json', // Specify JSON data format Token: 'ENTER API KEY HERE' // Replace with your actual API key }, body: JSON.stringify({ phone: "+1234567890", // Recipient's phone number message: "Once this message is delivered, the given labels will be added to the chat automatically.", actions: [ { action: "labels:add", // Action to add labels to the chat params: { labels: ["new", "sales"] // Labels to add } } ] }) }

async function addLabelsToChat() { try { const response = await fetch(url, options) // Send the POST request const data = await response.json() // Parse the JSON response console.log("Labels added successfully:", data) } catch (error) { console.error("Error adding labels:", error) } }

// Execute the function to send the API request addLabelsToChat()

🤩 🤖 Wassenger is a complete API solution for WhatsApp. Sign up for a 7-day free trial and get started in minutes!

Live API testing

You can live-test and play with the API directly from your browser in minutes.

Once you are done testing, get the auto-generated code example in your preferred programming language and you will be ready to go.

FAQ

How to send messages to multiple phone numbers

You have to send numerous API requests, one per target phone number.

For instance, to send a message to 10 phone numbers, you should send 10 independent HTTPS requests to the API.

There is no option to send multiple messages in a single API request.

How to validate if a phone number can receive WhatsApp messages

You can validate if a given phone number is linked to a WhatsApp account and can receive messages.

The API provides an endpoint that can validate whether a given phone number exists in WhatsApp or not.

The only requirement is to have at least one WhatsApp number connected to the platform in your current account.

For more details, please check out the API endpoint documentation here.

Before you check if a phone number exists on WhatsApp, you can also validate and normalize the format of a list of phone numbers by using the numbers validator API endpoint. This endpoint only validates the correct E164 format, but it does not check whether the phone number effectively exists on WhatsApp.

Note: The number of WhatsApp check validations is limited per month based on your subscription plan. Please check out the pricing table for more details about the limits.

Looking for more answers? Check out the extended FAQs.

Further useful resources

API Documentation

For more details about the endpoint API, please check the documentation where you will find all the details about the accepted request params, possible success or error responses and ready-to-use code examples in multiple programming languages:

https://app.wassenger.com/docs/#tag/Messages/operation/createMessage

Ready to transform your WhatsApp communication?

Start automating your customer interactions today with Wassenger

Get Started Free