File size: 3,258 Bytes
2ff42c3
284af3b
4415b9c
953d0c7
2ff42c3
 
 
284af3b
9c3e8e7
56a1090
9c3e8e7
56a1090
6e7aa15
9c3e8e7
 
 
284af3b
 
 
56a1090
284af3b
 
 
 
9c3e8e7
56a1090
 
9c3e8e7
 
 
56a1090
 
 
 
 
9c3e8e7
 
56a1090
 
 
 
 
284af3b
4415b9c
284af3b
4415b9c
 
953d0c7
4415b9c
 
ddf861f
4415b9c
953d0c7
4415b9c
953d0c7
 
 
 
 
 
 
9c3e8e7
 
 
 
 
 
 
 
953d0c7
 
 
 
 
ddf861f
 
 
 
 
953d0c7
 
 
4415b9c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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"

@app.get("/webhook")
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)

@app.post("/webhook")
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"}