Fix SSL
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
dvirlabs 2026-05-13 11:39:17 +03:00
parent 5182899553
commit 8dd7d9bf9b

View File

@ -3,6 +3,7 @@ WhatsApp Cloud API Service
Handles sending WhatsApp messages via Meta's API Handles sending WhatsApp messages via Meta's API
""" """
import os import os
import ssl
import httpx import httpx
import certifi import certifi
import re import re
@ -14,6 +15,34 @@ from datetime import datetime
logger = logging.getLogger(__name__) 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): class WhatsAppError(Exception):
"""Custom exception for WhatsApp API errors""" """Custom exception for WhatsApp API errors"""
pass pass
@ -166,7 +195,7 @@ class WhatsAppService:
url = f"{self.base_url}/{self.phone_number_id}/messages" url = f"{self.base_url}/{self.phone_number_id}/messages"
try: try:
async with httpx.AsyncClient(verify=certifi.where()) as client: async with create_http_client() as client:
response = await client.post( response = await client.post(
url, url,
json=payload, json=payload,
@ -296,7 +325,7 @@ class WhatsAppService:
print("=" * 80 + "\n") print("=" * 80 + "\n")
try: try:
async with httpx.AsyncClient(verify=certifi.where()) as client: async with create_http_client() as client:
response = await client.post( response = await client.post(
url, url,
json=payload, json=payload,
@ -559,7 +588,7 @@ class WhatsAppService:
url = f"{self.base_url}/{self.phone_number_id}/messages" url = f"{self.base_url}/{self.phone_number_id}/messages"
try: try:
async with httpx.AsyncClient(verify=certifi.where()) as client: async with create_http_client() as client:
response = await client.post( response = await client.post(
url, url,
json=payload, json=payload,