Search what you want

Monday, March 7, 2016

Create Push Notification with Google Cloud Messaging (1/3)

referensi:
http://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat-app-part-1/


=====================Configurasi di Google Console=============================
1. login dengan akun google
2. kunjungi situs Google Console untuk membuat projek baru.

3. Buat projek baru -> Create project
4. tampilan dashboard, klik Enable and manage APIs

5. klik Module APIs -> Google Cloud Messaging

6. klik enable

7. go to Credentials

8. klik create credentials

9. klik API key

10. klik server key

11. create credentials

12. get API key

13. konfigurasi di google console telah selesai.



========================== Configurasi di Server pribadi=========================

2. Tambahkan variabel di file untuk configurasi database. daftarkan API key dari google console
<?php
/**
 * Database configuration
 */
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '03011995');
define('DB_HOST', 'localhost');
define('DB_NAME', 'restapi');

define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);

define("GOOGLE_API_KEY", "AIzaSyCcIzHEjrhU9Wd08xxxxxxxxxxxxxxxxxxxx");

?>
3. Tambahkan colom gcm_registration_id di tabel users
ALTER TABLE `users` ADD `gcm_registration_id` TEXT NOT NULL AFTER `api_key` ;
4. Tambahkan method "updateGcmID" di DBHandler.php
// updating user GCM registration ID
    public function updateGcmID($user_id, $gcm_registration_id) {
        $response = array();
        $stmt = $this->conn->prepare("UPDATE users SET gcm_registration_id = ? WHERE user_id = ?");
        $stmt->bind_param("si", $gcm_registration_id, $user_id);
 
        if ($stmt->execute()) {
            // User successfully updated
            $response["error"] = false;
            $response["message"] = 'GCM registration ID updated successfully';
        } else {
            // Failed to update user
            $response["error"] = true;
            $response["message"] = "Failed to update GCM registration ID";
            $stmt->error;
        }
        $stmt->close();
 
        return $response;
    }
5.  Tambahkan folder "gcm" di dalam folder "libs"

6. Tambahkan file "gcm.php" dan "push.php"

7. tambahkan code berikut di gcm.php
<?php

class gcm {
    // constructor
    function __construct() {
         
    }
 
    // sending push message to single user by gcm registration id
    public function send($to, $message) {
        $fields = array(
            'to' => $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }
    
    // Sending message to a topic by topic id
    public function sendToTopic($to, $message) {
        $fields = array(
            'to' => '/topics/' . $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }
    
    // function makes curl request to gcm servers
    private function sendPushNotification($fields) {
 
        // include config
        include_once __DIR__ . '/../../include/Config.php';
 
        // Set POST variables
        $url = 'https://gcm-http.googleapis.com/gcm/send';
 
        $headers = array(
            'Authorization: key=' . GOOGLE_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);
 
        // 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;
    }
}

?>
8. tambahkan code berikut di push.php
<?php
/**
 * @author Ravi Tamada
 * @link URL Tutorial link
 */
 
class Push{
    // push message title
    private $title;
     
    // push message payload
    private $data;
     
    // flag indicating background task on push received
    private $is_background;
     
    // flag to indicate the type of notification
    private $flag;
     
    function __construct() {
         
    }
     
    public function setTitle($title){
        $this->title = $title;
    }
     
    public function setData($data){
        $this->data = $data;
    }
     
    public function setIsBackground($is_background){
        $this->is_background = $is_background;
    }
     
    public function setFlag($flag){
        $this->flag = $flag;
    }
     
    public function getPush(){
        $res = array();
        $res['title'] = $this->title;
        $res['is_background'] = $this->is_background;
        $res['flag'] = $this->flag;
        $res['data'] = $this->data;
         
        return $res;
    }
}
9. di file index.php yang berada di folder v1 tambahkan method untuk melakukan update untuk gcm_registration_id
/* * *
 * Updating user
 *  we use this url to update user's gcm registration id
 */
$app->put('/users', 'authenticate', function() use ($app) {
    global $user_id;
 
    verifyRequiredParams(array('gcm_registration_id'));
 
    $gcm_registration_id = $app->request->put('gcm_registration_id');
 
    $db = new DbHandler();
    $response = $db->updateGcmID($user_id, $gcm_registration_id);
 
    echoRespnse(200, $response);
});
10. ubah method untuk menambahkan task, agar ketika data masuk ke server, ada notifikasi ke aplikasi mobile yang kita miliki
/**
 * Creating new task in db
 * method POST
 * params - name
 * url - /tasks/
 */
$app->post('/tasks', 'authenticate', function() use ($app) {
    // check for required params
    verifyRequiredParams(array('sensor1', 'sensor2', 'sensor3', 'output'));

    $response = array();
    $sensor1 = $app->request->post('sensor1');
    $sensor2 = $app->request->post('sensor2');
    $sensor3 = $app->request->post('sensor3');
    $output = $app->request->post('output');

    global $user_id;
    $db = new DbHandler();

    // creating new task
    $task_id = $db->createTask($user_id, $sensor1, $sensor2, $sensor3, $output);

    if ($task_id != NULL) {
        require_once __DIR__ . '/../libs/gcm/gcm.php';
        require_once __DIR__ . '/../libs/gcm/push.php';
        $gcm = new GCM();
        $push = new Push();
        
        $user = $db->getUser($user_id);
        
        $msg = array();
        $msg['message'] = "pH : ".$sensor1."; Suhu : ".$sensor2."; DO : ".$sensor3."; Output : ".$output;
        $msg['message_id'] = '';
        $msg['chat_room_id'] = '';
        $msg['created_at'] = date('Y-m-d G:i:s');

        $data = array();
        $data['user'] = $user;
        $data['message'] = $msg;
        $data['image'] = '';

        $push->setTitle("Google Cloud Messaging");
        $push->setIsBackground(FALSE);
        $push->setFlag(PUSH_FLAG_USER);
        $push->setData($data);
        
        // sending message to topic `global`
        // On the device every user should subscribe to `global` topic
        $gcm->sendToTopic('global', $push->getPush());

        $response['user'] = $user;
        $response['error'] = false;
        
        echoRespnse(201, $push->getPush());
    } else {
        $response["error"] = true;
        $response["message"] = "Failed to create task. Please try again";
        echoRespnse(200, $response);
    }
});










No comments:

Post a Comment