From 8dd7d9bf9b12ee179c8feea18ede1786d4bb2ed8 Mon Sep 17 00:00:00 2001 From: dvirlabs <114520947+dvirlabs@users.noreply.github.com> Date: Wed, 13 May 2026 11:39:17 +0300 Subject: [PATCH] Fix SSL --- backend/whatsapp.py | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/backend/whatsapp.py b/backend/whatsapp.py index e026547..410a5c2 100644 --- a/backend/whatsapp.py +++ b/backend/whatsapp.py @@ -3,6 +3,7 @@ WhatsApp Cloud API Service Handles sending WhatsApp messages via Meta's API """ import os +import ssl import httpx import certifi import re @@ -14,6 +15,34 @@ from datetime import datetime logger = logging.getLogger(__name__) +def create_http_client() -> httpx.AsyncClient: + """ + Create an httpx client with robust SSL configuration. + Tries to use system certificates first, falls back to certifi. + """ + try: + # Try using system SSL context with certifi certificates + ssl_context = ssl.create_default_context(cafile=certifi.where()) + # Enable hostname checking but allow some TLS flexibility + ssl_context.check_hostname = True + ssl_context.verify_mode = ssl.CERT_REQUIRED + # Use more compatible TLS versions + ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 + + return httpx.AsyncClient(verify=ssl_context, timeout=30.0) + except Exception as e: + logger.warning(f"[WhatsApp] Failed to create SSL context with certifi: {e}. Trying default SSL.") + try: + # Fallback to default SSL context + ssl_context = ssl.create_default_context() + ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 + return httpx.AsyncClient(verify=ssl_context, timeout=30.0) + except Exception as e2: + logger.error(f"[WhatsApp] Failed to create SSL context: {e2}. Using basic client.") + # Last resort fallback - httpx will use its own SSL handling + return httpx.AsyncClient(timeout=30.0) + + class WhatsAppError(Exception): """Custom exception for WhatsApp API errors""" pass @@ -166,7 +195,7 @@ class WhatsAppService: url = f"{self.base_url}/{self.phone_number_id}/messages" try: - async with httpx.AsyncClient(verify=certifi.where()) as client: + async with create_http_client() as client: response = await client.post( url, json=payload, @@ -296,7 +325,7 @@ class WhatsAppService: print("=" * 80 + "\n") try: - async with httpx.AsyncClient(verify=certifi.where()) as client: + async with create_http_client() as client: response = await client.post( url, json=payload, @@ -559,7 +588,7 @@ class WhatsAppService: url = f"{self.base_url}/{self.phone_number_id}/messages" try: - async with httpx.AsyncClient(verify=certifi.where()) as client: + async with create_http_client() as client: response = await client.post( url, json=payload,