php - 无法从 php 脚本向 android 应用程序发送通知
问题描述
我遵循以下 JSON 结构将 PHP 脚本的推送通知发送到 android 应用程序,但无法实现。我正在使用 POSTMAN 并获得 200 的状态代码,但未收到通知。
我遵循的 JSON 结构:
https://firebase.google.com/docs/cloud-messaging/concept-options
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
PHP 脚本
<?php
$API_KEY="AAAAoyz8W_Q:APA91bFIJxTqoBnQo218QIIXi7uCmHFRP604RTC......";
$url = "https://fcm.googleapis.com/fcm/send";
$headers = array(
'Authorization:key='.$API_KEY,
'Content-Type:application/json'
);
$token="2tJfPjKZQ6UTVG....";
$notify=array("message"=>
array('token' =>$token,
'notification'=>array('title'=>"Title",
'body'=>"Body")));
$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_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notify));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}else{
echo $ch;
}
curl_close ( $ch );
?>
解决方案
使用下面的代码。在任何其他 PHP 文件中导入此类,然后传递 fcm 令牌和消息。
<?php
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actuall curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
推荐阅读
- android - 设置播放器后,Android ExoPlayer 控件不起作用
- arrays - 有没有办法阻止人们在在线表格中输入另一种语言?
- python - 带有错误信息的 Euler 项目问题
- python - 在 Python 中调用函数时如何插入换行符
- wix - WIX 单包安装程序 - 每台机器快捷方式
- hadoop - 具有 HA 的现有名称服务的 Cloudera Nameservice 代理设置
- ansible - 连接字符串以在 jinja2 中创建变量
- c - 系统调用挂钩示例参数不正确
- sql - Regex Postgresql:递归删除字符串的最后一部分
- docker - nvidia-docker 在本地找不到 nvidia-smi:latest