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 (

How to use PHP and GD library to convert text to an image?

To convert text to an image in PHP, you can use the GD library, which is a graphics library for creating and manipulating images. Here is an example code that creates an image with a text message: <?php // Create a blank image $image = imagecreatetruecolor( 400 , 200 ); // Set the background color $bg_color = imagecolorallocate( $image , 255 , 255 , 255 ); imagefill( $image , 0 , 0 , $bg_color ); // Set the text color $text_color = imagecolorallocate( $image , 0 , 0 , 0 ); // Write the text on the image $text = "Hello World!" ; imagettftext( $image , 24 , 0 , 50 , 100 , $text_color , 'arial.ttf' , $text ); // Output the image as PNG header( 'Content-Type: image/png' ); imagepng( $image ); // Free up memory imagedestroy( $image ); ?> This code creates a 400x200 pixels image with a white background and black text that says "Hello World!". You can change the text, font, and colors to suit your ne