
Mendaftar ke Pusher
Langkah pertama adalah mendaftar di Pusher Beams dan membuat sebuah aplikasi baru. Setelah itu, Anda akan mendapatkan Instance ID dan Secret Key yang diperlukan untuk konfigurasi.
Install Pusher SDK
Anda dapat menambahkan SDK ini ke proyek Anda menggunakan composer.
composer require pusher/pusher-push-notifications
Selanjutnya yaitu menyertakan SDK secara langsung melalui tag skrip pada master layout.
<script src="https://js.pusher.com/beams/1.0/push-notifications-cdn.js"></script>
<script>
const beamsClient = new PusherPushNotifications.Client({
instanceId: 'your_instance_id',
});
beamsClient.start()
.then(() => beamsClient.addDeviceInterest('App.User.{{ auth()->user()->id }}'))
.then(() => console.log('Successfully registered and subscribed!'))
.catch(console.error);
function enableNotifications() {
beamsClient.start().then(() => console.log("Registered with beams!"));
}
</script>
Kemudian buat file bernama service-worker.js dengan konten berikut dan simpan di folder root project.
importScripts("https://js.pusher.com/beams/service-worker.js");
Konfigurasi .env
Setelah menginstal SDK, tambahkan BEAMS_INSTANCE_ID dan BEAMS_SECRET_KEY ke file .env Anda.
PUSHER_BEAMS_INSTANCE_ID="your_instance_id"
PUSHER_BEAMS_SECRET_KEY="your_secret_key"
Implementasi Beams
Buatlah route dan controller untuk mengirimkan notifikasi. Misalnya, Anda bisa membuat route seperti ini.
Route::get('/sendAll', [\App\Http\Controllers\PusherController::class, 'publishToInterests']);
Route::get('/sendUser', [\App\Http\Controllers\PusherController::class, 'sendNotificationToUser']);
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
class PusherController extends Controller
{
public function publishToInterests()
{
$beamsClient = new \Pusher\PushNotifications\PushNotifications(array(
"instanceId" => env('PUSHER_BEAMS_INSTANCE_ID'),
"secretKey" => env('PUSHER_BEAMS_SECRET_KEY'),
));
$publishResponse = $beamsClient->publishToInterests(
array("hello"),
array(
"web" => array("notification" => array(
"title" => "Hello",
"body" => "Hello, All!",
"deep_link" => "https://www.pusher.com",
)),
)
);
return response()->json($publishResponse);
}
public function sendNotificationToUser()
{
$beamsClient = new \Pusher\PushNotifications\PushNotifications(array(
"instanceId" => env('PUSHER_BEAMS_INSTANCE_ID'),
"secretKey" => env('PUSHER_BEAMS_SECRET_KEY'),
));
$publishResponse = $beamsClient->publishToInterests(
array("App.User." . Auth::user()->id),
array(
"web" => array("notification" => array(
"title" => "Hello",
"body" => "Hello, " . Auth::user()->name . "!",
"deep_link" => "https://www.pusher.com",
)),
)
);
return response()->json($publishResponse);
}
}