Ubuntu Send FCM Push Notification

Kevin FOO
3 min readJul 7, 2020

--

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()
return access_token_info.access_token
print(_get_access_token())
This is how the indentation supposed to look like. My code snippet indentation is off.

Install and upgrade oauth2client

pip install --upgrade oauth2client
Successfully getting the access token

I am reusing the FCM registration token from my previous story. I’ll name the JSON payload file below as “message.json”.

{
"message": {
"token" : "eNIFS6yPlLWdBDnU-Mwu8W:APA91bFSPEdIkl6jvWwal5MK0WtC7le6N92zix3pKHdeZYcIfIVJ43qezx2DBw6Lo4dCqsCyR8LtAZyKRj0vFC7KJU02jgIeeF4rowvnVvqOHgcPoGAOL5s4ctWKIBTtITb3tm9qhwPT",
"webpush": {
"headers": {
"Urgency": "high"
},
"notification": {
"title": "FCM Message",
"body": "This is a message from FCM to web",
"requireInteraction": "true",
"icon": "https://oofnivek-medium-fcm.web.app/firebase-logo.png",
"image": "https://www.oofnivek.com/wp-content/uploads/2018/07/build-website-search-engine-optimization-singapore-06.jpg",
"badge": "https://oofnivek-medium-fcm.web.app/firebase-logo.png",
"click_action": "https://oofnivek.com"
}
}
}
}

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' \
"https://fcm.googleapis.com/v1/projects/oofnivek-medium-fcm/messages:send"

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.

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.

No responses yet