With just a few lines of code and a couple of API keys, your application can set up Push Notifications using Twilio Notify, Google Firebase and your choice of web language. We have code for you to stand up a server in C#, Node.js, PHP, Python, Ruby, and Java.
In this Quickstart, you will:
Before you can send push notifications with Notify and Firebase, you'll need to sign up for a Twilio account or sign into your existing account.
For now, that's about it - you'll need to set up an account with Firebase and get FCM credentials before you can move forward with the app. Leave the Twilio tab open and move to the next step.
If you haven't yet, sign up for Google's Firebase. We'll be using it as the base for our notification today. To use push notifications for your web apps, create a project on the Firebase Console:
In Firebase, the FCM Secret is called the Server Key
and you can find it in your Firebase console under your Project Settings and Cloud Messaging tab.
Once you have the secret, you need to create a credential on the Add a Push Credential page on the Twilio Console using the FCM Secret.
Give it a memorable name and paste the FCM Server Key into the "FCM Push Credentials" text box:
In the Notify console, create a new Notify service. Inside the new service in the FCM Credential SID dropdown, select the Credential that you have just created.
Make a note of the Service SID. You will use it later when you start writing code.
In order to authenticate your requests to Twilio API, you need to create a API Key. If you have already been using Twilio and have created API Keys, you can skip this step.
In Console, go to https://www.twilio.com/console/runtime/api-keys and click the Create API Key button to create a new API key. Give your new key a Friendly Name and choose the "Standard" type. Hit the "Create API Key" button to generate the key.
The generated Secret is shown only once, store it in a secure place. You will not be able to see the secret in the Console later. (If you do miss it, you can generate a new service).
Next, we need to grab all the necessary information from our Twilio account. Here's a list of what we'll need to gather:
CONFIG VALUE | DESCRIPTION |
---|---|
Notify Service Instance SID | A service instance where all the data for our application is stored and scoped. You can create one in the console. |
Account SID | Used to authenticate REST API requests - find it in the console here. |
API Key | Used to authenticate REST API requests - SID (SKxxx..). It can be found here: https://www.twilio.com/console/runtime/api-keys/ |
API Secret | Used to authenticate REST API requests. Hopefully, you stored it, but if not create a new API Key here. |
When using the Notify service, you need to register devices to receive notifications and then send notifications to those devices. To get you going quickly, we've created backend servers for the following languages:
The sample mobile app is set up to communicate with the server-side app to register a device for notifications.
For this example, we'll use the Node.js server. Feel free to copy our choice or follow along in the language you prefer.
Follow the Node.js installation instructions here and complete the installation.
Download the Node.js server app and unzip it, or get it uncompressed from GitHub
Now that you have Node.js installed and the Node.js server downloaded and unpacked, it is time to configure the server with your specific account information.
.env.example
file to .env
.env
file to include the four configuration parameters (Account SID, API Key SID, API Key Secret, Notify Service SID) we gathered from above.Now we need to install our dependencies.
In a Terminal window, navigate to the folder where you unzipped or downloaded the app and run:
npm install
Once we've done configuring we're ready to start the server - again in your terminal, run:
npm start
To confirm the server is running, visit http://localhost:3000 in your web browser. You should see the home screen, informing you of which Twilio services you've configured.
To get you going quickly, we provide a Web Push sample app, available on GitHub.
The following steps will guide you to configure Web Push Notifications for the Twilio Notify sample Web Push app.
You'll need to collect the Firebase Sender ID and Web API Key and configure the demo app for your Firebase project. To obtain these keys, go to the Firebase Console and open your Project Settings.
index.html:
Use Notify and Firebase to create push notifications
1<html>2<link rel="manifest" href="/manifest.json"/>34<head>5<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-app.js"></script>6<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-messaging.js"></script>7<script src="notify_actions.js"></script>8<title>Notify Firebase Cloud Notifications</title>9</head>1011<body>12<h1>Quick Start Notify</h1>13<a href="https://firebase.google.com/docs/cloud-messaging/js/client">More details how to set up Firebase web push</a>1415<h2>Create Binding</h2>1617<form id="binding_form">18Identity: <input type="text" name="identity_field"><br>19Address: <input type="text" name="address_field" size="200" value="<device token>"> <br>20<input type="button" onclick="createBinding()" value="Create Binding">21</form>2223<script>24// firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client25// Initialize Firebase26var config = {27apiKey: '<ENTER FIREBASE WEB API KEY HERE>',28messagingSenderId: '<ENTER FIREBASE SENDER ID HERE>'29};30firebase.initializeApp(config);3132// Retrieve Firebase Messaging object.33const messaging = firebase.messaging();3435messaging.requestPermission()36.then(function() {37console.log('Notification permission granted.');38})39.catch(function(err) {40console.log('Unable to get permission to notify.', err);41});4243// Get Instance ID token. Initially, this makes a network call, once retrieved44// subsequent calls to getToken will return from cache.45messaging.getToken()46.then(function(currentToken) {47if (currentToken) {48console.log('Token received: ', currentToken);49document.forms["binding_form"]["address_field"].value = currentToken;50} else {51var errMsg = 'No Instance ID token available. Request permission to generate one.';52alert(errMsg);53document.forms["binding_form"]["address_field"].value = errMsg;54}55})56.catch(function(err) {57console.log('An error occurred while retrieving token. ', err);58});5960messaging.onMessage(function(payload) {61console.log('Message received. ', payload);62alert(payload.data.twi_body);63});6465function createBinding(){66var identity = document.forms["binding_form"]["identity_field"].value;67if (identity == "") {68alert('Identity must be specified');69return false;70}7172var address = document.forms["binding_form"]["address_field"].value;73if (address == "") {74alert('Address must be specified');75return false;76}7778register(identity, address);79}8081</script>8283</body>8485</html>
firebase-messaging-sw.js:
Initialize Firebase in JavaScript
1// firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client2// [START initialize_firebase_in_sw]3// Give the service worker access to Firebase Messaging.4// Note that you can only use Firebase Messaging here, other Firebase libraries5// are not available in the service worker.6importScripts('https://www.gstatic.com/firebasejs/4.8.0/firebase-app.js');7importScripts('https://www.gstatic.com/firebasejs/4.8.0/firebase-messaging.js');89// Initialize the Firebase app in the service worker by passing in the10// messagingSenderId.11firebase.initializeApp({12'messagingSenderId': '<ENTER FIREBASE SENDER ID HERE>'13});1415// Retrieve an instance of Firebase Messaging so that it can handle background16// messages.17const messaging = firebase.messaging();18// [END initialize_firebase_in_sw]1920messaging.setBackgroundMessageHandler(function(payload) {21console.log('[firebase-messaging-sw.js] Received background message ', payload);22// Customize notification here23const notificationTitle = 'Background Message Title';24const notificationOptions = {25body: 'Background Message body.'26};2728return self.registration.showNotification(notificationTitle,29notificationOptions);30});31
Next, we need to create a binding between an Identity
and the browser using the web app. The Identity
can be any unique identifier you choose, for example, a GUID. In this quickstart, we take care of that with the web push app. For more about Identity and Bindings visit the Binding resource reference API.
Refresh (or open) the Web Push App at http://localhost:8000/
If you are running the sample app in debugger mode and it wasn't successful, you'll see an error message printed in the console.
Note: If you do not see a device token in the Address bar the first time you launch the app, reload the page. The demo app code is naive and doesn't handle the race between the App asking for and obtaining a token. Additionally, check the browser console for misconfiguration issues or hints.
Notify uses Identity as the unique identifier of a user. Do not use directly identifying information (personally identifiable information or PII) such as a person's name, home address, email address, phone number, et cetera, as the Identity
. The system that will process this attribute assumes it is not directly identifying information.
In the app enter the Identity
you chose and click the button "Create Binding".
This action creates a Binding which uniquely identifies a user on a certain device running your application.
In the terminal window running the "backend" (Node.js) server, you should see something like this:
1BindingInstance {2_version:3V1 {4_domain:5Notify {6twilio: [Object],7baseUrl: 'https://notify.twilio.com',8_v1: [Circular] },9_version: 'v1',10_credentials: undefined,11_services:12{ [Function: ServiceListInstance]13_version: [Circular],14_solution: {},15_uri: '/Services',16create: [Function: create],17each: [Function: each],18list: [Function: list],19page: [Function: page],20get: [Function: get] } },21sid: 'BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',22accountSid: 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,23serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,24dateCreated: 2017-01-17T13:07:39.000Z,25dateUpdated: 2017-01-17T13:07:39.000Z,26notificationProtocolVersion: '3',27endpoint: 'user9999999XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',28identity: 'Bob Builder',29bindingType: 'fcm',30address: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',31tags: [],32url: 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',33_context: undefined,34_solution:35{ serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',36sid: 'BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' } }37
Now that we have the Binding, we are ready to send a Push Notification.
To send a notification, you can use the Notify page on the "backend" service you have running at http://localhost:3000. Go ahead and click the "Notify" button at the bottom of the home page to go to the Notify page.
On this page, send a message to the identity you used in the app. Because you registered a binding with Twilio, the server will send your device the message as a notification.
And that's all there is to it! You've now got a "frontend" and a "backend" app which can send push notifications using Notify and Firebase, and you're ready to go off and build your own application. We can't wait to see what you build - notify us when you've got something.