Firebase 的管理后台也有发送测试消息推送的入口,在左侧栏目的 Cloud Messaging
准备工作:
1、准备好 服务器秘钥, 如图
打开postman , 创建一个新的api 请求
1、先输入 请求路径 " https://fcm.googleapis.com/fcm/send "
2、改为post 请求
3、设置Headers
3.1、 第一个key是 Authorization , 而对应的value 就是 key=服务器秘钥 (别漏了key= )
3.2、 第二个key是 Content-Type ,对应的value 是 application/json
4、设置body 由json 组装
static function send_message($token = '', $notify_data = []) { if (!$token) { return false; } $notify_data['data']["click_action"] = 'FLUTTER_NOTIFICATION_CLICK'; $notify_msg = [ "notification" => [ "title" => $notify_data['title'], "body" => $notify_data['body'] ], "data" => $notify_data['data'], "to" => $token, "direct_book_ok" => true ]; $data = json_encode($notify_msg); $notify_server_key = 'AAAAOKv***43kAAJiLgnRXfroRR'; $url = "https://fcm.googleapis.com/fcm/send"; $headers = [ "Authorization:key=" . $notify_server_key, "Content-Type:application/json" ]; try { $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, $data); // 在尝试连接时等待的秒数 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 2); // 最大执行时间 curl_setopt($ch, CURLOPT_TIMEOUT, 3); $result = curl_exec($ch); $respon = json_decode($result, true); } catch (\Exception $e) { $respon = []; } if (isset($respon['results'])) { if (isset($respon['results']['error'])) { return false; } else { return true; } } return true; }
使用方法
$notify = [ 'title' =>$message, 'body' => $message, 'data' => [ 'page_type'=> 30, 'bid'=> 0, 'url'=> ''], ]; $res = self::send_message($token, $notify_data);
来源地址:https://blog.csdn.net/qq_23564667/article/details/128551873