Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Request | |
| from fastapi.responses import PlainTextResponse | |
| from datetime import datetime, timezone, timedelta | |
| import requests | |
| app = FastAPI() | |
| VERIFY_TOKEN = "my_secure_token" | |
| PAGE_ACCESS_TOKEN = "EAAJGMsgQEhMBO0FxGBA1ZBKVIM6HmYYDK9stTrz4XjgN7PDOnkgH3g5WScFZBIVp6ZBXEN4rEsRuelZChxDnELXfojjkXyw9WUcZBYevkinXRIYsdjGZAGQ6QK2MDmnlX6mW4tD4uKzcpKxaaRDzPFouM51Vn6Yx5tatqYJyPBd39z1391QtEzTWWp8CS1BXuBdAJ078l4QF1uQ1ybQ4k4eksZD" | |
| APP_ID = "640133872226835" | |
| APP_SECRET = "01602f51d9aa49953064fda7c507ed7c" | |
| REDIRECT_URI = "https://mr-help-binrushd-meta-authenticator.hf.space/webhook" | |
| # ✅ رابط GAS WebApp (اللي بينتهي بـ /exec) | |
| GAS_WEBAPP_URL = "https://script.google.com/macros/s/AKfycbzmFQvZtpwhO6r3aDbBUhYJAb_1N94DMRT4MnZScIsTi9EMzODkHk7ICEyuH77vFv1E/exec" | |
| async def verify_webhook(request: Request): | |
| params = request.query_params | |
| code = params.get("code") | |
| mode = params.get("hub.mode") | |
| token = params.get("hub.verify_token") | |
| challenge = params.get("hub.challenge") | |
| # ✅ OAuth2 token exchange عبر GAS بدل graph.facebook.com | |
| if code: | |
| print(f"🔑 Received code: {code}") | |
| gas_payload = { | |
| "action": "exchange_code", | |
| "client_id": APP_ID, | |
| "redirect_uri": REDIRECT_URI, | |
| "client_secret": APP_SECRET, | |
| "code": code | |
| } | |
| response = requests.post(GAS_WEBAPP_URL, json=gas_payload, timeout=20) | |
| print("🎟️ Token Exchange Response:") | |
| print(response.json()) | |
| return PlainTextResponse("Token exchange completed") | |
| # Webhook verification logic | |
| if mode == "subscribe" and token == VERIFY_TOKEN: | |
| return PlainTextResponse(content=challenge) | |
| return PlainTextResponse(content="Verification failed", status_code=403) | |
| async def receive_webhook(request: Request): | |
| payload = await request.json() | |
| print("📥 Webhook payload received:") | |
| gmt_plus_3 = timezone(timedelta(hours=3)) | |
| print("Timestamp:", datetime.now(gmt_plus_3).strftime('%Y-%m-%d %H:%M:%S')) | |
| try: | |
| for entry in payload.get("entry", []): | |
| for change in entry.get("changes", []): | |
| if change.get("field") == "leadgen": | |
| lead_id = change["value"]["leadgen_id"] | |
| print(f"🔍 Lead ID: {lead_id}") | |
| # ✅ Fetch lead details عبر GAS بدل graph.facebook.com | |
| gas_payload = { | |
| "action": "fetch_lead", | |
| "lead_id": lead_id, | |
| "access_token": PAGE_ACCESS_TOKEN | |
| } | |
| lead_resp = requests.post(GAS_WEBAPP_URL, json=gas_payload, timeout=20) | |
| lead_data = lead_resp.json() | |
| print("📄 Lead Details:") | |
| print(lead_data) | |
| for item in lead_data.get("field_data", []): | |
| field_name = item.get("name") | |
| field_value = ", ".join(item.get("values", [])) | |
| print(f"{field_name}: {field_value}") | |
| except Exception as e: | |
| print(f"⚠️ Error processing lead: {e}") | |
| return {"status": "ok"} | |