What is WhatsApp?
WhatsApp is a fast, simple, and secure messaging platform created by Facebook. Praise for the application typically comes from its ability to secure messages, communicate with large groups, message without fees, and communicate internationally for free.
It’s reported that the app has over 1.5 billion users.
View the Best Whatsapp APIs List
How does WhatsApp API work?
An important distinction between WhatsApp, and SMS services, is that WhatsApp sends messages over the internet. That means there are not SMS fees and international voice calls do not typically incur charges. To use WhatsApp, a person needs;
- phone number
- internet connection
- smartphone
Other features include the ability to send PDFs, Voice Messages, documents, spreadsheets, and slideshows.
Controversy
The main feature is encrypted messaging, which in turn, receives a lot of criticism. Zak Doffman, in an article published on Forbes.com at the end of 2019 wrote;
So what’s the issue? Put simply, it’s that if WhatsApp cannot access the content, then law enforcement and government agencies cannot access it either. Not without compromising an endpoint, a smartphone. There is no level of pressure that can be applied to the platform to have it relent, no court orders or warrants, it is not possible for them to crack the encryption without a hack.
Encrypted messages are sent by—and in between—illegal entities without the platform’s ability to shut it down. Similarly, competing political factions in various countries have used the platform to communicate free from government spying.
A simple dive into your favorite search engine will yield plenty of information on the ethics of WhatApp (as well as alternatives like Telegram or WeChat). Alternatively, check out this BuzzFeed article on simple hacks if you’re interested in less controversial uses of WhatsApp.
WhatsApp Web
In addition to messaging on the mobile app, a user can scan a QR-code with their phone to sign-into WhatsApp Web. This is essentially how we are going to integrate WhatsApp into our application. To start using WhatsApp Web;
Open https://web.whatsapp.com in your Chrome, Firefox, Opera, Safari or Edge browser and scan the QR code by using the WhatsApp app on your phone. WhatsApp.com
In order to scan the QR-code in the app navigate to Settings > WhatsApp Web/Desktop. There you can see devices that are logged in and scan QR-codes.
Once scanned, a new browser tab opens displaying your chats and messages. Subsequently, messaging can now be executed from the browser. But, how can we integrate WhatsApp Web with our application?
Maytapi WhatsApp API
Maytapi is an API that creates endpoints for a user’s WhatsApp account. Consequently, the user can send and receive text and media messages through WhatsApp in private chats.
The API wraps around WhatsApp Web and can programmatically send WhatsApp messages from the configured phone via HTTP requests. The sender is the configured phone for the API and the receiver can be any valid phone number (that is linked to a WhatsApp account) passed into the data payload of the HTTP post request.
In addition, Maytapi can:
- pass media files (up to 2MB) as a message parameter
- send messages to groups
- send response message data to a specified webhook URL
For example—assuming I had already set up a webhook endpoint—if I sent a message using the API to a phone number, and that person responded on WhatsApp, I would receive a webhook similar to:
{ product_id: 'productid', phone_id: 9999, message: { type: 'text', text: 'sample text', id: 'true_mynumber@c.us_3A64296F620C5245E26F_out', _serialized: 'true_mynumber@c.us_3A64296F620C5245E26F_out', fromMe: true }, user: { id: 'responders-number@c.us', name: 'responders-number', phone: 'responders-number' }, conversation: 'mynumber@c.us', receiver: 'mynumber', timestamp: 1582863093, type: 'message', reply: 'https://api.maytapi.com/api/myaccount/9999/sendMessage', productId: 'productid', phoneId: 9999 }
With this information, I could capture the response message or send another message using the number provided in the user
object (which is the number of the person we sent the original message to).
Is the WhatsApp API Free?
Unfortunately, no. The MayTapi WhatsApp API is priced at $29/month for unlimited API requests.
One More Hypothetical Before We Integrate
Let’s say I:
- configured my personal mobile phone as the primary phone for my Maytapi API account
- sent a message to different phone number programmatically with the API
After I sent the message, I would see a new conversation started in my WhatsApp chats on my phone. This is because the API is using my phone to send the messages. Furthermore, I could then chat with the other person in the app if they chose to respond.
We can easily configure a phone in the RapidAPI Maytapi Dashboard and I will walk you through the steps in the next section. In addition to configuring the phone, I will explain some of the other endpoints and provide an example integration on a sign-up form. Let’s begin!
How to get access to the WhatsApp API?
1. Sign Up for a Free RapidAPI Account
First, sign up for an account at RapidAPI.com. It’s free!
2. Navigate to the MayTapi WhatsApp API page
From RapidAPI, search for “WhatsApp” or click this link directly to get to the WhatsApp API page.
3. Subscribe to the API
From there, click on the pricing tab, and subscribe to the API. For only $29 a month, you’ll receive unlimited API requests.
How to Add WhatsApp Integration Into an App with JavaScript
Prerequisites
In order to complete the example you will need to have a few things:
- RapidAPI account
- subscription to Maytapi API on RapidAPI
- WhatApps downloaded on your smartphone
- internet connection
- understanding of NodeJS and ReactJS
- general understanding of how to open and use the command line
- ngrok installed locally (instructions on MAC)
- netlify cli installed
It may take a few minutes to check everything off the list but come back soon and continue!
1. Connect API to Phone
Navigate to the Maytapi API on RapidAPI.
Select the addPhone endpoint.
Add your phone number as the value for the number
parameter. You will need to add the country calling code at the beginning of the number.
Next, click Test Endpoint further up on the page.
The response body shows up next to where the required phone number parameter was added. It will look like;
{ "pid":"rapidapi-yourusername", "number":NULL, "status":NULL, "id":9999, }
Make a note of the id
parameter. This is your phone ID. It’s used in subsequent calls.
Next, on the left side of the screen select the getScreen endpoint.
Enter your phone id as the phone_id
parameter in the middle of the dashboard.
If you lost your ID, the getListPhones endpoint will return a list of phones registered.
Finally, the endpoint returns a screenshot of the QR-code you need to scan with the phone you are trying to connect.
You may not be able to scan the small image and will have to open the image in a new tab.
Furthermore, the QR-codes changes frequently, so you may need to do this a few times before you catch a valid QR-code.
There are two ways to check that you are logged in:
- There will be a Windows device under your Logged in Devices on your phone
- Run the getStatus endpoint in the dashboard with your phone id as a parameter. The response object should have a parameter
loggedIn
with a value oftrue
.
Good work! The phone is now set up properly.
Test Message
We can send a test message to ourselves using the sendMessage endpoint in the RapidAPI dashboard.
Once sent, there should be a new chat on your smartphone with the text you sent in the message
parameter. If you already had a conversation going with yourself, the message will go to the previously created chat.
2. Clone Project Repository
Project Description
I set up a small sample project that was bootstrapped with Create React App. Additionally, the project uses Netlify functions as serverless functions.
If we use Netlify functions, Netlify command-line-interface, ngrok, and Create React App we can set up a development environment that acts as a front-end, back-end, and has the ability to consume real webhooks sent to a proxy URL that’s set up with ngrok.
We can do this all in our project directory, without having to set up a code up a server and add a lot of code.
As a bonus, we are also using the REST Countries API on RapidAPI to retrieve a list of countries and their corresponding country codes. The data returned is fairly comprehensive in each country and the API is free. The response from this API generates the country list for the select input in the form.
If you are coming from an Express background, think of the functions
folder as separate routes. After the development server is running on localhost:8888
the functions can be reached at /.netlify/functions/[function name]
.
Furthermore, the lambda
folder is the compiled version of our code fields in the functions
folder. You can read more about configuring the file system in Netlify’s docs.
Clone Repo
Clone the repository from Github:
git clone https://github.com/jdretz/rapidapi-whatsapp-integration-maytapi.git
Change directories into the project and run npm install
. It will need some time to install the dependencies.
In the project root create a file .env
. Inside the file add:
REACT_APP_RAPIDAPI_KEY=[your rapidapi key]
Next, open up the file sendMessage.js
. Change the URL on line 18 by replacing PHONE_ID
with your four-digit phone ID.
After that, at the top of the file, import your RapidAPI key from the environment or hardcode it into the headers
variable for testing purposes.
Finally, run netlify dev
in the project, root to start the development server. The command explained nontechnically;
- detects and starts the React app on port 3000
- builds the serverless functions in the
functions
folder and serves them on port 34567 or/.netlify/functions/[function name]
- creates a development server listening on port 8888 combining the two worlds so we can do everything on one port (8888).
Our applications will be accessed at http://localhost:8888
.
3. Set Up Webhook
We need to set up a reachable URL in order to test the response webhook. To do this run ngrok http 8888
in a new terminal.
The terminal will display a screen like:
Next, take a look at the first line labeled ‘Forwarding’. Copy that URL and head back over into the RapidAPI dashboard. The URL will be something similar to http://idnumber.ngrok.io
.
In the dashboard, select the setWebhook
endpoint. Scroll down and enter the URL you copied, but combine it with /.netlify/functions/webhooks
.
To clarify, the project you cloned has a serverless function named webhooks. This file is located in the functions
folder. Netlify will serve the functions we create at /.netlify/functions/[function name]
.
Inspecting the webhooks.js
file reveals that we are logging the response data to the console when a webhook is received.
Finally, back on your phone in the chat, type a message in response to our programmatically sent message.
Two things should happen:
- The webhook response is logged to the running terminal
Request from ::1: POST /.netlify/functions/webhooks { product_id: 'product-id', phone_id: 9999, message: { type: 'text', text: 'Hey this is super awesome way to get in touch with me!', id: 'true_yournumber@c.us_3A77C9634C59ABC88FC5_out', _serialized: 'true_yournumber@c.us_3A77C9634C59ABC88FC5_out', fromMe: true }, user: { id: 'receiversNumber@c.us', name: 'receiversNumber', phone: 'receiversNumber' }, conversation: 'conversationId@c.us', receiver: 'receiversNumber', timestamp: 1582919890, type: 'message', reply: 'https://api.maytapi.com/api/productid/phone_id/sendMessage', productId: 'productID', phoneId: 9999 } Response with status 200 in 52 ms.
2. The terminal running ngrok will display the endpoint that received the webhook with a status code (200 if it worked)
And there you have it! To recap we now have a:
- configured phone for the Maytapi API that integrates with WhatsApp
- function that can dynamically and programmatically send WhatsApp messages with custom messages
- webhook that receives and processes response data sent to our phone
Conclusion
To sum up, the tutorial may have seemed fairly opinionated, but the concepts and vital code are not. The API call made to send a message (in sendMessage.js
) will work in virtually any other setup that runs NodeJS. The same goes for the webhook URL. The webhook is a simple POST request coming from the API and can be handled in numerous ways.
This point is important to remember if you are unfamiliar with Netlify’s serverless functions or serverless functions in general.
I did not give examples on group messaging or sending images, but there are examples on RapidAPI and examples on Maytapi that are easy to reproduce now that you know how to use the API.
This set up might make you spam crazy and tempted to unleash your marketing mania on everyone with a WhatsApp account. However, sending a message to someone outside of your contact list may get reported as spam. Additionally, you can be banned if you are tagged as spam a few times (5 – 10). Maytapi has more tips on not getting banned on their website.
Leave a Reply