Saturday, January 2, 2016

Push Google Cloud Message (GCM) from PHP Web Application

In this blog I am going to explain how to push a Google Cloud Message (GCM) from PHP web application.

First of all you will need API key from your Google API account. Go to Google API console and add GCM t your API project and generate a key for Android.  This key you have to add in your PHP script.

Now add following function to your PHP script.

public function send_notification($registatoin_ids, $message) {
     
        // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';
        $apiKey = 'your_api_key';
     
        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );

        $headers = array(
            'Authorization: key=' . $apiKey,
            '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;
    }

As you can see above function takes registration id and message as param and use curl to send push message to particular device. Registration is is unique per device for all the android phones.

No comments:

Post a Comment