DIG*_*EDI 18 php android firebase firebase-cloud-messaging
我使用下面的脚本向特定用户发送通知:
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'My_API_KEY' );
$registrationIds = array( TOKENS );
// prep the bundle
$msg = array
(
'body' => "abc",
'title' => "Hello from Api",
'vibrate' => 1,
'sound' => 1,
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
?>
Run Code Online (Sandbox Code Playgroud)
脚本工作正常,但我如何向安装我的应用程序的所有用户发送通知.我在我的应用程序(警报)中创建了一个主题,我可以通过firebase控制台向所有用户发送通知.任何人都可以指导我更新上面的主题脚本.
DIG*_*EDI 23
我通过替换修复
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg
);
Run Code Online (Sandbox Code Playgroud)
至
$fields = array
(
'to' => '/topics/alerts',
'notification' => $msg
);
Run Code Online (Sandbox Code Playgroud)
您可以在没有 curl 的情况下发送通知(这在我的服务器上不可用)。我准备了一个可以向指定主题发送通知的函数:
sendNotification("New post!", "How to send a simple FCM notification in php", ["new_post_id" => "605"], "new_post", "YOUR_SERVER_KEY");
function sendNotification($title = "", $body = "", $customData = [], $topic = "", $serverKey = ""){
if($serverKey != ""){
ini_set("allow_url_fopen", "On");
$data =
[
"to" => '/topics/'.$topic,
"notification" => [
"body" => $body,
"title" => $title,
],
"data" => $customData
];
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n" .
"Authorization:key=".$serverKey
)
);
$context = stream_context_create( $options );
$result = file_get_contents( "https://fcm.googleapis.com/fcm/send", false, $context );
return json_decode( $result );
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13631 次 |
| 最近记录: |