php - 如何使用 PHP cURL 和 FCM 向移动设备发送通知?
问题描述
如何使用 PHP cURL 和 FCM 向移动设备发送通知?
$ch = curl_init(); //init
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');//Fire URL
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//send 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); //.json_encode($fields);
return $result;
curl_close( $ch );
解决方案
$to - 设备 ID
$title - 通知标题
$message - 通知消息
$img - 完整的图片链接
$datapayload - 自定义值的数组。
用法:
发送通知($to, $title, $message, $img, $datapayload = "");
带有演示值:
sendnotification("Device_ID","测试通知","测试消息","https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",array("ID"=>1 ));
function sendnotification($to, $title, $message, $img = "", $datapayload = ""){
$msg = urlencode($message);
$data = array(
'title'=>$title,
'sound' => "default",
'msg'=>$msg,
'data'=>$datapayload,
'body'=>$message,
'color' => "#79bc64"
);
if($img){
$data["image"] = $img;
$data["style"] = "picture";
$data["picture"] = $img;
}
$fields = array(
'to'=>$to,
'notification'=>$data,
'data'=>$datapayload,
"priority" => "high",
);
$headers = array(
'Authorization: key=GOOGLE_API_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 );
return $result;
}
推荐阅读
- navigation - Liferay.SPA.app.navigate 不会在没有路径的情况下重定向
- swiftui - 有没有办法在 SwiftUI 中“激活”自动换行?
- php - 我们如何在 Laravel 的单个控制器中处理 50 个依赖注入?
- ruby-on-rails - Rails 应用程序如何在默认情况下单独使用 Puma 运行 - 没有 Web 服务器
- apache-kafka - 创建刷新流时的问题
- c++ - 为 Windows 构建 SpiderMonkey
- firebase - 你还能在新项目中使用 XMPP 和 Firebase 云消息传递吗?
- javascript - 我的不和谐机器人无法正确发送对命令的多个响应
- python-3.x - 如果 None 使用 attr,如何使用默认值
- svg - 使用 Webpack 处理 SVG 图标字体