Show More
Menu
Image
Hi there! I am

Web DeveloperTech ConstultantTechnical LeadBackend Developer

Whatsapp Cloud API: How to Send & Receive WhatsApp messages

November 12, 2022
By masiting
0 Comments
Post Image

WhatsApp Cloud API is now available for all types of businesses or individual developers and it’s hosted on the Meta cloud which means now you don’t need to pay & apply WhatsApp Business API on Twilio, Zendesk, 360Dialog, or MessageBird WhatsApp BSP (Business Solution Provider) to host your WhatsApp Business API on their platform.

Features of WhatsApp Cloud API

  • In just a few minutes, any business or developer can easily access the WhatsApp Cloud API service and build directly on top of WhatsApp to customize their experience.
  • It will eliminate costly server expenses and give them instant access to new features as they arrive through API.
  • Developers can now more focus on WhatsApp SaaS product features instead of managing the infrastructure of WhatsApp Busines API.

Let’s start step by step procedures, how to use WhatsApp Cloud API

We will complete the whole setup in four sections. It following below:

  • Create a business app on Facebook.
  • Setup the WhatsApp outbound message API to send messages from your business number to your customers’ number.
  • Setup the WhatsApp inbound message webhook to accept customers’ messages to your business number.
  • Setup never expires WhatsApp Cloud API access token.

Create a business app on Facebook

  • Now, Facebook will ask for some details about your app and email. Fill in the details according to your preferences.
  • Once you will click the Create app button then Facebook will ask for your Facebook password. Enter the password and click Submit button.
  • Now, your app should be created and then you need to add the product to your recently created app. Click the Setup button on the WhatsApp product card.
  • Now you will be redirected to the WhatsApp get started page. If you want to create a new meta business account then you can choose the “create a business account” option from the dropdown or if you already have a business account then you can choose an existing account. I am choosing, the “create a business account option”. Click on the continue button.
  • Now, you can see the Temporary access token, Phone number ID, WhatsApp Business Account IDand Curl of send messages.
  • So, here you will get the Facebook test phone number (you cannot use it for the production), fill your personal number in the recipient phone number field, and try to copy the CURL code and paste it into your Mac OS or Linux terminal and hit enter to check the outbound message. The message should be received at your personal number from the Facebook test number.
  • It’s time to add your business number. Click on the Add Phone Number button which places below the current page. Once you click the button then you will see the pop-up which will ask for some details about your WhatsApp business name(Your customers will see this name when they will receive the message from your business number), business email, country, and business website.
  • Click on the Next button and then a pop-up will ask for the timezone, business category, and business description. Fill in the details carefully and hit the Next button again then you will see the phone number field. Enter your WhatsApp business phone number that you want to apply and choose the Text message option and click the Next button.
  • Now, you will get the OTP message from WhatsApp to your WhatsApp business number. Enter the OTP number & click the Finish button. Your number should be verified at this stage. Now, your number should be linked with your WhatsApp business account.

Setup the WhatsApp outbound message API to send messages from your business number to your customer’s number.

  • Now, you can use this CURL request code in order to send messages to your customer’s number or your personal number.
curl -i -X POST \https://graph.facebook.com/v13.0/<Your Phone number ID>/messages \-H 'Authorization: Bearer <Your Temporary access token>' \-H 'Content-Type: application/json' \-d '{ "messaging_product": "whatsapp", "to": "<Your Personal Number or Your customers's Number with country code>", "type": "template", "template": { "name": "hello_world", "language": { "code": "en_US" } } }'
  • You can use this online tool to convert this curl request code to your favorite programming language code.
  • Now, if you will notice something carefully in the code then you will find the template message. Let’s understand the whole concept of template message(un-session message) and normal message(session message) and what’s actually the difference?

Let’s assume that you want to give an update to your customers related to their orders, reservations tickets, delivery status, etc. So, in that case, you cannot send normal random messages(session messages) to customers. You must to send the pre-approved templated message(un-session message) which must be verified from the Meta team in order to initiate a chat with your customer.

Once you receive the message from your customer then you can send as many as normal message to your customer within 24h session window. Once the window expires then you must again send the templated message.

Here is the link which you can use to see your all template messages in your account. You can also create your own custom template message.

  • If you want to send the normal session message to your customer then you can use this CURL request code.
curl --location --request POST 'https://graph.facebook.com/v13.0/<Your Phone number ID>/messages' \--header 'Authorization: Bearer <Your Temporary access token>' \--header 'Content-Type: application/json' \--data-raw '{"messaging_product":"whatsapp","recipient_type":"individual","to":"918587808915","type":"text","text": {"body":"Hello Rishabh!"}}'
  • If you want to send images, video, or mp3 media to your customer then you can check the official documentation or my StackOverflow answer. So, finally, we have completed the send message API. Now, let’s understand how to receive the WhatsApp message from your customer to our own server.

Setup the WhatsApp inbound message webhook to accept customers’ messages to your business number.

  • Click on the Configure webhooks link button.
  • Now, you will be redirected to the Configuration settings page. Click on the Configure a webhook link button.
  • Enter the full path of your server route or script and add the verification token(Random Hash) to identify the authenticity of the request. Once you click the Verify and Save button then you will get the API request from WhatsApp to your server webhook callback URL or script. Here is the message that you will get from WhatsApp to your server.
{"hub_mode":"subscribe","hub_challenge":"1379687428","hub_verify_token":"d40f067bd781d3e306ccb921ae15a698"}
  • Now, you need to respond back hub_challenge key. Here is the simple PHP script for your reference.
<?phpif($_SERVER['REQUEST_METHOD']=="GET"){    echo $_GET['hub_challenge']; //respond back hub_callenge key    http_response_code(200);}else{    $data = json_decode(file_get_contents('php://input'), true);    error_log(json_encode($data)); //print inbound message     }
  • Your webhook should be verified. Click on the Manage button then you will see the pop-up window, click the all Subscribe button. Here, you can see different types of events from WhatsApp. Suppose, if you want listen-only specific changes(message, message_template_status_update) then you can only subscribe to those events but in my case, I am subscribing to all events.
  • Now, send the message from your personal number to the WhatsApp business number and check the inbound message to your server. An inbound message should look like this
{"object":"whatsapp_business_account","entry":[{"id":"115730194473734","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"16469076883","phone_number_id":"111491931567355"},"contacts":[{"profile":{"name":"Rishabh Rawat"},"wa_id":"918587808715"}],"messages":[{"from":"918587805615","id":"wamid.HBgMOTE4NTg3ODA1NjE1FQIAEhggQjEwMjM1QzQyQUM4MEQ1MURCQjhBQjBFREFFMkQwM0MA","timestamp":"1653161271","text":{"body":"Thank you so much"},"type":"text"}]},"field":"messages"}]}]}
  • I set up the bot in my case. So, when I receive a message from WhatsApp then the bot will send a notification to me. Here in the screenshot, you can see the WhatsApp Inbound message JSON
  • If you will notice carefully the “Temporary access token” then you will see the message “ This token will expire in 23 hours”. Suppose, we want to send the message after 23 hours then the current access token will not work and you need to log in again Facebook developer page and click the refresh button in order to create a new one. This is literally a pain for us. Also, in that case, we cannot use automation tools like Zapier or Pabbly. Let’s create a never expired access token.

Setup never expires WhatsApp Cloud API access token

  • Login to your Facebook developer account and choose the WhatsApp app and then go to the Business settings page.
  • You will see the System users under the section of Users on the left sidebar. Click the Add button and you will get the pop-up window. Enter the user name and choose the admin as the system user role.
  • Now, your new system user should be created. Click on the Add Asserts on the current page(System user page) the pop-up will appear. Choose App>Select App Name>Full control option & click save changes button.
  • Now, click on the “WhatsApp Account” on the left sidebar and then select the WhatsApp business app and click the “Add people” button. Popup will appear, choose the recently created system user and check the full control and then click the Assign button.
  • Now, go back again to the system users page and select the recently created system user from the list and then click the “Generate new token” button.
  • Pop up will appear, choose the business app from the dropdown and make sure the whatsapp_business_management and whatsapp_business_messaging must be checked, if not then click on the checkbox and click the “Generate token” button.
  • The token should be generated at this time. Now, this token will not expire and live forever until and unless you do not click the revoke token button. You can use this token in the API instead of a temporary access token.
  • You can also verify the token scope from the Facebook token debugger tool and check the scope of the token added successfully or not.

Finally Done 🎉

Hope this has been helpful and you learned the WhatsApp Cloud API. Thank you for reading and feel free to reach out to me in case you need any help regarding WA cloud API. If you have any questions or want to improve this article then please comment below ✍🏻

References https://developers.facebook.com/docs/whatsapp/cloud-api/

Leave a reply