Mr-Help commited on
Commit
e5c6457
·
verified ·
1 Parent(s): 72879e5

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +99 -34
main.py CHANGED
@@ -1,39 +1,104 @@
1
- # file: simple_token_api.py
2
- # pip install fastapi uvicorn requests
3
-
4
  import requests
5
- from fastapi import FastAPI
 
6
 
7
  app = FastAPI()
8
 
9
- BASE = "https://odoo-demo.binrushd.care"
10
- CF_ID = "0491b36d7dcabce5b04f1a53f347bb4e.access"
11
- CF_SECRET = "22152cb41b62393e159daaff7dce433006c3744c5850e6adc15fa3544bb5eb09"
12
- LOGIN = "binrushd.automation@gmail.com"
13
- PASSWORD = "BR2025"
14
- DB = "Live_August_25"
15
-
16
-
17
- @app.post("/test_token")
18
- def test_token():
19
- headers = {
20
- "CF-Access-Client-Id": CF_ID,
21
- "CF-Access-Client-Secret": CF_SECRET,
22
- "login": LOGIN,
23
- "password": PASSWORD,
24
- "db": DB,
25
- }
26
-
27
- print("🔹 Sending request to get new token...")
28
  try:
29
- r = requests.get(f"{BASE}/api/auth/token", headers=headers, timeout=30)
30
- print("Status:", r.status_code)
31
- print("Headers:", r.headers)
32
- print("Response text:", r.text[:500])
33
- r.raise_for_status()
34
- data = r.json()
35
- print("✅ Token response:", data)
36
- return {"status": "ok", "data": data}
37
- except Exception as e:
38
- print("❌ Error while getting token:", e)
39
- return {"status": "error", "message": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
 
 
2
  import requests
3
+ from fastapi import FastAPI, Request
4
+ from datetime import datetime, timezone, timedelta
5
 
6
  app = FastAPI()
7
 
8
+ # Load Supabase environment variables
9
+ SUPABASE_URL = os.getenv("SUPABASE_URL")
10
+ SUPABASE_API_KEY = os.getenv("SUPABASE_API_KEY")
11
+
12
+ @app.post("/webhook")
13
+ async def receive_webhook(request: Request):
14
+ payload = await request.json()
15
+
16
+ print("📥 Webhook received:")
17
+
18
+ gmt_plus_3 = timezone(timedelta(hours=3))
19
+
20
+ # Top-level fields
21
+ print(f"Request ID: {payload.get('request_id')}")
22
+ print(f"Object: {payload.get('object')}")
23
+ print(f"Time (Unix): {payload.get('time')}")
 
 
 
24
  try:
25
+ formatted_time = datetime.fromtimestamp(payload.get('time'), gmt_plus_3).strftime('%Y-%m-%d %H:%M:%S GMT+3')
26
+ print(f"Time (Formatted): {formatted_time}")
27
+ except Exception:
28
+ print("Time (Formatted): Invalid timestamp")
29
+ print("----")
30
+
31
+ # Loop through entries
32
+ for entry in payload.get('entry', []):
33
+ lead_id = entry.get('id')
34
+ campaign_id = entry.get('campaign_id')
35
+ campaign_name = entry.get('campaign_name')
36
+ adset_id = entry.get('adgroup_id')
37
+ adset_name = entry.get('adgroup_name')
38
+ ad_id = entry.get('ad_id')
39
+ ad_name = entry.get('ad_name')
40
+ advertiser_id = entry.get('advertiser_id')
41
+ create_ts = entry.get('create_time')
42
+
43
+ print(f"Lead ID: {lead_id}")
44
+ print(f"Campaign ID: {campaign_id}")
45
+ print(f"Campaign Name: {campaign_name}")
46
+ print(f"Ad Group ID: {adset_id}")
47
+ print(f"Ad Group Name: {adset_name}")
48
+ print(f"Ad ID: {ad_id}")
49
+ print(f"Ad Name: {ad_name}")
50
+ try:
51
+ formatted_create_time = datetime.fromtimestamp(create_ts, gmt_plus_3).isoformat()
52
+ print(f"Create Time: {formatted_create_time}")
53
+ except Exception:
54
+ formatted_create_time = None
55
+ print("Create Time: Invalid")
56
+
57
+ # Extract lead fields
58
+ field_map = {}
59
+ for change in entry.get('changes', []):
60
+ field = change.get('field').lower()
61
+ value = change.get('value')
62
+ field_map[field] = value
63
+ print(f"{field}: {value}")
64
+
65
+ print("----")
66
+
67
+ # Prepare data for Supabase insertion
68
+ insert_data = {
69
+ "platform": "tiktok",
70
+ "campaign_id": campaign_id,
71
+ "campaign_name": campaign_name,
72
+ "adset_id": adset_id,
73
+ "adset_name": adset_name,
74
+ "ad_id": ad_id,
75
+ "lead_id": lead_id,
76
+ "full_name": field_map.get("name"),
77
+ "email": field_map.get("email"),
78
+ "phone": field_map.get("phone_number"),
79
+ "city": field_map.get("city"),
80
+ "lead_timestamp": formatted_create_time
81
+ }
82
+
83
+ headers = {
84
+ "apikey": SUPABASE_API_KEY,
85
+ "Authorization": f"Bearer {SUPABASE_API_KEY}",
86
+ "Content-Type": "application/json"
87
+ }
88
+
89
+ supa_resp = requests.post(
90
+ f"{SUPABASE_URL}/rest/v1/binrushdleads",
91
+ headers=headers,
92
+ json=insert_data
93
+ )
94
+
95
+ print("💾 Supabase insert status:", supa_resp.status_code)
96
+ if supa_resp.status_code == 201:
97
+ print("✅ Lead inserted successfully.")
98
+ else:
99
+ try:
100
+ print("❌ Supabase Error:", supa_resp.json())
101
+ except Exception:
102
+ print("❌ Supabase Response:", supa_resp.text)
103
+
104
+ return {"status": "ok"}