Receive Response from a Quick Reply Button in an Interactive Templated Message

Overview

This guide covers how to receive webhook response when a user clicks on a quick reply button in an interactive templated message.

Prerequisites

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.

Create a Rails controller to receive 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.

include Plivo
include Plivo::XML

class PlivoController < ApplicationController
  protect_from_forgery with: :null_session

  def inbound
    request_body = request.body.read
    webhook = JSON.parse(request_body)

    if webhook.nil?
      render json: { error: 'Invalid JSON' }, status: :bad_request
      return
    end

    from_number = webhook['From']
    to_number = webhook['To']
    content_type = webhook['ContentType']
    media0 = webhook['Media0']
    body = webhook['Body']
    context_message_uuid = webhook['Context']&.fetch('MessageUUID', nil)
    button_text = webhook['Button']&.fetch('Text', nil)
    button_payload = webhook['Button']&.fetch('Payload', nil)

    case content_type
    when 'text'
      puts "Text Message received - From: #{from_number}, To: #{to_number}, Text: #{body}"
    when 'media'
      puts "Media Message received - From: #{from_number}, To: #{to_number}, Media Attachment: #{media0}, Caption: #{body}"
    when 'button'
      puts "Button Message received - From: #{from_number}, To: #{to_number}, Button Text: #{button_text}, Button Payload: #{button_payload}"
    end

    if context_message_uuid
      puts "Context Message UUID: #{context_message_uuid}"
    end

    render json: { message: 'Message Received' }, status: :ok
  end
end

Configure a webhook URL in your WhatsApp Business Account

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.

Test

Send a WhatsApp message to the Plivo number you specified using WhatsApp application.