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 组装
/**
* 发送消息
* @param string $token
* @param array $notify_data = [
'title' =>'title', 'body' => 'body of message.',
'data' => [ 'page_type'=> 1, 'bid'=> 0, 'url'=> ''],
];
* page_type 1 网页 2 详情 3 阅读页 4 邀请好友 5 福利中心 6 看海量视频 7 签到 8 推送 9 书城 10 书架
11 网页跳出App 12 积分墙 13 下载墙 14 优惠券 15 VIP 16 建议反馈 17 GamePix页游 18 我的回复
* @return bool
* @Date 2021/4/2 9:56
* @Author wzb
*/
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);