This commit is contained in:
parent
5182899553
commit
8dd7d9bf9b
@ -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,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user