mirror of
https://github.com/lingble/chatwoot.git
synced 2025-12-25 15:17:02 +00:00
Fixes https://linear.app/chatwoot/issue/CW-5692/whatsapp-es-numbers-stuck-in-pending-due-to-premature-registration ### Problem Multiple customers reported that their WhatsApp numbers remain stuck in **Pending** in WhatsApp Manager even after successful onboarding. - Our system triggers a **registration call** (`/<PHONE_NUMBER_ID>/register`) as soon as the number is OTP verified. - In many cases, Meta hasn’t finished **display name review/provisioning**, so the call fails with: ``` code: 100, error_subcode: 2388001 error_user_title: "Cannot Create Certificate" error_user_msg: "Your display name could not be processed. Please edit your display name and try again." ``` - This leaves the number stuck in Pending, no messaging can start until we manually retry registration. - Some customers have reported being stuck in this state for **7+ days**. ### Root cause - We only check `code_verification_status = VERIFIED` before attempting registration. - We **don’t wait** for display name provisioning (`name_status` / `platform_type`) to be complete. - As a result, registration fails prematurely and the number never transitions out of Pending. ### Solution #### 1. Health Status Monitoring - Build a backend service to fetch **real-time health data** from Graph API: - `code_verification_status` - `name_status` / `display_name_status` - `platform_type` - `throughput.level` - `messaging_limit_tier` - `quality_rating` - Expose health data via API (`/api/v1/accounts/:account_id/inboxes/:id/health`). - Display this in the UI as an **Account Health tab** with clear badges and direct links to WhatsApp Manager. #### 2. Smarter Registration Logic - Update `WebhookSetupService` to include a **dual-condition check**: - Register if: 1. Phone is **not verified**, OR 2. Phone is **verified but provisioning incomplete** (`platform_type = NOT_APPLICABLE`, `throughput.level = NOT_APPLICABLE`). - Skip registration if number is already provisioned. - Retry registration automatically when stuck. - Provide a UI banner with complete registration button so customers can retry without manual support. ### Screenshot <img width="2292" height="1344" alt="CleanShot 2025-09-30 at 16 01 03@2x" src="https://github.com/user-attachments/assets/1c417d2a-b11c-475e-b092-3c5671ee59a7" /> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
117 lines
4.0 KiB
Ruby
117 lines
4.0 KiB
Ruby
class Whatsapp::WebhookSetupService
|
|
def initialize(channel, waba_id, access_token)
|
|
@channel = channel
|
|
@waba_id = waba_id
|
|
@access_token = access_token
|
|
@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
|
|
|
|
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}")
|
|
# Continue with webhook setup even if registration fails
|
|
# This is just a warning, not a blocking error
|
|
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
|
|
callback_url = build_callback_url
|
|
verify_token = @channel.provider_config['webhook_verify_token']
|
|
|
|
@api_client.subscribe_waba_webhook(@waba_id, callback_url, verify_token)
|
|
|
|
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
|