PushNotify API Logo

PushNotify API

PushNotify API memungkinkan aplikasi web Anda mengirimkan pemberitahuan push kepada pengguna secara realtime.

Unduh Demo: push-notification.zip

Persiapkan

Sebelum memulai anda di perlukan untuk mempersiapkan sebuah layanan pekerjaan (service-worker) agar PushNotify Api dapat berfungsi. buat file baru dengan nama service-worker.js dan isikan dengan kode berikut atau anda dapat mengunduhnya disini service-worker.js:

service-worker.js

self.addEventListener('push', event => {
  const data = event.data.json();

  const options = {
    body: data.notification.body || 'Default Body Message',
    icon: data.notification.icon || 'https://example.com/icon.png',
    image: data.notification.image || 'https://example.com/image.png',
    data: {
      url: data.notification.data.url || 'https://example.com'
    },
    vibrate: [200, 100, 200] 
  };

  event.waitUntil(
    self.registration.showNotification(data.notification.title || 'Default Title', options)
  );
});

self.addEventListener('notificationclick', event => {
  event.notification.close();

  if (event.notification.data && event.notification.data.url) {
    event.waitUntil(
      clients.openWindow(event.notification.data.url)
    );
  }
});

Contoh Penggunaan

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./service-worker.js')
    .then(function (registration) {
        console.log('Service Worker Registered Successfully:', registration.scope);
        return fetchConnection().then(() => subscribeUser(registration));
    })
    .catch(function (error) {
        console.error('Service Worker registration failed:', error);
    });
}

API Endpoint

Endpoint API yang digunakan dalam implementasi PushNotify API.

Koneksi (GET)

https://pushnotify.i-as.dev/api/connection

Contoh Penggunaan

function fetchConnection() {
    return fetch(`https://pushnotify.i-as.dev/api/connection`)
    .then(response => response.json())
    .then(data => {
        publicPushNotifyKey = data.publicKey;
    })
    .catch(error => {
        console.error('Failed to fetch connection:', error);
    });
}

Endpoint ini digunakan untuk mendapatkan koneksi, diperlukan untuk proses mengirim notifikasi, subscribe & unsubscribe pada PushNotify API.

Subscribe (POST)

https://pushnotify.i-as.dev/api/subscribe

Contoh Penggunaan

function subscribeUser(registration) {
    return registration.pushManager.getSubscription()
    .then(function (subscription) {
        if (subscription) {
            console.log('User is already subscribed');
            return subscription;
        }

        const applicationServerKey = urlBase64ToUint8Array(publicPushNotifyKey);
        return registration.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: applicationServerKey
        });
    })
    .then(function (subscription) {
        console.log('Subscription successful');
        return fetch(`https://pushnotify.i-as.dev/api/subscribe`, {
            method: 'POST',
            body: JSON.stringify({
                domain: window.location.host,
                subscription: subscription
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        });
    })
    .catch(function (error) {
        console.error('Subscription failed:', error);
    });
}

Endpoint ini menerima detail langganan push notification yang dikirimkan oleh client-side setelah proses Koneksi berhasil.

Unsubscribe (POST)

https://pushnotify.i-as.dev/api/unsubscribe

Contoh Penggunaan

function unsubscribeUser() {
    navigator.serviceWorker.ready.then(function (registration) {
        return registration.pushManager.getSubscription()
        .then(function (subscription) {
            if (subscription) {
                return fetch(`https://pushnotify.i-as.dev/api/unsubscribe`, {
                    method: 'POST',
                    body: JSON.stringify({
                        domain: window.location.host,
                        subscription: subscription
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(() => subscription.unsubscribe())
                .then(() => console.log('Unsubscribed successfully'))
                .catch(err => console.error('Error during unsubscribe:', err));
            } else {
                console.log('No subscription found');
            }
        });
    });
}

Endpoint ini menerima detail langganan push notification yang dikirimkan oleh client-side untuk menghentikan langganan.

Notification (POST)

https://pushnotify.i-as.dev/api/notification
{
  "title": "Your Notification Title",
  "message": "Your notification message goes here.",
  "imageUrl": "https://example.com/image.png",
  "url": "https://example.com"
}

Contoh Penggunaan

const response = await fetch(`https://pushnotify.i-as.dev/api/notification`, {
	method: 'POST',
	body: JSON.stringify(notificationData),
	headers: {
		'Content-Type': 'application/json'
	}
});

Endpoint ini menerima data notifikasi yang akan dikirimkan kepada pengguna yang telah berlangganan. Data yang dikirimkan biasanya mencakup title, message, imageUrl, dan url.