Isuru
Isuru

Reputation: 3958

Firebase Cloud Messaging using PHP

I'm trying to use PHP to send a notification from my localhost server. But I cannot get it to work. I previously received curl error. I solved it. But now it doesn't yield any errors. I can successfully send notifications from the Firebase console.

Screenshot

I have created FirebaseCloudMessaging.php to send the messages using curl.

<?php
/**
 * Created by PhpStorm.
 * User: Isuru
 * Date: 18/11/2016
 * Time: 16:47
 */
class FirebaseCloudMessaging {

    // this methods send messages to a single device
    public function send($to, $message){
        $fields = array(
          'to' => $to,
          'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }

    // Send message to topic subscribers
    public function sendToTopic($to, $message){
        $fields = array(
          'to' => '/topics/'. $to,
          'data' => $message,
        );

        return $this->sendPushNotification($fields);
    }

    // Send push message to multiple devices
    public function sendToMultipleDevices($registrationIds, $message){
        $fields = array(
            'to' => $registrationIds,
            'data' => $message,
        );

        return $this->sendPushNotification($fields);
    }

    // CURL request to Firebase Platform
    private function sendPushNotification($fields){

        require_once __DIR__ . '/config.php';

        // POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';

        $headers = array(
            'Authorization: key=' . FIREBASE_API_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);

        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

        // Disable SSL Certificate Support temporary
        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));
        }else{
            json_decode($result);
        }

        // Close connection
        curl_close($ch);

        return $result;


    }

}

And PushNotification.php is a model class for the messages.

<?php
/**
 * Created by PhpStorm.
 * User: Isuru
 * Date: 17/11/2016
 * Time: 01:32
 */
class PushNotification{

    // push message title, message and image
    private $title;
    private $message;
    private $image;

    // data payload
    private $data;

    // flag indicating whether to
    // show the push notification
    private $is_background;

    function _construct(){

    }

    public function setTitle($title){
        $this->title = $title;
    }

    public function setMessage($message){
        $this->message = $message;
    }

    public function setImage($imageUrl){
        $this->image = $imageUrl;
    }

    public function setDataPayload($data){
        $this->data = $data;
    }

    public function setIsBackground($is_background){
        $this->is_background = $is_background;
    }

    public function getPushNotification(){
        $res = array();
        $res['data']['title'] = $this->title;
        $res['data']['is_background'] = $this->is_background;
        $res['data']['message'] = $this->message;
        $res['data']['image'] = $this->image;
        $res['data']['payload'] = $this->data;
        $res['data']['timestamp'] = date('Y-m-d G:i:s');

        return $res;
    }
}

Following index.php shows the form and process the form submission.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Firebase Cloud Messaging</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <style type="text/css">
        /*Panel tabs*/
        .panel-tabs {
            position: relative;
            bottom: 30px;
            clear: both;
            border-bottom: 1px solid transparent;
        }

        .panel-tabs > li {
            float: left;
            margin-bottom: -1px;
        }

        .panel-tabs > li > a {
            margin-right: 2px;
            margin-top: 4px;
            line-height: .85;
            border: 1px solid transparent;
            border-radius: 4px 4px 0 0;
            color: #ffffff;
        }

        .panel-tabs > li > a:hover {
            border-color: transparent;
            color: #ffffff;
            background-color: transparent;
        }

        .panel-tabs > li.active > a,
        .panel-tabs > li.active > a:hover,
        .panel-tabs > li.active > a:focus {
            color: #fff;
            cursor: default;
            -webkit-border-radius: 2px;
            -moz-border-radius: 2px;
            border-radius: 2px;
            background-color: rgba(255, 255, 255, .23);
            border-bottom-color: transparent;
        }

        .input_width {
            width: 520px;
        }
    </style>

</head>
<body>

<br>
<div class="container">

    <?php

    // Enabling error reporting
    error_reporting(-1);
    ini_set('display_errors', 'On');

    require_once __DIR__ . '/FirebaseCloudMessaging.php';
    require_once __DIR__ . '/PushNotification.php';

    $firebaseCloudMessaging = new FirebaseCloudMessaging();
    $pushNotification = new PushNotification();

    // optional payload
    $payload = array();

    // notification title
    $title = isset($_GET['title']) ? $_GET['title'] : '';

    // notification message
    $message = isset($_GET['message']) ? $_GET['message'] : '';

    // push type - single user / topic
    $push_type = isset($_GET['push_type']) ? $_GET['push_type'] : '';

    $pushNotification->setTitle($title);
    $pushNotification->setMessage($message);
    $pushNotification->setIsBackground(FALSE);
    $pushNotification->setDataPayload($payload);

    $json = '';
    $response = '';

    if ($push_type == 'topic') {
        $json = $pushNotification->getPushNotification();
        $response = $firebaseCloudMessaging->sendToTopic('news', $json);
    } else if ($push_type == 'individual') {
        $json = $pushNotification->getPushNotification();
        $regId = isset($_GET['regId']) ? $_GET['regId'] : '';
        $response = $firebaseCloudMessaging->send($regId, $json);
    }

    ?>

    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-primary">

                <div class="fl_window">                    
                    <br/>
                    <?php if ($json != '') { ?>
                        <label><b>Request:</b></label>
                        <div class="json_preview">
                            <pre><?php echo json_encode($json) ?></pre>
                        </div>
                    <?php } ?>
                    <br/>
                    <?php if ($response != '') { ?>
                        <label><b>Response:</b></label>
                        <div class="json_preview">
                            <pre><?php echo json_encode($response) ?></pre>
                        </div>
                    <?php } ?>

                </div>

                <div class="panel-heading">
                    <h3 class="panel-title">Firebase Cloud Messaging</h3>
                    <span class="pull-right">
                        <!-- Tabs -->
                        <ul class="nav panel-tabs">
                            <li class="active"><a href="#tab1" data-toggle="tab">Single Device</a></li>
                            <li><a href="#tab2" data-toggle="tab">Send To Topic 'News'</a></li>
                        </ul>
                    </span>
                </div>
                <div class="panel-body">
                    <div class="tab-content">
                        <div class="tab-pane active" id="tab1">
                            <form class="pure-form pure-form-stacked" method="get">
                                <fieldset>
                                    <div class="form-group">
                                        <div class="input_width">
                                            <input
                                                class="form-control input-lg" type="text"
                                                placeholder="Enter Firebase Registration ID" id="redId" name="regId"
                                                placeholder="Enter Firebase Registration ID">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="input_width">
                                            <input
                                                class="form-control input-lg" type="title"
                                                placeholder="Enter Title" id="title" name="title">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div>
                                            <textarea class="input_width input-lg" rows="5" name="message" id="message"
                                                      placeholder="Notification message!"></textarea>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div>
                                            <input name="include_image" id="include_image" type="checkbox"> Include
                                            image
                                        </div>
                                    </div>
                                </fieldset>
                                <input type="hidden" name="push_type" value="individual"/>
                                <div class=" text-center">
                                    <input type="submit" class="btn btn-primary" value="SUBMIT"/>
                                </div>
                            </form>
                        </div>
                        <div class="tab-pane" id="tab2">
                            <form class="pure-form pure-form-stacked" method="get">
                                <fieldset>
                                    <div class="form-group">
                                        <div class="input_width">
                                            <input
                                                class="form-control input-lg" type="text"
                                                placeholder="Enter Title" id="title1" name="title"
                                                placeholder="Enter Title">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div>
                                            <textarea class="input_width input-lg" rows="5" name="message" id="message"
                                                      placeholder="Notification message!"></textarea>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div>
                                            <input name="include_image" id="include_image" type="checkbox"> Include
                                            image
                                        </div>
                                    </div>
                                </fieldset>
                                <input type="hidden" name="push_type" value="topic"/>
                                <div class=" text-center">
                                    <input type="submit" class="btn btn-primary" value="Send to Topic Subscribers"/>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>

enter image description here

And config.php stores the web API. Is there a way to debug the code? For example to check whether Google accepts my request? Any suggestion is appreciated.

Thank you!

Upvotes: 1

Views: 1223

Answers (1)

bipin patel
bipin patel

Reputation: 2111

Change your $fields array like this

$fields = array (
    'registration_ids' => array (
            $registrationIds
    ),
    'notification' => array (
            "title" => "Title here",
            "text" => $message
    ));

It's work for me

Upvotes: 1

Related Questions