首页 > 解决方案 > 如何在 nodejs 中使用 FCM 发送 AWS SNS 推送通知?

问题描述

我想问我如何端到端发送 AWS SNS 推送通知意味着我不想使用控制台来创建端点并且我想使用 nodejs 发送通知。我可以使用控制台为一台设备发送通知,并使用该端点发布通知。我想问我如何完全使用 nodejs 来实现。这是我尝试过的解决方案

var AWS = require('aws-sdk');

AWS.config.update({
    accessKeyId: "",
  secretAccessKey:"",
  region: "us-east-1"
});
var sns = new AWS.SNS();

let payload2 = JSON.stringify({
    default: 'Practice',
    GCM:  JSON.stringify({
      notification : {
        body : 'great match!',
        title : 'Portugal vs. Denmark'       
      },
      data:{
        testdata: 'Check out these awesome deals!',
        url: 'www.amazon.com'
      }
    })
  });
  console.log(payload2)


  console.log('sending push');

  sns.publish({
    Message: payload2,      // Required
     MessageStructure: 'json',
    TargetArn: 'Arn from console' // Required
  }, function(err, data) {
    if (err) {
      console.log(err.stack);
      return;
    }

    console.log('push sent');
    console.log(data);
  });

我还想知道如何将批量推送通知发送到多个设备?

标签: javascriptnode.jspush-notificationamazon-snsandroid-push-notification

解决方案


如何完全使用 NodeJS 实现

// Use AWS-SDK
import * as AWS from 'aws-sdk';

// Known constants
const fcmToken = 'SAMPLE_FCM_TOKEN';
const applicationArn = 'FCM_APPLICATION_ARN';
const topicArn = 'SNS_TOPIC_ARN';


// Initialize SNS
const sns = new AWS.SNS({
    apiVersion: '2010-03-31',
    accessKeyId: 'YOUR_ACCESS_KEY',
    secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',
    region: 'YOUR_REGION'
});

// Function to register an application-endpoint using FCM token
async function registerDevice(deviceFcmToken: string): Promise<string> {
    console.log('Registering device endpoint');
    const endpointArn = await sns.createPlatformEndpoint({
        PlatformApplicationArn: applicationArn,
        Token: deviceFcmToken
    })
    .promise()
    .then((data) => {
        return data.EndpointArn;
    })
    .catch((error) => {
        return null;
    });
    return endpointArn;
}

// Function to subscribe to an SNS topic using an endpoint
async function subscribeToSnsTopic(endpointArn: string): Promise<string> {
    console.log('Subscribing device endpoint to topic');
    const subscriptionArn = await sns.subscribe({
        TopicArn: topicArn,
        Endpoint: endpointArn,
        Protocol: 'application'
    })
    .promise()
    .then((data) => {
        return data.SubscriptionArn;
    })
    .catch((error) => {
        return null;
    });
    return subscriptionArn;
}

// Send SNS message to a topic
var params = {
    Message: 'Hello World',
    TopicArn: topicArn
};
sns.publish(params)
    .promise()
    .then((data) => {
        console.log(`Message ${params.Message} send sent to the topic ${params.TopicArn}`);
        console.log("MessageID is " + data.MessageId);
    })
    .catch((err) => {
        console.error(err, err.stack);
    });


如何将批量推送通知发送到多个设备?

假设您想通过使用 SNS 本身来做到这一点。您可以为平台应用程序下的所有设备添加/注册应用程序端点。然后从每个端点订阅一个 SNS 主题,因此每当您向 SNS 主题发送消息时,它都会自动发送给所有订阅者。

PS:不确定这种方法的扩展性如何。


推荐阅读