【问题标题】:APNS PHP JSON Payload structureAPNS PHP JSON 有效负载结构
【发布时间】:2015-10-19 10:24:59
【问题描述】:

我通过 PHP 脚本发送推送通知以连接到 APNS 服务器。当我使用以下有效负载结构时,一切正常。

$body['aps'] = array(
    'alert' => $message,
    'badge' => $badge,
    'sound' => 'default'

    );

$payload = json_encode($body);

但是,我需要向“警报”元素添加更多参数,并希望添加更多自定义参数。我的做法如下,但 APNS 不接受 JSON。我在 PHP 中创建 JSON 的方法有问题吗?

$payload='{

"aps": {
    "alert":{
    "title": "'.$message.'",    
    "body":"'.$notif_desc.'"
            },
"badge":"'.$badge.'",
"sound": "default"


},
"type": "notification",
"id":"'.$lastid.'",
"date:"'.$date1.'"

}';

所以基本上,我有两个疑问。第二种方法错了吗?如果是这样,请告诉我一个为 APNS 服务器创建嵌套 JSON 有效负载的有效方法。第二个问题,我需要在Payload中添加自定义的PHP变量,我想知道我在第二种方法中添加的方式是对还是错。

基本上,我需要在 PHP 中创建一个 JSON 对象,如下所示

{
    "aps" : {
        "alert" : {
            "title" : "Game Request",
            "body" : "Bob wants to play poker",
            "action-loc-key" : "PLAY"
        },
        "badge" : 5,
    },
    "acme1" : "bar",
    "acme2" : [ "bang",  "whiz" ]
}

【问题讨论】:

    标签: php json nested apple-push-notifications


    【解决方案1】:

    “日期”属性后缺少双引号:

    "date:"'.$date1.'"
    

    ...应该是...

    "date":"'.$date1.'"
    

    我建议首先将有效负载作为 PHP 对象/数组放在一起(就像您的原始示例一样),因为以这种格式而不是巨大的串联字符串更容易查看结构。例如

    $payload['aps'] = array(
        'alert' => array(
            'title' => $title,
            'body' => $body,
            'action-loc-key' => 'PLAY'
        ),
        'badge' => $badge,
        'sound' => 'default'
    );
    $payload['acme1'] = 'bar';
    $payload['acme2'] = array(
        'bang',
        'whiz'
    );
    
    $payload = json_encode($body);
    

    【讨论】:

    • 感谢好友的帮助。问题是,我错过了日期后的双引号。而且我对 JSON 有点尴尬,所以我认为你关于使用 PHP 对象/数组的建议就是我要使用的。谢谢大哥!!!
    • 没问题。制作大字符串肯定会使阅读变得更加困难。祝你编码好运! :)
    【解决方案2】:
    $send_data = 
    array(
            'aps' => 
            array
            (
                'status_code'=>200,
                'alert'=>$message,
                'sound' => 'default',
                'notification_type'=>'DoctorPendingRequest',
                'request_id'=>$request_id
            )
    );
    

    将 $send_data 传递给有效负载。

    【讨论】:

    • 我需要在 alert 元素中进行另一个嵌套。我该怎么做?
    • @AshifShereef 另一个答案中显示的代码应该适合您。
    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 2020-06-30
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多