Files
chatwoot/app/services/whatsapp/webhook_setup_service.rb
c4a6a19e9b feat(voice): WhatsApp Cloud Calling — UI [6] (#14346)
## Summary

Frontend for WhatsApp Cloud Calling: header / contact-panel call
buttons, ringing widget, accept/reject/hangup, mute, in-bubble audio
player + transcript, recording-on-hangup upload, mid-call reload
warning. WebRTC is browser-direct to Meta — no media server bridge.

## Closes
- https://linear.app/chatwoot/issue/PLA-150

## How to test

Requires backend support — the controller, services, model changes, and
routes ship in **#14334** (`feature/pla-150`). Merge / deploy that first
(or simultaneously); the FE alone won't function without those
endpoints.

Then on staging, for a WhatsApp Cloud + embedded-signup inbox with the
new \`Configuration → Enable voice calling\` toggle ON and webhook
registered:

1. **Outbound** — open a conversation, click the phone icon in the
conversation header (or contact panel), grant mic, your phone rings,
answer, audio both ways, hang up. Recording + transcript land in the
bubble within ~10s.
2. **Inbound** — call the business number from your phone. The
FloatingCallWidget appears bottom-right with caller name. Click accept,
audio both ways, hang up. Recording + transcript appear.
3. **Mute** — during an active WhatsApp call, click the mic icon next to
hangup. Speech stops reaching Meta until you click again.
4. **Mid-call reload guard** — try `Cmd-R` during an active call;
browser shows a confirm prompt.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: iamsivin <iamsivin@gmail.com>
Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2026-05-22 18:42:39 +05:30

124 lines
4.3 KiB
Ruby

class Whatsapp::WebhookSetupService
def initialize(channel, waba_id = nil, access_token = nil)
@channel = channel
@waba_id = waba_id || channel.provider_config['business_account_id']
@access_token = access_token || channel.provider_config['api_key']
@api_client = Whatsapp::FacebookApiClient.new(@access_token)
end
def perform
validate_parameters!
# Register phone number if either condition is met:
# 1. Phone number is not verified (code_verification_status != 'VERIFIED')
# 2. Phone number needs registration (pending provisioning state)
register_phone_number if !phone_number_verified? || phone_number_needs_registration?
setup_webhook
end
def register_callback(subscribed_fields: nil)
validate_parameters!
setup_webhook(subscribed_fields: subscribed_fields)
end
private
def validate_parameters!
raise ArgumentError, 'Channel is required' if @channel.blank?
raise ArgumentError, 'WABA ID is required' if @waba_id.blank?
raise ArgumentError, 'Access token is required' if @access_token.blank?
end
def register_phone_number
phone_number_id = @channel.provider_config['phone_number_id']
pin = fetch_or_create_pin
@api_client.register_phone_number(phone_number_id, pin)
store_pin(pin)
rescue StandardError => e
Rails.logger.warn("[WHATSAPP] Phone registration failed but continuing: #{e.message}")
end
def fetch_or_create_pin
# Check if we have a stored PIN for this phone number
existing_pin = @channel.provider_config['verification_pin']
return existing_pin.to_i if existing_pin.present?
# Generate a new 6-digit PIN if none exists
SecureRandom.random_number(900_000) + 100_000
end
def store_pin(pin)
# Store the PIN in provider_config for future use
@channel.provider_config['verification_pin'] = pin
@channel.save!
end
def setup_webhook(subscribed_fields: nil)
callback_url = build_callback_url
verify_token = @channel.provider_config['webhook_verify_token']
args = [@waba_id, callback_url, verify_token]
if subscribed_fields
@api_client.subscribe_waba_webhook(*args, subscribed_fields: subscribed_fields)
else
@api_client.subscribe_waba_webhook(*args)
end
rescue StandardError => e
Rails.logger.error("[WHATSAPP] Webhook setup failed: #{e.message}")
raise "Webhook setup failed: #{e.message}"
end
def build_callback_url
frontend_url = ENV.fetch('FRONTEND_URL', nil)
phone_number = @channel.phone_number
"#{frontend_url}/webhooks/whatsapp/#{phone_number}"
end
def phone_number_verified?
phone_number_id = @channel.provider_config['phone_number_id']
# Check with WhatsApp API if the phone number code verification is complete
# This checks code_verification_status == 'VERIFIED'
verified = @api_client.phone_number_verified?(phone_number_id)
Rails.logger.info("[WHATSAPP] Phone number #{phone_number_id} code verification status: #{verified}")
verified
rescue StandardError => e
# If verification check fails, assume not verified to be safe
Rails.logger.error("[WHATSAPP] Phone verification status check failed: #{e.message}")
false
end
def phone_number_needs_registration?
# Check if phone is in pending provisioning state based on health data
# This is a separate check from phone_number_verified? which only checks code verification
phone_number_in_pending_state?
rescue StandardError => e
Rails.logger.error("[WHATSAPP] Phone registration check failed: #{e.message}")
# Conservative approach: don't register if we can't determine the state
false
end
def phone_number_in_pending_state?
health_service = Whatsapp::HealthService.new(@channel)
health_data = health_service.fetch_health_status
# Check if phone number is in "not provisioned" state based on health indicators
# These conditions indicate the number is pending and needs registration:
# - platform_type: "NOT_APPLICABLE" means not fully set up
# - throughput.level: "NOT_APPLICABLE" means no messaging capacity assigned
health_data[:platform_type] == 'NOT_APPLICABLE' ||
health_data.dig(:throughput, :level) == 'NOT_APPLICABLE'
rescue StandardError => e
Rails.logger.error("[WHATSAPP] Health status check failed: #{e.message}")
# If health check fails, assume registration is not needed to avoid errors
false
end
end