Search code examples
phphttpfirebasehttprequestyii2-advanced-app

Integrating android firebase notification in php yii2.0


I know it the very silly question, I'm integrating android Firebase notification in yii2 backend. I got to know many yii2 extension but that's not working, I found this one simple so trying to use this. But I'm not getting how to use this, I have to send HTTP request for this. Here is the code.

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=Your_Authorization_Key
 {
   "registration_ids": ["registration_token"],
   "data": {
    "message": "This is a Firebase Message!",
 }
}

I have the auth_key and registration token, Just need to know how to execute this.


Solution

  • Yes i did it!! Here is the way for anyone trying this.

    Lets say you have a backend in which you are submitting "title" and "body" of the push notification. Now when i submit my form, it has a action where im reading the submit data. Like this.

    use backend\helpers\FirebaseNotifications; 
    

    is defined in top

    if ($model->load(Yii::$app->request->post())) {
            $model->save(false);
            $title = $model->title;
            $body = $model->content;
            $service = new FirebaseNotifications(['authKey' => 
          'YOUR_AUTH_KEY']);
    
            $all_users = User::find()->where(['!=','device_id','Null'])->andwhere(['!=','device_id',' '])->all();
            $tokens = [];    
                foreach ($all_users as $users) { 
                     $tokens[] = $users['device_id'];
                } 
            $message = array('title' => $title, 'body' => $body);
            $service->sendNotification($tokens, $message);
    
            return $this->redirect(['index']);
     }
    

    Im calling

    $service->sendNotification($tokens, $message);

    which is defined in helpers class in a separate file. under helpers folder like FirebaseNotifications.php. And its content look like this.

    <?php
        namespace backend\helpers;
    
        use yii\base\Object;
        use Yii;
        use yii\helpers\ArrayHelper;
    
        class FirebaseNotifications extends Object
        { 
            public $authKey;
            public $timeout = 50;
            public $sslVerifyHost = false;
            public $sslVerifyPeer = false;
            public $apiUrl = 'https://fcm.googleapis.com/fcm/send';
    
            public function init()
            {
                if (!$this->authKey) throw new \Exception("Empty authKey");
            }
    
            public function send($body)
            {
                $headers = [
                    "Authorization:key={$this->authKey}",
                    'Content-Type: application/json',
                    'Expect: ',
                ];
                $ch = curl_init($this->apiUrl);
                curl_setopt_array($ch, [
                    CURLOPT_POST           => true,
                    CURLOPT_SSL_VERIFYHOST => $this->sslVerifyHost,
                    CURLOPT_SSL_VERIFYPEER => $this->sslVerifyPeer,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_BINARYTRANSFER => true,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_HEADER         => false,
                    CURLOPT_FRESH_CONNECT  => false,
                    CURLOPT_FORBID_REUSE   => false,
                    CURLOPT_HTTPHEADER     => $headers,
                    CURLOPT_TIMEOUT        => $this->timeout,
                    CURLOPT_POSTFIELDS     => json_encode($body),
                ]);
                $result = curl_exec($ch);
    
                if ($result === false) {
                    Yii::error('Curl failed: '.curl_error($ch).", with result=$result");
                    throw new \Exception("Could not send notification..");
                }
                $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if ($code<200 || $code>=300) {
                    Yii::error("got unexpected response code $code with result=$result");
                    throw new \Exception("Could not send notification");
                }
                curl_close($ch);
                $result = json_decode($result , true);
                return $result;
            }
    
            public function sendNotification($tokens = [], $notification, $options = [])
            {   
                $body = array(
                    'registration_ids' => $tokens,
                    'notification' => $notification,
                        //array('title' => 'Time of Sports', 'body' => 'Salman Notification'),
                    //'data' => array('message' => $notification)
                );
                $body = ArrayHelper::merge($body, $options);
                return $this->send($body);
            }
    
        }