Sending Firebase Cloud Messaging (FCM) Notifications Using Google Apps Script and Web App

Sending Firebase Cloud Messaging (FCM) Notifications Using Google Apps Script and Web App

Firebase Cloud Messaging (FCM) is a powerful tool that allows you to send notifications to users. In this blog, we will walk through how to create a web app using Google Apps Script that allows you to send FCM notifications by calling a URL with parameters.

Prerequisites 

  • A Firebase Project.
  • Service Account credentials (client email, private key, and project ID).
  • Basic understanding of Google Apps Script.

Steps to Implement the Solution

Here’s how you can set up and deploy a Google Apps Script web app that sends FCM notifications by simply accessing a URL.


1. Set Up Firebase and Generate Service Account Credentials

Before diving into the code, ensure you have set up Firebase and have your service account credentials ready.

  • Go to the Firebase Console.
  • Select your project.
  • Navigate to Project Settings > Service Accounts.
  • Click Generate New Private Key and download the JSON file.
  • Note down the client_email, private_key, and project_id.

2. Update the Script

Below is the JavaScript code that we will use. This script contains two main functions:

  • myFunction(): This function generates a JWT access token using your Firebase service account credentials.
  • sendMsg(): This function sends an FCM notification using the generated access token.

Script:

var clientemail = "your client email";
var privateKey = "your private key";
var project = "your project id";


function myFunction() {

  var header = `{
    "alg":"RS256",
    "typ":"JWT"
  }`;
  var time = new Date().getTime()/1000;
  var expiration = time + 3600;


var payload = "{'iss':'"+ clientemail+"','scope': 'https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/firebase.messaging','aud' : 'https://oauth2.googleapis.com/token','exp':"+expiration+",'iat' :"+ time+"}";


var base64Header = Utilities.base64Encode(header).replace(['+','/','='],['-','_','']);
// console.log(payload);
var base64Payload = Utilities.base64Encode(payload).replace(['+','/','='],['-','_','']);

var signatureInput = base64Header+"."+base64Payload;

var signature = Utilities.computeRsaSha256Signature(signatureInput,privateKey);

var base64UrlSignature = Utilities.base64Encode(signature).replace(['+','/','='],['-','_','']);

var jwt = base64Header+'.'+base64Payload+'.'+base64UrlSignature;


var payload2 = {
       'grant_type' : 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' : jwt

  };
 
  var url ='https://oauth2.googleapis.com/token';
  // Options for the POST request
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
//    'headers': headers,
    'muteHttpExceptions':true,
    'payload' : JSON.stringify(payload2)
  };
 
  // Make the POST request
  var response = UrlFetchApp.fetch(url, options);

// console.log(response.getContentText());

var json = JSON.parse(response.getContentText());


console.log(json["access_token"]);

return json["access_token"];
 
}


function sendMsg(title,msg) {
 
  var message = {
    "message": {
      "topic": "all",
      "notification": {
        "title": title,
        "body": msg
      },
      "data":{
      }
    }
  };


  var options = {
    headers: {
     
      "Content-Type": "application/json; charset=UTF-8",
      "Authorization": "Bearer " + myFunction()
    },
     method:"post",
    payload: JSON.stringify(message),
   muteHttpExceptions :true
  }

console.log(options)

  var resp = UrlFetchApp.fetch('https://fcm.googleapis.com/v1/projects/' + project + '/messages:send', options);

console.info(resp.getContentText())
if(resp.getContentText().includes("error"))
  return JSON.parse(resp.getContentText())["error"]["message"];
return "Message sent successfully";
}



function doGet(e){

    try{
      var title = e.parameter.title;
      var msg = e.parameter.msg;
    }catch{
      var title = "test";
      var msg = "test msg";
    }

   return ContentService.createTextOutput().append(sendMsg(title,msg)).setMimeType(ContentService.MimeType.TEXT);
}

Explanation of the Code:

  • myFunction(): This function creates a JWT token using Firebase credentials (clientemail and privateKey), which is then used to generate an access token for authentication.
  • sendMsg(): This function sends the FCM message to all devices subscribed to the "all" topic. The message payload includes the title and body of the notification.
  • doGet(): This function allows you to pass title and msg as URL parameters, so you can easily trigger a notification by visiting a URL.

3. Deploy the Script as a Web App

To deploy the script as a web app, follow these steps:

Step 1: Save the Script

  • Once the script is written, go to File > Save to save your project.

Step 2: Deploy the Web App

  • Click on Deploy > New deployments > Select Type: Web App.
  • Under Execute as, choose Me.
  • Under Who has access, select Anyone.
  • Click Deploy and note down the generated web app URL.

4. Send Messages via URL

You can now send FCM messages by accessing the deployed web app URL with query parameters for the title and message. For example:

perl
https://script.google.com/macros/s/your-web-app-id/exec?title=Hello&msg=Welcome to FCM Notifications

This URL will trigger the doGet() function, which sends a notification with the title Hello and the message Welcome to FCM Notifications to all devices subscribed to the all topic.


5. Testing and Debugging

  • Open the URL in a browser with different titles and messages to test if the FCM messages are sent successfully.
  • Use the Firebase Console to verify whether notifications are received by the devices.

Conclusion

Using Google Apps Script as a web app to send Firebase Cloud Messaging notifications is an efficient way to handle notifications without the need for complex server-side solutions. By simply accessing a URL with query parameters, you can send notifications to all devices subscribed to a specific FCM topic.

Now you have an easy-to-deploy, lightweight system for sending notifications via FCM. This method is ideal for lightweight applications or automation needs.

No comments:

Post a Comment