FCM( Firebase) 发送推送消息PHP

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值