File size: 2,102 Bytes
29a8df0
 
bcdd7d2
167c23d
 
 
 
 
28cc3fd
9be9f97
28cc3fd
 
29a8df0
 
 
 
 
 
 
b212680
 
 
 
82376a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29a8df0
 
 
167c23d
 
29a8df0
 
167c23d
29a8df0
 
167c23d
28cc3fd
 
29a8df0
 
 
 
 
bcdd7d2
 
28cc3fd
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
from fastapi import FastAPI, Body
from pydantic import BaseModel
import uvicorn
import firebase_admin
from firebase_admin import messaging, credentials

app = FastAPI()

# Firebase Admin SDK initialization
cred = credentials.Certificate("earn-by-ads-34cd4-firebase-adminsdk-23x4r-557fc24c1d.json")
firebase_admin.initialize_app(cred)

# Define request model
class NotificationRequest(BaseModel):
    title: str
    body: str
    topic: str = "all"
    data: dict = None

@app.get("/")  # Test endpoint
def root():
    return {"message": "FastAPI is running!"}



# Example FastAPI endpoint for your server
@app.post("/send_notification_to_token")
async def send_notification_to_token(notification: dict):
    try:
        # Extract notification details
        title = notification.get("title")
        body = notification.get("body")
        token = notification.get("token")
        data = notification.get("data", {})
        
        # Create message for FCM
        message = messaging.Message(
            notification=messaging.Notification(
                title=title,
                body=body,
            ),
            data=data,
            token=token,  # This is the key difference - send to a specific token
        )
        
        # Send message
        response = messaging.send(message)
        return {"success": True, "message_id": response}
    except Exception as e:
        return {"success": False, "error": str(e)}



        


@app.post("/send_notification")
def send_notification(request: NotificationRequest = Body(...)):
    # Create the notification message
    message = messaging.Message(
        notification=messaging.Notification(
            title=request.title,
            body=request.body
        ),
        data=request.data,
        topic=request.topic
    )
    
    # Send the notification
    try:
        response = messaging.send(message)
        return {"success": True, "message_id": response}
    except Exception as e:
        return {"success": False, "error": str(e)}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)