feat: Enhanced WhatsApp template support with media headers (#11997)
This commit is contained in:
148
app/services/whatsapp/populate_template_parameters_service.rb
Normal file
148
app/services/whatsapp/populate_template_parameters_service.rb
Normal file
@@ -0,0 +1,148 @@
|
||||
class Whatsapp::PopulateTemplateParametersService
|
||||
def build_parameter(value)
|
||||
case value
|
||||
when String
|
||||
build_string_parameter(value)
|
||||
when Hash
|
||||
build_hash_parameter(value)
|
||||
else
|
||||
{ type: 'text', text: value.to_s }
|
||||
end
|
||||
end
|
||||
|
||||
def build_button_parameter(button)
|
||||
return { type: 'text', text: '' } if button.blank?
|
||||
|
||||
case button['type']
|
||||
when 'copy_code'
|
||||
coupon_code = button['parameter'].to_s.strip
|
||||
raise ArgumentError, 'Coupon code cannot be empty' if coupon_code.blank?
|
||||
raise ArgumentError, 'Coupon code cannot exceed 15 characters' if coupon_code.length > 15
|
||||
|
||||
{
|
||||
type: 'coupon_code',
|
||||
coupon_code: coupon_code
|
||||
}
|
||||
else
|
||||
# For URL buttons and other button types, treat parameter as text
|
||||
# If parameter is blank, use empty string (required for URL buttons)
|
||||
{ type: 'text', text: button['parameter'].to_s.strip }
|
||||
end
|
||||
end
|
||||
|
||||
def build_media_parameter(url, media_type)
|
||||
return nil if url.blank?
|
||||
|
||||
sanitized_url = sanitize_parameter(url)
|
||||
validate_url(sanitized_url)
|
||||
build_media_type_parameter(sanitized_url, media_type.downcase)
|
||||
end
|
||||
|
||||
def build_named_parameter(parameter_name, value)
|
||||
sanitized_value = sanitize_parameter(value.to_s)
|
||||
{ type: 'text', parameter_name: parameter_name, text: sanitized_value }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_string_parameter(value)
|
||||
sanitized_value = sanitize_parameter(value)
|
||||
if rich_formatting?(sanitized_value)
|
||||
build_rich_text_parameter(sanitized_value)
|
||||
else
|
||||
{ type: 'text', text: sanitized_value }
|
||||
end
|
||||
end
|
||||
|
||||
def build_hash_parameter(value)
|
||||
case value['type']
|
||||
when 'currency'
|
||||
build_currency_parameter(value)
|
||||
when 'date_time'
|
||||
build_date_time_parameter(value)
|
||||
else
|
||||
{ type: 'text', text: value.to_s }
|
||||
end
|
||||
end
|
||||
|
||||
def build_currency_parameter(value)
|
||||
{
|
||||
type: 'currency',
|
||||
currency: {
|
||||
fallback_value: value['fallback_value'],
|
||||
code: value['code'],
|
||||
amount_1000: value['amount_1000']
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def build_date_time_parameter(value)
|
||||
{
|
||||
type: 'date_time',
|
||||
date_time: {
|
||||
fallback_value: value['fallback_value'],
|
||||
day_of_week: value['day_of_week'],
|
||||
day_of_month: value['day_of_month'],
|
||||
month: value['month'],
|
||||
year: value['year']
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def build_media_type_parameter(sanitized_url, media_type)
|
||||
case media_type
|
||||
when 'image'
|
||||
build_image_parameter(sanitized_url)
|
||||
when 'video'
|
||||
build_video_parameter(sanitized_url)
|
||||
when 'document'
|
||||
build_document_parameter(sanitized_url)
|
||||
else
|
||||
raise ArgumentError, "Unsupported media type: #{media_type}"
|
||||
end
|
||||
end
|
||||
|
||||
def build_image_parameter(url)
|
||||
{ type: 'image', image: { link: url } }
|
||||
end
|
||||
|
||||
def build_video_parameter(url)
|
||||
{ type: 'video', video: { link: url } }
|
||||
end
|
||||
|
||||
def build_document_parameter(url)
|
||||
{ type: 'document', document: { link: url } }
|
||||
end
|
||||
|
||||
def rich_formatting?(text)
|
||||
# Check if text contains WhatsApp rich formatting markers
|
||||
text.match?(/\*[^*]+\*/) || # Bold: *text*
|
||||
text.match?(/_[^_]+_/) || # Italic: _text_
|
||||
text.match?(/~[^~]+~/) || # Strikethrough: ~text~
|
||||
text.match?(/```[^`]+```/) # Monospace: ```text```
|
||||
end
|
||||
|
||||
def build_rich_text_parameter(text)
|
||||
# WhatsApp supports rich text formatting in templates
|
||||
# This preserves the formatting markers for the API
|
||||
{ type: 'text', text: text }
|
||||
end
|
||||
|
||||
def sanitize_parameter(value)
|
||||
# Basic sanitization - remove dangerous characters and limit length
|
||||
sanitized = value.to_s.strip
|
||||
sanitized = sanitized.gsub(/[<>\"']/, '') # Remove potential HTML/JS chars
|
||||
sanitized[0...1000] # Limit length to prevent DoS
|
||||
end
|
||||
|
||||
def validate_url(url)
|
||||
return if url.blank?
|
||||
|
||||
uri = URI.parse(url)
|
||||
raise ArgumentError, "Invalid URL scheme: #{uri.scheme}. Only http and https are allowed" unless %w[http https].include?(uri.scheme)
|
||||
raise ArgumentError, 'URL too long (max 2000 characters)' if url.length > 2000
|
||||
|
||||
rescue URI::InvalidURIError => e
|
||||
raise ArgumentError, "Invalid URL format: #{e.message}. Please enter a valid URL like https://example.com/document.pdf"
|
||||
end
|
||||
end
|
||||
@@ -106,10 +106,7 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
|
||||
policy: 'deterministic',
|
||||
code: template_info[:lang_code]
|
||||
},
|
||||
components: [{
|
||||
type: 'body',
|
||||
parameters: template_info[:parameters]
|
||||
}]
|
||||
components: template_info[:parameters]
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -12,15 +12,20 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
end
|
||||
|
||||
def send_template(phone_number, template_info)
|
||||
template_body = template_body_parameters(template_info)
|
||||
|
||||
request_body = {
|
||||
messaging_product: 'whatsapp',
|
||||
recipient_type: 'individual', # Only individual messages supported (not group messages)
|
||||
to: phone_number,
|
||||
type: 'template',
|
||||
template: template_body
|
||||
}
|
||||
|
||||
response = HTTParty.post(
|
||||
"#{phone_id_path}/messages",
|
||||
headers: api_headers,
|
||||
body: {
|
||||
messaging_product: 'whatsapp',
|
||||
to: phone_number,
|
||||
template: template_body_parameters(template_info),
|
||||
type: 'template'
|
||||
}.to_json
|
||||
body: request_body.to_json
|
||||
)
|
||||
|
||||
process_response(response)
|
||||
@@ -119,17 +124,36 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
|
||||
end
|
||||
|
||||
def template_body_parameters(template_info)
|
||||
{
|
||||
template_body = {
|
||||
name: template_info[:name],
|
||||
language: {
|
||||
policy: 'deterministic',
|
||||
code: template_info[:lang_code]
|
||||
},
|
||||
components: [{
|
||||
type: 'body',
|
||||
parameters: template_info[:parameters]
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
# Enhanced template parameters structure
|
||||
# Note: Legacy format support (simple parameter arrays) has been removed
|
||||
# in favor of the enhanced component-based structure that supports
|
||||
# headers, buttons, and authentication templates.
|
||||
#
|
||||
# Expected payload format from frontend:
|
||||
# {
|
||||
# processed_params: {
|
||||
# body: { '1': 'John', '2': '123 Main St' },
|
||||
# header: { media_url: 'https://...', media_type: 'image' },
|
||||
# buttons: [{ type: 'url', parameter: 'otp123456' }]
|
||||
# }
|
||||
# }
|
||||
# This gets transformed into WhatsApp API component format:
|
||||
# [
|
||||
# { type: 'body', parameters: [...] },
|
||||
# { type: 'header', parameters: [...] },
|
||||
# { type: 'button', sub_type: 'url', parameters: [...] }
|
||||
# ]
|
||||
template_body[:components] = template_info[:parameters] || []
|
||||
|
||||
template_body
|
||||
end
|
||||
|
||||
def whatsapp_reply_context(message)
|
||||
|
||||
117
app/services/whatsapp/template_parameter_converter_service.rb
Normal file
117
app/services/whatsapp/template_parameter_converter_service.rb
Normal file
@@ -0,0 +1,117 @@
|
||||
# Service to convert legacy WhatsApp template parameter formats to enhanced format
|
||||
#
|
||||
# Legacy formats (deprecated):
|
||||
# - Array: ["John", "Order123"] - positional parameters
|
||||
# - Flat Hash: {"1": "John", "2": "Order123"} - direct key-value mapping
|
||||
#
|
||||
# Enhanced format:
|
||||
# - Component-based: {"body": {"1": "John", "2": "Order123"}} - structured by template components
|
||||
# - Supports header, body, footer, and button parameters separately
|
||||
#
|
||||
class Whatsapp::TemplateParameterConverterService
|
||||
def initialize(template_params, template)
|
||||
@template_params = template_params
|
||||
@template = template
|
||||
end
|
||||
|
||||
def normalize_to_enhanced
|
||||
processed_params = @template_params['processed_params']
|
||||
|
||||
# Early return if already enhanced format
|
||||
return @template_params if enhanced_format?(processed_params)
|
||||
|
||||
# Mark as legacy format before conversion for tracking
|
||||
@template_params['format_version'] = 'legacy'
|
||||
|
||||
# Convert legacy formats to enhanced structure
|
||||
# TODO: Legacy format support will be deprecated and removed after 2-3 releases
|
||||
enhanced_params = convert_legacy_to_enhanced(processed_params, @template)
|
||||
|
||||
# Replace original params with enhanced structure
|
||||
@template_params['processed_params'] = enhanced_params
|
||||
|
||||
@template_params
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def enhanced_format?(processed_params)
|
||||
return false unless processed_params.is_a?(Hash)
|
||||
|
||||
# Enhanced format has component-based structure
|
||||
component_keys = %w[body header footer buttons]
|
||||
has_component_structure = processed_params.keys.any? { |k| component_keys.include?(k) }
|
||||
|
||||
# Additional validation for enhanced format
|
||||
if has_component_structure
|
||||
validate_enhanced_structure(processed_params)
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
def validate_enhanced_structure(params)
|
||||
valid_body?(params['body']) &&
|
||||
valid_header?(params['header']) &&
|
||||
valid_buttons?(params['buttons'])
|
||||
end
|
||||
|
||||
def valid_body?(body)
|
||||
body.nil? || body.is_a?(Hash)
|
||||
end
|
||||
|
||||
def valid_header?(header)
|
||||
header.nil? || header.is_a?(Hash)
|
||||
end
|
||||
|
||||
def valid_buttons?(buttons)
|
||||
return true if buttons.nil?
|
||||
return false unless buttons.is_a?(Array)
|
||||
|
||||
buttons.all? { |b| b.is_a?(Hash) && b['type'] }
|
||||
end
|
||||
|
||||
def convert_legacy_to_enhanced(legacy_params, _template)
|
||||
# Legacy system only supported text-based templates with body parameters
|
||||
# We only convert the parameter format, not add new features
|
||||
|
||||
enhanced = {}
|
||||
|
||||
case legacy_params
|
||||
when Array
|
||||
# Array format: ["John", "Order123"] → {body: {"1": "John", "2": "Order123"}}
|
||||
body_params = convert_array_to_body_params(legacy_params)
|
||||
enhanced['body'] = body_params unless body_params.empty?
|
||||
when Hash
|
||||
# Hash format: {"1": "John", "name": "Jane"} → {body: {"1": "John", "name": "Jane"}}
|
||||
body_params = convert_hash_to_body_params(legacy_params)
|
||||
enhanced['body'] = body_params unless body_params.empty?
|
||||
else
|
||||
raise ArgumentError, "Unknown legacy format: #{legacy_params.class}"
|
||||
end
|
||||
|
||||
enhanced
|
||||
end
|
||||
|
||||
def convert_array_to_body_params(params_array)
|
||||
return {} if params_array.empty?
|
||||
|
||||
body_params = {}
|
||||
params_array.each_with_index do |value, index|
|
||||
body_params[(index + 1).to_s] = value.to_s
|
||||
end
|
||||
|
||||
body_params
|
||||
end
|
||||
|
||||
def convert_hash_to_body_params(params_hash)
|
||||
return {} if params_hash.empty?
|
||||
|
||||
body_params = {}
|
||||
params_hash.each do |key, value|
|
||||
body_params[key.to_s] = value.to_s
|
||||
end
|
||||
|
||||
body_params
|
||||
end
|
||||
end
|
||||
@@ -2,11 +2,9 @@ class Whatsapp::TemplateProcessorService
|
||||
pattr_initialize [:channel!, :template_params, :message]
|
||||
|
||||
def call
|
||||
if template_params.present?
|
||||
process_template_with_params
|
||||
else
|
||||
process_template_from_message
|
||||
end
|
||||
return [nil, nil, nil, nil] if template_params.blank?
|
||||
|
||||
process_template_with_params
|
||||
end
|
||||
|
||||
private
|
||||
@@ -20,51 +18,6 @@ class Whatsapp::TemplateProcessorService
|
||||
]
|
||||
end
|
||||
|
||||
def process_template_from_message
|
||||
return [nil, nil, nil, nil] if message.blank?
|
||||
|
||||
# Delete the following logic once the update for template_params is stable
|
||||
# see if we can match the message content to a template
|
||||
# An example template may look like "Your package has been shipped. It will be delivered in {{1}} business days.
|
||||
# We want to iterate over these templates with our message body and see if we can fit it to any of the templates
|
||||
# Then we use regex to parse the template varibles and convert them into the proper payload
|
||||
channel.message_templates&.each do |template|
|
||||
match_obj = template_match_object(template)
|
||||
next if match_obj.blank?
|
||||
|
||||
# we have a match, now we need to parse the template variables and convert them into the wa recommended format
|
||||
processed_parameters = match_obj.captures.map { |x| { type: 'text', text: x } }
|
||||
|
||||
# no need to look up further end the search
|
||||
return [template['name'], template['namespace'], template['language'], processed_parameters]
|
||||
end
|
||||
[nil, nil, nil, nil]
|
||||
end
|
||||
|
||||
def template_match_object(template)
|
||||
body_object = validated_body_object(template)
|
||||
return if body_object.blank?
|
||||
|
||||
template_match_regex = build_template_match_regex(body_object['text'])
|
||||
message.outgoing_content.match(template_match_regex)
|
||||
end
|
||||
|
||||
def build_template_match_regex(template_text)
|
||||
# Converts the whatsapp template to a comparable regex string to check against the message content
|
||||
# the variables are of the format {{num}} ex:{{1}}
|
||||
|
||||
# transform the template text into a regex string
|
||||
# we need to replace the {{num}} with matchers that can be used to capture the variables
|
||||
template_text = template_text.gsub(/{{\d}}/, '(.*)')
|
||||
# escape if there are regex characters in the template text
|
||||
template_text = Regexp.escape(template_text)
|
||||
# ensuring only the variables remain as capture groups
|
||||
template_text = template_text.gsub(Regexp.escape('(.*)'), '(.*)')
|
||||
|
||||
template_match_string = "^#{template_text}$"
|
||||
Regexp.new template_match_string
|
||||
end
|
||||
|
||||
def find_template
|
||||
channel.message_templates.find do |t|
|
||||
t['name'] == template_params['name'] && t['language'] == template_params['language'] && t['status']&.downcase == 'approved'
|
||||
@@ -75,21 +28,100 @@ class Whatsapp::TemplateProcessorService
|
||||
template = find_template
|
||||
return if template.blank?
|
||||
|
||||
parameter_format = template['parameter_format']
|
||||
# Convert legacy format to enhanced format before processing
|
||||
converter = Whatsapp::TemplateParameterConverterService.new(template_params, template)
|
||||
normalized_params = converter.normalize_to_enhanced
|
||||
|
||||
if parameter_format == 'NAMED'
|
||||
template_params['processed_params']&.map { |key, value| { type: 'text', parameter_name: key, text: value } }
|
||||
else
|
||||
template_params['processed_params']&.map { |_, value| { type: 'text', text: value } }
|
||||
end
|
||||
process_enhanced_template_params(template, normalized_params['processed_params'])
|
||||
end
|
||||
|
||||
def validated_body_object(template)
|
||||
# we don't care if its not approved template
|
||||
return if template['status'] != 'approved'
|
||||
def process_enhanced_template_params(template, processed_params = nil)
|
||||
processed_params ||= template_params['processed_params']
|
||||
components = []
|
||||
|
||||
# we only care about text body object in template. if not present we discard the template
|
||||
# we don't support other forms of templates
|
||||
template['components'].find { |obj| obj['type'] == 'BODY' && obj.key?('text') }
|
||||
components.concat(process_header_components(processed_params))
|
||||
components.concat(process_body_components(processed_params, template))
|
||||
components.concat(process_footer_components(processed_params))
|
||||
components.concat(process_button_components(processed_params))
|
||||
|
||||
@template_params = components
|
||||
end
|
||||
|
||||
def process_header_components(processed_params)
|
||||
return [] if processed_params['header'].blank?
|
||||
|
||||
header_params = build_header_params(processed_params['header'])
|
||||
header_params.present? ? [{ type: 'header', parameters: header_params }] : []
|
||||
end
|
||||
|
||||
def build_header_params(header_data)
|
||||
header_params = []
|
||||
header_data.each do |key, value|
|
||||
next if value.blank?
|
||||
|
||||
if media_url_with_type?(key, header_data)
|
||||
media_param = parameter_builder.build_media_parameter(value, header_data['media_type'])
|
||||
header_params << media_param if media_param
|
||||
elsif key != 'media_type'
|
||||
header_params << parameter_builder.build_parameter(value)
|
||||
end
|
||||
end
|
||||
header_params
|
||||
end
|
||||
|
||||
def media_url_with_type?(key, header_data)
|
||||
key == 'media_url' && header_data['media_type'].present?
|
||||
end
|
||||
|
||||
def process_body_components(processed_params, template)
|
||||
return [] if processed_params['body'].blank?
|
||||
|
||||
body_params = processed_params['body'].filter_map do |key, value|
|
||||
next if value.blank?
|
||||
|
||||
parameter_format = template['parameter_format']
|
||||
if parameter_format == 'NAMED'
|
||||
parameter_builder.build_named_parameter(key, value)
|
||||
else
|
||||
parameter_builder.build_parameter(value)
|
||||
end
|
||||
end
|
||||
|
||||
body_params.present? ? [{ type: 'body', parameters: body_params }] : []
|
||||
end
|
||||
|
||||
def process_footer_components(processed_params)
|
||||
return [] if processed_params['footer'].blank?
|
||||
|
||||
footer_params = processed_params['footer'].filter_map do |_, value|
|
||||
next if value.blank?
|
||||
|
||||
parameter_builder.build_parameter(value)
|
||||
end
|
||||
|
||||
footer_params.present? ? [{ type: 'footer', parameters: footer_params }] : []
|
||||
end
|
||||
|
||||
def process_button_components(processed_params)
|
||||
return [] if processed_params['buttons'].blank?
|
||||
|
||||
button_params = processed_params['buttons'].filter_map.with_index do |button, index|
|
||||
next if button.blank?
|
||||
|
||||
if button['type'] == 'url' || button['parameter'].present?
|
||||
{
|
||||
type: 'button',
|
||||
sub_type: button['type'] || 'url',
|
||||
index: index,
|
||||
parameters: [parameter_builder.build_button_parameter(button)]
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
button_params.compact
|
||||
end
|
||||
|
||||
def parameter_builder
|
||||
@parameter_builder ||= Whatsapp::PopulateTemplateParametersService.new
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user