Angularjs:有没有办法使用角度js和FCM发送推送通知

时间:2016-08-30 14:47:48

标签: angularjs cordova ionic-framework firebase-cloud-messaging

我正在使用离子应用,需要使用FCM发送PUSH通知。 我想仅测试两个设备的推送通知。因为我已经有两个设备的令牌。

有没有办法使用angularjs向FCM发送REST api POST请求以向设备发送推送通知?

2 个答案:

答案 0 :(得分:2)

也许您可以尝试修改此回购https://github.com/mexists/ionic-fcm-starter

<强> [UPDATE]

这里有一些重要的部分。

  • ngCordova
  • Cordova Plugin FCM

接收推送通知

要接收推送通知,我们需要将ngCordova注入应用程序模块。从项目目录中,导航到www\js\app.js并编辑app.js文件,如下所示。

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

  • 倾听推送通知服务

该应用现在需要监听并控制传入的推送通知消息。为此,以及$ionicPlatform.ready(fn)文件中www\js\app.js内的以下代码。

//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);
    }
);

现在您的应用已准备好接收推送通知。您可以通过导航到左侧边栏菜单中的Notification菜单在Firebase控制台上对其进行测试。您也可以https://cordova-plugin-fcm.appspot.comFCM project's server key进行测试。

发送推送通知

要发送推送通知,我们需要使用AngularJS $http提供商。

在您的控制器中,添加$http服务提供商

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

然后在控制器中添加以下代码:

$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));
    });
  }

答案 1 :(得分:0)

发送下游通知(通知设备)要求您有权访问Firebase Cloud Messaging的服务器密钥。因此,永远不应该从客户端应用程序完成此操作,因为访问服务器密钥允许代表您的应用程序发送消息。

完成设备到设备消息发送的常用方法是通过Firebase数据库。请参阅此blog post that describes sending between Android devices,但该方法也适用于其他技术。