In my previous story, I setup Firebase Cloud Messaging (FCM) in Ubuntu Server 20.04 and deployed it to Firebase hosting from scratch. I’ll be resuming where I left off from the previous story.
Firebase has documentation on how to call an API to send a Firebase Cloud Messaging (FCM) push notification message at https://firebase.google.com/docs/cloud-messaging/js/first-message but it is very vague on how to get the access token.
Here is the documentation on how to mint the access token at https://firebase.google.com/docs/cloud-messaging/auth-server. Copy pasting the snippet in its documentation won’t work.
You’ll need a service account credential. The series of screenshots below show you where to get it.
Verify if python exists.
Verify if pip exists. Install if not exists.
Below is the python script to get access token.
from oauth2client.service_account import ServiceAccountCredentials
scope = 'https://www.googleapis.com/auth/firebase.messaging'def _get_access_token():
credentials = ServiceAccountCredentials.from_json_keyfile_name('/home/ubuntu/oofnivek-medium-fcm.json', scope)
access_token_info = credentials.get_access_token()
Install and upgrade oauth2client
pip install --upgrade oauth2client
I am reusing the FCM registration token from my previous story. I’ll name the JSON payload file below as “message.json”.
"token" : "eNIFS6yPlLWdBDnU-Mwu8W:APA91bFSPEdIkl6jvWwal5MK0WtC7le6N92zix3pKHdeZYcIfIVJ43qezx2DBw6Lo4dCqsCyR8LtAZyKRj0vFC7KJU02jgIeeF4rowvnVvqOHgcPoGAOL5s4ctWKIBTtITb3tm9qhwPT",
"title": "FCM Message",
"body": "This is a message from FCM to web",
The curl command is to send the push notification message.
curl -X POST -H "Authorization: Bearer `python get_access_token.py`" \
-H "Content-Type: application/json" \
--data '@/home/ubuntu/message.json' \
For simplicity, I am renewing my access token on every send. This slows down the sending process. Best to put in extra logic to renew only when the token expires.