如何向Firebase推送通知发送附加数据

3

我能够使用php和curl向Ios/Android发送推送通知。现在我想更新代码,以便发送附加参数,例如user_id和name。这样我就可以在前端获取这些信息。但我不知道如何传递这些数据。请问有人可以帮助我吗?

function sendPushNotification($token,$push_notification_title=null,$push_notification_body=null){

$url = env('FIREBASE_URL');
$serverKey = env('FIREBASE_SERVER_KEY');
$title = $push_notification_title??"New Physician Review";
$body = $push_notification_body??"Your case has been reviewed";

$notification = array('title' => $title, 'text' => $body, 'body' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high', 'data' => $notification, 'content_available' => true);

$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=' . $serverKey;


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);

curl_close($ch);

return $response;

}

1个回答

5
如果您想在消息中包含额外信息,可以添加一个data数组。这个data数组与您已有的notification数组类似,但它不会由系统处理,而只是传递给您的应用程序代码。
因此,可以像这样编写:
$notification = array('title' => $title, 'text' => $body, 'body' => $body, 'sound' => 'default', 'badge' => '1');
$data = array('user_id' => 'youruserid', 'name' => 'yohan'); //  new array
$arrayToSend = array('to' => $token, 'notification' => $notification, 
                     'priority' => 'high', 'data' => $data, 'content_available' => true);
                                                    //  use it here

谢谢您的回答。这个解决方案有效。 - yohan dhanushka fernando

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接