google firebase推送

617 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第4天,点击查看活动详情

google firebase推送(官方文档

Firebase是一种后端即服务,可为构建应用程序提供强大的功能。 它具有核心服务,例如身份验证,云消息传递,崩溃,实时数据库,性能监控等。

FCM是指Firebase Cloud消息传递。 这是Firebase提供的核心功能之一。 如果您需要向应用发送通知,则无需构建自己的服务器

1. 准备工作

获取firebase后台的推送密钥,单个用户推送需要手客户端收集用户的token(token是根据用户的设备来区分的,不同的设备token才会不同,要做好同一个用户换设备token的维护问题),全局推送还要拿到客户端配置的主题topic 在这里插入图片描述

2. 拼凑参数,android和ios有所不同(可选参数还有图片,颜色,链接等,具体可参考上面的官方文档)

```php
public function getPush($firebase_resultactivity) {
        $res = array();
        if($this->IosOrAndroid == 1){
        	//ios
            $res['title'] = $this->title?:'';//消息标题
            $res['body'] = $this->message?:'';//消息内容
            $res['sound'] = "XXXX";//系统提示音
        }else{
        	//android
            $res['data']['title'] = $this->title?:'';//消息标题
            $res['data']['message'] = $this->message?:'';//消息内容
            $res['data']['resultActivity'] = $firebase_resultactivity;//客户端提供,配置之后可以在未打开游戏的情况下,点击消息启动游戏
        }
        return $res;
    }
```

3. 发送请求

```php
private function sendPushNotification($fields) {
    $firebase_key = $fields['firebase_key'];//firebase后台的key
    unset($fields['firebase_key']);
    $url = 'https://fcm.googleapis.com/fcm/send';//请求链接
    //请求头
    $headers = array(
        'Authorization: key=' . $firebase_key,
        'Content-Type: application/json'
    );
    // Open connection
    $ch = curl_init();

    // Set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Disabling SSL Certificate support temporarly
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    // Execute post
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }

    // Close connection
    curl_close($ch);
    return $result;
```

4. 查看返回结果,以下结果即为推送成功,查看客户端是否会收到消息

{"multicast_id":8083597852777327546,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1624346763678416%6bd3ddb8f9fd7ecd"}]}