我正在尝试设置一个服务器来发送推送通知。
我正在尝试向指定包的用户发送推送通知,例如com.mysite.android
(此选项在Firebase控制台可用)。检查这样的答案,我不明白如何设置to
参数向指定包的用户发送推送通知。我可以找到发送通知给specific devices by their ids
或news topics
的样品。
澄清:我是应用程序的所有者,我想要发送推送通知。
如果有帮助,下面是我的代码:
<?php
/*
Parameter Example
$data = array('post_id'=>'12345','post_title'=>'A Blog post');
$target = 'single tocken id or topic name';
or
$target = array('token1','token2','...'); // up to 1000 in one request
*/
echo "Start<br/>";
$result = sendMessage('{"id":"hello"}',null);
var_dump($result);
function sendMessage($data,$target){
//FCM api URL
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'xxxxxxxxxxxxxxxxxxxkeyxxxxxxxxxxxxxxxxxxxxxxxx';
$fields = array();
$fields['data'] = $data;
$fields['restricted_package_name']='com.mysite.android ';
$fields['dry_run']=true;
if (isset($target)){
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
注意:我故意删除了我的server_key
。
你不能发送推送通知到任何外部应用程序,除了你自己的应用程序,简单的用户设备令牌和你的服务器密钥被链接在一个项目下,所以你必须使用服务器密钥和有效的设备令牌为"X"应用程序
这是可以管理的。但是,为了能够向应用程序发送通知,您首先需要成为一个有效的Sender。
通常(如果你是应用程序的所有者),你所要做的就是将应用程序添加到你的Firebase项目中,生成google-services。
如果你不是应用程序的所有者,你不想通过你的Firebase项目添加应用程序,这可以通过简单地修改谷歌服务来覆盖。在应用中使用的SenderID . json中添加你的SenderID。但我非常怀疑你一开始就有权限修改不属于你的应用。
注意:不建议修改你的google-services。虽然json。
如果你能够将你的项目设置为一个有效的发送者,你将不得不使用主题消息传递,并将设备订阅到一个主题名称,这是它们的应用程序包名称。
然后在发送到主题时,只需在to
参数中使用包的名称,如下所示:
"to": "/topics/<app_package_name_here>"