This guide explains how to handle webhook responses when you receive inbound messages or interactions from your users on your WhatsApp number. The following use cases are covered in the code snippets below:
To get started, you need a Plivo account — sign up with your work email address if you don’t have one already. If this is your first time using Plivo APIs, follow our instructions to set up a Ruby development environment.
You must have an onboarded WhatsApp account to receive inbound messages. If a number is listed as connected, it can receive inbound messages.
Change to the project directory and run this command to create a Rails controller for inbound messages.
$ rails generate controller Plivo whatsapp
This command generates a controller named plivo_controller in the app/controllers/ directory and a respective view in app/views/plivo. We can delete the view as we don’t need it.
$ rm app/views/plivo/whatsapp.html.erb
Edit the app/controllers/plivo_controller.rb file and paste this code into the PlivoController class.
class WhatsappController < ApplicationController
skip_before_action :verify_authenticity_token
def receive
data = JSON.parse(request.body.read)
from_number = data['From']
to_number = data['To']
content_type = data['ContentType']
case content_type
when 'text'
puts "Text Message - From: #{from_number}, To: #{to_number}, Text: #{data['Body']}"
when 'media'
puts "Media Message - From: #{from_number}, To: #{to_number}, URL: #{data['Media0']}, Caption: #{data['Body']}"
when 'button'
puts "Button Message - From: #{from_number}, To: #{to_number}, Text: #{data['Button']['Text']}, Payload: #{data['Button']['Payload']}"
when 'interactive'
interactive = data['Interactive']
if interactive['Type'] == 'button_reply'
puts "Interactive Button - From: #{from_number}, To: #{to_number}, ID: #{interactive['ButtonReply']['Id']}, Title: #{interactive['ButtonReply']['Title']}"
elsif interactive['Type'] == 'list_reply'
puts "Interactive List - From: #{from_number}, To: #{to_number}, ID: #{interactive['ListReply']['Id']}, Title: #{interactive['ListReply']['Title']}, Description: #{interactive['ListReply']['Description']}"
end
when 'location'
location = data['Location']
puts "Location - From: #{from_number}, To: #{to_number}, Latitude: #{location['Latitude']}, Longitude: #{location['Longitude']}, Name: #{location['Name']}, Address: #{location['Address']}"
end
render json: { message: 'Message Received' }, status: :ok
end
end
Add or update a webhook URL from this link to a WhatsApp Business Account. Once you’ve done this, you should be able to receive inbound messages.
Send a WhatsApp message to the Plivo number you specified using WhatsApp application.