1

I'm working on ionic app and need to send PUSH Notifications using FCM. I want to test push notification only for two devices. As I already have token for both device.

Is there any way to send REST api POST request using angularjs to FCM to send push notification to device ?

2 Answers2

2

Maybe you can try modifying this repo https://github.com/mexists/ionic-fcm-starter

[UPDATE]

Here some essential parts.

  • ngCordova
  • Cordova Plugin FCM

Receiving Push Notification

To receive push notification, we need to inject ngCordova to the application module. From your project directory, navigate to www\js\app.js and edit app.js file as follows.

angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers', 'starter.services'])

  • Listening to Push Notification Services

The app now need to listen and take control of incoming push notification message. To do this, and the following code inside $ionicPlatform.ready(fn) in www\js\app.js file.

//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
//Keep in mind the function will return null if the token has not been established yet.
FCMPlugin.getToken(
    function (token) {
        alert('Token: ' + token);
        console.log('Token: ' + token);
    },
    function (err) {
        alert('error retrieving token: ' + token);
        console.log('error retrieving token: ' + err);
    }
);

FCMPlugin.onNotification(
    function(data){
        if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
            alert("Tapped: " +  JSON.stringify(data) );
        }else{
//Notification was received in foreground. Maybe the user needs to be notified.
            alert("Not tapped: " + JSON.stringify(data) );
        }
    },
    function(msg){
        alert('onNotification callback successfully registered: ' + msg);
        console.log('onNotification callback successfully registered: ' + msg);
    },
    function(err){
        alert('Error registering onNotification callback: ' + err);
        console.log('Error registering onNotification callback: ' + err);
    }
);

Now your app is ready to receive push notification. You can test it on Firebase Console by navigating to Notification menu at the left sidebar menu. You also can test it at https://cordova-plugin-fcm.appspot.com by providing your FCM project's server key.

Sending Push Notification

To send push notification, we will need to use the AngularJS $http provider.

In your controller, add $http service provider

.controller('ChatDetailCtrl', function($scope, $http, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);

Then add the following code in your controller:

$scope.formData = {};
  $scope.send = function(){
    //FCMPlugin.subscribeToTopic( topic, successCallback(msg), errorCallback(err) );
    //All devices are subscribed automatically to 'all' and 'ios' or 'android' topic respectively.
    //Must match the following regular expression: "[a-zA-Z0-9-_.~%]{1,900}".
    FCMPlugin.subscribeToTopic('all'); //subscribe current user to topic

    var fcm_server_key = "AIzaSyCmu7RXJkSsNJch9MB5ySDUbguyRBeAWm8";

    $http({
      method: "POST",
      dataType: 'jsonp',
      headers: {'Content-Type': 'application/json', 'Authorization': 'key=' + fcm_server_key},
      url: "https://fcm.googleapis.com/fcm/send",
      data: JSON.stringify(
          {
            "notification":{
              "title":"Ionic 2 FCM Starter",  //Any value
              "body": $scope.formData.message,  //Any value
              "sound": "default", //If you want notification sound
              "click_action": "FCM_PLUGIN_ACTIVITY",  //Must be present for Android
              "icon": "fcm_push_icon"  //White icon Android resource
            },
            "data":{
              "param1":"value1",  //Any data to be retrieved in the notification callback
              "param2": $scope.formData.message
            },
            "to":"/topics/all", //Topic or single device
            "priority":"high", //If not set, notification won't be delivered on completely closed iOS app
            "restricted_package_name":"" //Optional. Set for application filtering
          }
        )
    }).success(function(data){
      $scope.reply = $scope.formData.message;
      alert("Success: " + JSON.stringify(data));
    }).error(function(data){
      alert("Error: " + JSON.stringify(data));
    });
  }
Community
  • 1
  • 1
mexists
  • 21
  • 4
0

Sending downstream notifications (notifications to a device) requires that you have access to the server key of Firebase Cloud Messaging. As such this should never be done from a client-side app, since having access to the server key allows sending messages on your app's behalf.

A common way to accomplish device-to-device message sending is through the Firebase Database. See this blog post that describes sending between Android devices, but the approach would apply to other technologies too.

Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
  • My idea was never to implement device to device messaging. I want to send notification. I think i need to send REST API request, by adding server key in header and passing other data as json. As I already have other device's token. – darshak katariya Aug 30 '16 at 15:04
  • If you add the server key to the header from within your Ionic app, you are exposing the server key to users of your app. Unless you have control over who uses your app, this opens you up to abuse. But if you have such control: https://firebase.google.com/docs/cloud-messaging/send-message#http_post_request – Frank van Puffelen Aug 30 '16 at 15:35