File size: 3,498 Bytes
e5c6457
a854e2d
e5c6457
 
2ff42c3
 
 
e5c6457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f18b5a0
e5c6457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import os
import requests
from fastapi import FastAPI, Request
from datetime import datetime, timezone, timedelta

app = FastAPI()

# Load Supabase environment variables
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_API_KEY = os.getenv("SUPABASE_API_KEY")

@app.post("/webhook")
async def receive_webhook(request: Request):
    payload = await request.json()
    
    print("📥 Webhook received:")

    gmt_plus_3 = timezone(timedelta(hours=3))

    # Top-level fields
    print(f"Request ID: {payload.get('request_id')}")
    print(f"Object: {payload.get('object')}")
    print(f"Time (Unix): {payload.get('time')}")
    try:
        formatted_time = datetime.fromtimestamp(payload.get('time'), gmt_plus_3).strftime('%Y-%m-%d %H:%M:%S GMT+3')
        print(f"Time (Formatted): {formatted_time}")
    except Exception:
        print("Time (Formatted): Invalid timestamp")
    print("----")

    # Loop through entries
    for entry in payload.get('entry', []):
        lead_id = entry.get('id')
        campaign_id = entry.get('campaign_id')
        campaign_name = entry.get('campaign_name')
        adset_id = entry.get('adgroup_id')
        adset_name = entry.get('adgroup_name')
        ad_id = entry.get('ad_id')
        ad_name = entry.get('ad_name')
        advertiser_id = entry.get('advertiser_id')
        create_ts = entry.get('create_time')

        print(f"Lead ID: {lead_id}")
        print(f"Campaign ID: {campaign_id}")
        print(f"Campaign Name: {campaign_name}")
        print(f"Ad Group ID: {adset_id}")
        print(f"Ad Group Name: {adset_name}")
        print(f"Ad ID: {ad_id}")
        print(f"Ad Name: {ad_name}")
        try:
            formatted_create_time = datetime.fromtimestamp(create_ts, gmt_plus_3).isoformat()
            print(f"Create Time: {formatted_create_time}")
        except Exception:
            formatted_create_time = None
            print("Create Time: Invalid")

        # Extract lead fields
        field_map = {}
        for change in entry.get('changes', []):
            field = change.get('field').lower()
            value = change.get('value')
            field_map[field] = value
            print(f"{field}: {value}")

        print("----")

        # Prepare data for Supabase insertion
        insert_data = {
            "platform": "tiktok",
            "campaign_id": campaign_id,
            "campaign_name": campaign_name,
            "adset_id": adset_id,
            "adset_name": adset_name,
            "ad_id": ad_id,
            "lead_id": lead_id,
            "full_name": field_map.get("name"),
            "email": field_map.get("email"),
            "phone": field_map.get("phone_number"),
            "city": field_map.get("city"),
            "lead_timestamp": formatted_create_time
        }

        headers = {
            "apikey": SUPABASE_API_KEY,
            "Authorization": f"Bearer {SUPABASE_API_KEY}",
            "Content-Type": "application/json"
        }

        supa_resp = requests.post(
            f"{SUPABASE_URL}/rest/v1/binrushdleads",
            headers=headers,
            json=insert_data
        )

        print("💾 Supabase insert status:", supa_resp.status_code)
        if supa_resp.status_code == 201:
            print("✅ Lead inserted successfully.")
        else:
            try:
                print("❌ Supabase Error:", supa_resp.json())
            except Exception:
                print("❌ Supabase Response:", supa_resp.text)

    return {"status": "ok"}