Skip to content

Instantly share code, notes, and snippets.

@hasanisaeed
Last active April 17, 2024 17:35
Show Gist options
  • Save hasanisaeed/3c376f01510aeeab25eff7e8f5f86d37 to your computer and use it in GitHub Desktop.
Save hasanisaeed/3c376f01510aeeab25eff7e8f5f86d37 to your computer and use it in GitHub Desktop.
Python script to send push notifications using Firebase Cloud Messaging (FCM) and Google OAuth2.
import requests
from google.oauth2 import service_account
import google.auth.transport.requests
import google
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
def get_access_token():
"""Retrieve a valid access token that can be used to authorize requests."""
credentials = service_account.Credentials.from_service_account_file(
r'C:\path\to\your\service-account.json', scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
return credentials.token
def get_header():
return {'Authorization': 'Bearer ' + get_access_token(),
'Content-Type': 'application/json; UTF-8'}
def send_push_message(recipient_token, data):
"""
Sends a push message to the specified recipient.
Args:
recipient_token (str): The recipient's token.
data (dict): Dictionary containing message data.
Returns:
dict: The response JSON.
"""
firebase_url = 'https://fcm.googleapis.com/v1/projects/your-project-id/messages:send'
headers = get_header()
response = requests.post(firebase_url, headers=headers, json=data)
return response.json()
# Example usage
recipient_token = 'your_recipient_token_here'
data = {
"message": {
"token": recipient_token,
"notification": {
"title": "Breaking News!",
"body": "New news story available."
},
"data": {
"story_id": "story_12345"
},
"android": {
"notification": {
"click_action": "TOP_STORY_ACTIVITY"
}
},
"apns": {
"payload": {
"aps": {
"category": "NEW_MESSAGE_CATEGORY"
}
}
}
}
}
response = send_push_message(recipient_token, data)
print(response)
requests==2.25.1
google-auth==2.29.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment