kali ini kita akan mencoba mengirimkan Firebase Push Notification dari server (PHP) ke aplikasi android Show firebase sendiri sudah menyiapkan link/endpoint untuk mengirimkan push notification secara instan dengan mengisi semua parameter header dan body yaitu https://fcm.googleapis.com/fcm/send Anda dapat membaca detailnya di sini ok pertama buat file php dengan nama yang sama yang penting ada di folder server lokal (XAMPP/MAMP/LAMP/LARAGON) untuk melakukan request ke endpoint FCM kita akan menggunakan metode curl di php <?php function sendPushNotification($fcm_token, $title, $message, $id = null,$action = null) { $url = "https://fcm.googleapis.com/fcm/send"; $header = [ 'authorization: key=<TOKEN_MU>', 'content-type: application/json' ]; $notification = [ 'title' =>$title, 'body' => $message ]; $extraNotificationData = ["message" => $notification,"id" =>$id,'action'=>$action]; $fcmNotification = [ 'to' => $fcm_token, 'notification' => $notification, 'data' => $extraNotificationData ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification)); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); $result = curl_exec($ch); curl_close($ch); return $result; }_ isi maka kita panggil saja fungsinya <?php sendPushNotification("<FCM_TOKEN_DARI_APLIKASI_ANDROID>","Ini Title","Ini Isi",123456,"notif") Anda bisa mendapatkan token fcm dari generate di aplikasi android menggunakan library firebase jadi alurnya adalah jika pengguna mendaftar 1. register pengguna 2. aplikasi android menghasilkan token fcm 3. aplikasi mengirimkan data pengguna dan token fcm yang telah dihasilkan 4. kemudian kedua data tersebut disimpan dalam database 5. selanjutnya kita tinggal menggunakan token fcm yang ada di database untuk digunakan mengirim notifikasi ke user Push Notification adalah saluran komunikasi yang paling banyak digunakan oleh aplikasi web untuk tetap berhubungan dengan penggunanya. Saat kami mengunjungi situs web mana pun, kami melihat peringatan izin pemberitahuan untuk mengizinkan atau memblokir pemberitahuan. Lansiran ini dibuat oleh situs web untuk mendapatkan persetujuan untuk menampilkan pemberitahuan dengan pembaruan terkini, berita, dll. Jika kami memberikan izin untuk menampilkan notifikasi, maka notifikasi tersebut didorong oleh administrator situs web untuk ditampilkan kepada pengguna situs web Saat ini, pemberitahuan push adalah fungsi yang paling menuntut yang diterapkan di situs web. Jadi jika Anda sedang mengembangkan aplikasi web dan perlu mengimplementasikan fungsi notifikasi push, maka Anda berada di tempat yang tepat. Dalam tutorial kami sebelumnya Anda belajar bagaimana mengimplementasikan penyaringan pencarian produk dengan PHP, Dalam tutorial ini Anda akan belajar cara membuat Push Notification System dengan PHP dan MySQL Baca juga
Kami akan membahas tutorial ini selangkah demi selangkah dengan contoh langsung untuk membuat notifikasi dengan detail push oleh administrator dan normal dapat masuk untuk melihat notifikasi push Jadi mari kita terapkan Sistem Notifikasi Push dengan PHP dan MySQL. File utamanya adalah
Langkah 1. Buat Tabel Basis Data MySQLPertama kita akan membuat tabel database MySQL INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345');_3 untuk admin dan pengguna normal untuk menguji sistem pemberitahuan push CREATE TABLE `notification_user` ( `id` int(11) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notification_user` ADD PRIMARY KEY (`id`); ALTER TABLE `notification_user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;_ Kami akan memasukkan beberapa catatan pengguna untuk tujuan pengujian INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345'); Kami akan membuat tabel database MySQL INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345');_4 untuk menyimpan detail notifikasi CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; Langkah 2. Desain Formulir Login PenggunaKami akan membuat INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345');5 file dan mendesain formulir login <div class="container"> <h2>User Login:</h2> <div class="row"> <div class="col-sm-4"> <form method="post"> <div class="form-group"> <?php if ($message ) { ?> <div class="alert alert-warning"><?php echo $message; ?></div> <?php } ?> </div> <div class="form-group"> <label for="username">Username:</label> <input type="username" class="form-control" name="username" required> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" name="password" required> </div> <button type="submit" name="login" class="btn btn-default">Login</button> </form><br> </div> </div> </div>_ Kami akan menangani fungsionalitas login pengguna dengan memanggil metode INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345');6 dari kelas INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345');7. Kami akan menyimpan nama pengguna ke dalam sesi untuk digunakan sambil mengimplementasikan fungsi pemberitahuan push session_start(); $message = ''; if (!empty($_POST['username']) && !empty($_POST['password'])) { include_once 'config/Database.php'; include_once 'class/User.php'; $database = new Database(); $db = $database->getConnection(); $user = new User($db); $user->username = $_POST['username']; $user->password = $_POST['password']; if($user->login()) { $_SESSION['username'] = $user->username; header("Location:index.php"); } else { $message = "Invalid username or password!"; } } Kami akan menerapkan metode INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345');_8 di kelas INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES (1, 'webdamn', '12345'), (2, 'admin', '12345');7 function login (){ $stmt = $this->conn->prepare(" SELECT id as userid, username, password FROM ".$this->userTable." WHERE username = ? AND password = ? "); $stmt->bind_param("ss", $this->username, $this->password); $stmt->execute(); $result = $stmt->get_result(); return $result; } Langkah 3. Menampilkan Akun PenggunaKami akan membuat file CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;_0 untuk menampilkan detail pengguna yang masuk. Kami juga akan menampilkan bagian notifikasi kelola untuk pengguna Administrator <div class="container"> <h2>Example: Build Push Notification System with PHP & MySQL</h2> <h3>User Account </h3> <?php if(isset($_SESSION['username']) && $_SESSION['username'] == 'admin') { ?> <a href="manage.php">Manage Notification</a> | <?php } ?> <?php if(isset($_SESSION['username']) && $_SESSION['username']) { ?> Logged in : <strong><?php echo $_SESSION['username']; ?></strong> | <a href="logout.php">Logout</a> <?php } else { ?> <a href="login.php">Login</a> <?php } ?> <hr> <?php if (isset($_SESSION['username']) && $_SESSION['username']) { ?> <div <?php if($_SESSION['username'] != 'admin') { ?> id="loggedIn" <?php } ?>> <h4> You're welcome! You can manage </h4> </div> <?php } ?> </div> Langkah4. Kelola Notifikasi dan daftarKami akan membuat file CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;1 dan mengelola fungsionalitas Administrator untuk membuat notifikasi baru dengan detail dan menugaskan pengguna untuk menampilkan notifikasi push. Kami akan memanggil metode CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;2 dari kelas CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;3. Kami juga akan mencantumkan notifikasi yang dibuat di halaman ini <div class="row"> <div class="col-sm-6"> <h3>Add New Notification:</h3> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <table class="table borderless"> <tr> <td>Title</td> <td><input type="text" name="title" class="form-control" required></td> </tr> <tr> <td>Message</td> <td><textarea name="message" cols="50" rows="4" class="form-control" required></textarea></td> </tr> <tr> <td>Broadcast time</td> <td><select name="ntime" class="form-control"><option>Now</option></select> </td> </tr> <tr> <td>Loop (time)</td> <td><select name="loops" class="form-control"> <?php for ($i=1; $i<=5 ; $i++) { ?> <option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?> </select></td> </tr> <tr> <td>Loop Every (Minute)</td> <td><select name="loop_every" class="form-control"> <?php for ($i=1; $i<=60 ; $i++) { ?> <option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?> </select> </td> </tr> <tr> <td>For</td> <td><select name="user" class="form-control"> <?php $allUser = $user->listAll(); while ($user = $allUser->fetch_assoc()) { ?> <option value="<?php echo $user['username'] ?>"><?php echo $user['username'] ?></option> <?php } ?> </select></td> </tr> <tr> <td colspan=1></td> <td colspan=1></td> </tr> <tr> <td colspan=1></td> <td><button name="submit" type="submit" class="btn btn-info">Add Message</button></td> </tr> </table> </form> </div> </div> <?php if (isset($_POST['submit'])) { if(isset($_POST['message']) and isset($_POST['ntime']) and isset($_POST['loops']) and isset($_POST['loop_every']) and isset($_POST['user'])) { $notification->title = $_POST['title']; $notification->message = $_POST['message']; $notification->ntime = date('Y-m-d H:i:s'); $notification->repeat = $_POST['loops']; $notification->nloop = $_POST['loop_every']; $notification->username = $_POST['user']; if($notification->saveNotification()) { echo '* save new notification success'; } else { echo 'error save data'; } } else { echo '* completed the parameter above'; } } ?> <h3>Notifications List:</h3> <table class="table"> <thead> <tr> <th>No</th> <th>Next Schedule</th> <th>Title</th> <th>Message</th> <th>Remains</th> <th>User</th> </tr> </thead> <tbody> <?php $notificationCount =1; $notificationList = $notification->listNotification(); while ($notif = $notificationList->fetch_assoc()) { ?> <tr> <td><?php echo $notificationCount ?></td> <td><?php echo $notif['ntime'] ?></td> <td><?php echo $notif['title'] ?></td> <td><?php echo $notif['message'] ?></td> <td><?php echo $notif['nloop']; ?></td> <td><?php echo $notif['username'] ?></td> </tr> <?php $notificationCount++; } ?> </tbody> </table> Kami akan menerapkan metode CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;2 di kelas CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;3 function saveNotification(){ $insertQuery = " INSERT INTO ".$this->notificationTable."( `title`, `message`, `ntime`, `repeat`, `nloop`, `username`) VALUES(?,?,?,?,?,?)"; $stmt = $this->conn->prepare($insertQuery); $stmt->bind_param("sssiis",$this->title, $this->message, $this->ntime, $this->repeat, $this->nloop, $this->username); if($stmt->execute()){ return true; } return false; } Langkah5. Menangani Notifikasi PushKami akan membuat file JavaScript CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;_6 dan mengimplementasikan fungsi CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;7 untuk mendapatkan detail notifikasi dengan membuat permintaan Ajax ke file CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;8. Fungsi ini juga akan menangani fungsionalitas pemberitahuan push dengan memeriksa izin dan menampilkannya function getNotification() { if (!Notification) { $('body').append('*Browser does not support Web Notification'); return; } if (Notification.permission !== "granted") { Notification.requestPermission(); } else { $.ajax({ url : "notification.php", type: "POST", success: function(response, textStatus, jqXHR) { var response = jQuery.parseJSON(response); if(response.result == true) { var notificationDetails = response.notif; for (var i = notificationDetails.length - 1; i >= 0; i--) { var notificationUrl = notificationDetails[i]['url']; var notificationObj = new Notification(notificationDetails[i]['title'], { icon: notificationDetails[i]['icon'], body: notificationDetails[i]['message'], }); notificationObj.onclick = function () { window.open(notificationUrl); notificationObj.close(); }; setTimeout(function(){ notificationObj.close(); }, 5000); }; } else { } }, error: function(jqXHR, textStatus, errorThrown) {} }); } } Langkah6. Dapatkan Detail Notifikasi PushKami akan membuat file CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;_8 dan masuk ke detail pemberitahuan pengguna dengan memanggil metode <div class="container"> <h2>User Login:</h2> <div class="row"> <div class="col-sm-4"> <form method="post"> <div class="form-group"> <?php if ($message ) { ?> <div class="alert alert-warning"><?php echo $message; ?></div> <?php } ?> </div> <div class="form-group"> <label for="username">Username:</label> <input type="username" class="form-control" name="username" required> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" name="password" required> </div> <button type="submit" name="login" class="btn btn-default">Login</button> </form><br> </div> </div> </div>0 untuk menampilkan pemberitahuan. Detail notifikasi telah diperbarui setelah menampilkan notifikasi dengan memanggil metode <div class="container"> <h2>User Login:</h2> <div class="row"> <div class="col-sm-4"> <form method="post"> <div class="form-group"> <?php if ($message ) { ?> <div class="alert alert-warning"><?php echo $message; ?></div> <?php } ?> </div> <div class="form-group"> <label for="username">Username:</label> <input type="username" class="form-control" name="username" required> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" name="password" required> </div> <button type="submit" name="login" class="btn btn-default">Login</button> </form><br> </div> </div> </div>1 dari kelas CREATE TABLE `notifications` ( `id` int(11) NOT NULL, `title` varchar(250) NOT NULL, `message` text NOT NULL, `ntime` datetime DEFAULT NULL, `repeat` int(11) DEFAULT 1, `nloop` int(11) NOT NULL DEFAULT 1, `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `username` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `notifications` ADD PRIMARY KEY (`id`); ALTER TABLE `notifications` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;3. Detail notifikasi dikembalikan sebagai data JSON |