Skip to main content

Learn how to setup push notifications in your Ionic app and send a sample notification using Node.js and PHP.

Ionic is an open source mobile UI toolkit for building modern, high quality cross-platform mobile apps from a single code base.

To set up push notifications in your Ionic app, you will need to perform the following steps:

  1. Create a new Firebase project or use an existing one, and then enable Firebase Cloud Messaging (FCM) for your project.

  2. Install the Firebase Cloud Messaging plugin for Ionic:

npm install @ionic-native/firebase-x --save
  1. Add the plugin to your app's app.module.ts file:
import { FirebaseX } from '@ionic-native/firebase-x/ngx';

@NgModule({
  ...
  providers: [
    ...
    FirebaseX
    ...
  ]
  ...
})
  1. Initialize Firebase in your app's app.component.ts file:
import { FirebaseX } from '@ionic-native/firebase-x/ngx';

@Component({
  ...
})
export class AppComponent {
  constructor(private firebase: FirebaseX) {
    this.firebase.init();
  }
}
  1. Register your app with Firebase Cloud Messaging by adding the google-services.json file to your app's root directory for Android or GoogleService-Info.plist file for iOS.

  2. Use the Firebase Cloud Messaging API to subscribe your app to a topic or receive notifications for specific devices.

  3. Send push notifications to your app using the Firebase Cloud Messaging console or through the Firebase Cloud Messaging API.

That's it! Your Ionic app should now be able to receive push notifications from Firebase Cloud Messaging.

Server-side PHP code for sending push notification

An example of server-side PHP code for sending push notifications to devices via Firebase Cloud Messaging (FCM):

<?php

// Set your FCM server key here
$server_key = 'YOUR_SERVER_KEY_HERE';

// Set the device token of the device you want to send the notification to
$device_token = 'DEVICE_TOKEN_HERE';

// Set the notification message
$message = array(
    'title' => 'Notification Title',
    'body' => 'Notification Body',
    'icon' => 'icon.png',
    'click_action' => 'OPEN_ACTIVITY_1'
);

// Set the data payload (optional)
$data = array(
    'param1' => 'value1',
    'param2' => 'value2'
);

// Set the headers for the HTTP request
$headers = array(
    'Authorization: key=' . $server_key,
    'Content-Type: application/json'
);

// Set the request data
$data = array(
    'to' => $device_token,
    'notification' => $message,
    'data' => $data
);

// Send the HTTP request to FCM
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);

// Print the response from FCM
echo $response;

?>

Replace YOUR_SERVER_KEY_HERE with your FCM server key, and DEVICE_TOKEN_HERE with the device token of the device you want to send the notification to. You can get the device token from the device when you register it with FCM.

The $message array contains the notification message, and you can add additional data to the $data array if needed.

The code sends an HTTP POST request to the FCM server with the device token and the notification message, and FCM sends the notification to the specified device.

Server-side Node.js code for sending push notification

An example of server-side Node.js code for sending push notifications to devices via Firebase Cloud Messaging (FCM):

const request = require('request');

// Set your FCM server key here
const serverKey = 'YOUR_SERVER_KEY_HERE';

// Set the device token of the device you want to send the notification to
const deviceToken = 'DEVICE_TOKEN_HERE';

// Set the notification message
const message = {
  notification: {
    title: 'Notification Title',
    body: 'Notification Body',
    icon: 'icon.png',
    click_action: 'OPEN_ACTIVITY_1'
  },
  data: {
    param1: 'value1',
    param2: 'value2'
  },
  token: deviceToken
};

// Set the headers for the HTTP request
const headers = {
  'Authorization': 'key=' + serverKey,
  'Content-Type': 'application/json'
};

// Set the request options
const options = {
  url: 'https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send',
  method: 'POST',
  headers: headers,
  json: message
};

// Send the HTTP request to FCM
request(options, (error, response, body) => {
  if (error) {
    console.error('Error sending notification: ', error);
  } else if (response.statusCode >= 400) {
    console.error('HTTP Error: ', response.statusCode, body);
  } else {
    console.log('Notification sent successfully: ', body);
  }
});

Replace YOUR_SERVER_KEY_HERE with your FCM server key, and DEVICE_TOKEN_HERE with the device token of the device you want to send the notification to. You can get the device token from the device when you register it with FCM.

The message object contains the notification message, and you can add additional data to the data property if needed.

The code sends an HTTP POST request to the FCM server with the device token and the notification message, and FCM sends the notification to the specified device. You also need to replace YOUR_PROJECT_ID with your Firebase project ID in the options object.

Using node-gcm package

You can also use the node-gcm library (previously known as node-fcm) for sending push notifications to devices via Firebase Cloud Messaging (FCM) in Node.js. Here's an example code using node-gcm:

const gcm = require('node-gcm');

// Set your FCM server key here
const serverKey = 'YOUR_SERVER_KEY_HERE';

// Set the device token of the device you want to send the notification to
const deviceToken = 'DEVICE_TOKEN_HERE';

// Set the notification message
const message = new gcm.Message({
  notification: {
    title: 'Notification Title',
    body: 'Notification Body',
    icon: 'icon.png',
    click_action: 'OPEN_ACTIVITY_1'
  },
  data: {
    param1: 'value1',
    param2: 'value2'
  }
});

// Set the sender ID (optional)
const sender = new gcm.Sender(serverKey);

// Set the registration tokens for the devices you want to send the notification to
const registrationTokens = [deviceToken];

// Send the notification to the specified devices
sender.send(message, { registrationTokens: registrationTokens }, function (err, response) {
  if (err) {
    console.error('Error sending notification: ', err);
  } else {
    console.log('Notification sent successfully: ', response);
  }
});

Replace YOUR_SERVER_KEY_HERE with your FCM server key, and DEVICE_TOKEN_HERE with the device token of the device you want to send the notification to. You can get the device token from the device when you register it with FCM.

The message object contains the notification message, and you can add additional data to the data property if needed.

The sender.send function sends the notification to the specified device(s) using the registrationTokens parameter, which is an array of device tokens. Note that node-gcm library has been deprecated and you can use firebase-admin instead.

Comments

Popular posts from this blog

How to export php/html page to Excel,Word & CSV file format

This class can generate the necessary request headers to make the outputted HTML be downloaded as a file by the browser with a file name that makes the file readable by Excel(.xls),Word(.doc) and CSV(.csv). Step1: Create PHP file named 'ExportPHP.class.php' ExportPHP.class.php <?php class ExportPHP { // method for Excel file function setHeaderXLS ( $file_name ) { header( "Content-type: application/ms-excel" ); header( "Content-Disposition: attachment; filename=$file_name" ); header( "Pragma: no-cache" ); header( "Expires: 0" ); } // method for Doc file function setHeaderDoc ( $file_name ) { header( "Content-type: application/x-ms-download" ); header( "Content-Disposition: attachment; filename=$file_name" ); header( 'Cache-Control: public' ); } // method for CSV file function setHeaderCSV (

Why is Apollo Client a crucial tool for your GraphQL project?

Apollo Client is a popular JavaScript library for managing GraphQL queries and mutations in client-side applications. There are several reasons why you might want to use Apollo Client in your GraphQL application: Simplified data management : With Apollo Client, you can easily manage your application's data with a single, declarative API. This can help to simplify your code and make it easier to reason about. Real-time updates : Apollo Client includes built-in support for subscriptions, which allow you to receive real-time updates from your GraphQL server. This can be useful for applications that require real-time data, such as chat applications or real-time analytics dashboards. Caching and performance : Apollo Client includes a sophisticated caching system that can help to improve the performance of your application by reducing the number of network requests required to fetch data. The cache can also be configured to automatically invalidate data when it becomes stale, ensuring th