简体   繁体   English

如何通过Amazon SNS推送通知在有效负载中发送额外参数

[英]How to send Extra parameters in payload via Amazon SNS Push Notification

This is something new i am asking as i haven't got it any answers for it on SO. 这是我要问的新事物,因为我没有得到任何答案。

I am using Amazon SNS Push for sending push to my registered devices, everything is working good, i can register devices on my app first start, can send push etc etc. The problem i am facing is that, i want to open a specific page when i open my app through push. 我正在使用亚马逊SNS推送发送推送到我的注册设备,一切正常,我可以在我的应用程序首先启动注册设备,可以发送推送等等。我面临的问题是,我想打开一个特定的页面当我通过推动打开我的应用程序。 I want to send some extra params with the payload but i am not able to do that. 我想用有效载荷发送一些额外的参数,但我无法做到这一点。

I tried this Link :- http://docs.aws.amazon.com/sns/latest/api/API_Publish.html 我试过这个链接: - http://docs.aws.amazon.com/sns/latest/api/API_Publish.html

we have only one key ie "Message", in which we can pass the payload as far as i know. 我们只有一个键,即“消息”,据我所知,我们可以在其中传递有效载荷。

i want pass a payload like this :- 我想通过这样的有效载荷: -

{
    aps = {
            alert = "My Push text Msg";
          };
    "id" = "123",
    "s" = "section"
}

or any other format is fine, i just wanted to pass 2-3 values along with payload so that i can use them in my app. 或任何其他格式是好的,我只想传递2-3个值和有效负载,以便我可以在我的应用程序中使用它们。

The code i am using for sending push is :- 我用来发送推送的代码是: -

// Load the AWS SDK for PHP
if($_REQUEST)
{
    $title=$_REQUEST["push_text"];

    if($title!="")
    {
        require 'aws-sdk.phar';


        // Create a new Amazon SNS client
        $sns = Aws\Sns\SnsClient::factory(array(
            'key'    => '...',
            'secret' => '...',
            'region' => 'us-east-1'
        ));

        // Get and display the platform applications
        //print("List All Platform Applications:\n");
        $Model1 = $sns->listPlatformApplications();

        print("\n</br></br>");*/

        // Get the Arn of the first application
        $AppArn = $Model1['PlatformApplications'][0]['PlatformApplicationArn'];

        // Get the application's endpoints
        $Model2 = $sns->listEndpointsByPlatformApplication(array('PlatformApplicationArn' => $AppArn));

        // Display all of the endpoints for the first application
        //print("List All Endpoints for First App:\n");
        foreach ($Model2['Endpoints'] as $Endpoint)
        {
          $EndpointArn = $Endpoint['EndpointArn'];
          //print($EndpointArn . "\n");
        }
        //print("\n</br></br>");

        // Send a message to each endpoint
        //print("Send Message to all Endpoints:\n");
        foreach ($Model2['Endpoints'] as $Endpoint)
        {
          $EndpointArn = $Endpoint['EndpointArn'];

          try
          {
            $sns->publish(array('Message' => $title,
                    'TargetArn' => $EndpointArn));

            //print($EndpointArn . " - Succeeded!\n");
          }
          catch (Exception $e)
          {
            //print($EndpointArn . " - Failed: " . $e->getMessage() . "!\n");
          }
        }
    }
}
?>

Any help or idea will be appreciated. 任何帮助或想法将不胜感激。 Thanks in advance. 提前致谢。

The Amazon SNS documentation is still lacking here, with few pointers on how to format a message to use a custom payload. 此处仍缺少Amazon SNS文档,几乎没有关于如何格式化消息以使用自定义有效负载的指示。 This FAQ explains how to do it, but doesn't provide an example. 此常见问题解答说明了如何操作,但没有提供示例。

The solution is to publish the notification with the MessageStructure parameter set to json and a Message parameter that is json-encoded, with a key for each transport protocol. 解决方案是使用MessageStructure参数设置为json和使用json编码的Message参数发布通知,并使用每个传输协议的密钥。 There always needs to be a default key too, as a fallback. 总是需要一个default密钥,作为后备。

This is an example for iOS notifications with a custom payload: 这是具有自定义有效内容的iOS通知的示例:

array(
    'TargetArn' => $EndpointArn,
    'MessageStructure' => 'json',
    'Message' => json_encode(array(
        'default' => $title,
        'APNS' => json_encode(array(
            'aps' => array(
                'alert' => $title,
            ),
            // Custom payload parameters can go here
            'id' => '123',
            's' => 'section'
        ))

    ))
);

The same goes for other protocols as well. 其他协议也是如此。 The format of the json_encoded message must be like this (but you can omit keys if you don't use the transport): json_encoded消息的格式必须与此类似(但如果不使用传输,则可以省略键):

{ 
    "default": "<enter your message here>", 
    "email": "<enter your message here>", 
    "sqs": "<enter your message here>", 
    "http": "<enter your message here>", 
    "https": "<enter your message here>", 
    "sms": "<enter your message here>", 
    "APNS": "{\"aps\":{\"alert\": \"<message>\",\"sound\":\"default\"} }", 
    "APNS_SANDBOX": "{\"aps\":{\"alert\": \"<message>\",\"sound\":\"default\"} }", 
    "GCM": "{ \"data\": { \"message\": \"<message>\" } }", 
    "ADM": "{ \"data\": { \"message\": \"<message>\" } }" 
}

From a Lambda function (Node.js) the call should be: 从Lambda函数(Node.js)调用应该是:

exports.handler = function(event, context) {

  var params = {
    'TargetArn' : $EndpointArn,
    'MessageStructure' : 'json',
    'Message' : JSON.stringify({
      'default' : $title,
      'APNS' : JSON.stringify({
        'aps' : { 
          'alert' : $title,
          'badge' : '0',
          'sound' : 'default'
        },
        'id' : '123',
        's' : 'section',
      }),
      'APNS_SANDBOX' : JSON.stringify({
        'aps' : { 
          'alert' : $title,
          'badge' : '0',
          'sound' : 'default'
        },
        'id' : '123',
        's' : 'section',
      })
    })
  };

  var sns = new AWS.SNS({apiVersion: '2010-03-31', region: 'us-east-1' });
  sns.publish(params, function(err, data) {
    if (err) {
      // Error
      context.fail(err);
    }
    else {
      // Success
      context.succeed();
    }
  });
}

You can simplify by specifying only one protocol: APNS or APNS_SANDBOX . 您可以通过仅指定一个协议来简化: APNSAPNS_SANDBOX

I am too inexperienced to comment here but I would like to draw peoples attention to the nested json_encode. 我太缺乏经验,无法在这里发表评论,但我想引起人们对嵌套json_encode的关注。 This is important without it the APNS string will not be parsed by Amazon and it will send only the default message value. 这很重要,如果没有APNS字符串将不会被亚马逊解析,它将只发送默认消息值。

I was doing the following: 我正在做以下事情:

$message = json_encode(array(
   'default'=>$msg,
   'APNS'=>array(
      'aps'=>array(
         'alert'=>$msg,
         'sound'=>'default'
         ),
         'id'=>$id,
         'other'=>$other
       )
     )
   );

But this will not work. 但这不起作用。 You MUST json_encode the array under 'APNS' separately as shown in felixdv's answer. 您必须分别对'APNS'下的数组进行json_encode编码,如felixdv的回答所示。 Don't ask me why as the outputs look exactly the same in my console log. 不要问我为什么输出在我的控制台日志中看起来完全一样。 Although the docs show that the json string under the 'APNS' key should be wrapped in "" so suspect this has something to do with it. 虽然文档显示'APNS'键下的json字符串应该包含在“”中,所以怀疑这与它有关。

http://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-custommessage.html http://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-custommessage.html

Dont be fooled though as the JSON will validate fine without these double quotes. 不要被愚弄,因为JSON将在没有这些双引号的情况下验证正常。

Also I am not sure about emkman's comment. 我也不确定埃马克的评论。 Without the 'default' key in the above structure being sent to a single endpoint ARN I would receive an error from AWS. 如果上述结构中的“默认”密钥未发送到单个端点ARN,我将收到来自AWS的错误。

Hope that speeds up someones afternoon. 希望下午加速某些人。

EDIT 编辑

Subsequently cleared up the need to nest the json_encodes - it creates escaped double quotes which despite the docs saying arent required at the API they are for the whole string for GCM and as above the sub array under APNS for apple. 随后清除了嵌套json_encodes的需要 - 它创建了转义双引号,尽管文档说API不需要它们用于GCM的整个字符串,并且在APNS下用于Apple的子数组。 This maybe my implementation but its pretty much out of the box using the AWS PHP SDK and was the only way to make it send custom data. 这可能是我的实现,但它使用AWS PHP SDK几乎是开箱即用的,并且是使其发送自定义数据的唯一方法。

容易错过您需要添加APNS_SANDBOX以及APNS以进行本地测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM