Search code examples
phppush-notificationweb-pushpushpad

How to send notification to the browser of the selected user


I am using PushPad Web Push Notification service using PHP. I can easily push notifications but they are sent to all browsers. Lets say I have a lot of users.

user 1
user 2 
user 3
...

Now I want to send notification to just User 1. I cannot think of the idea how to do it. Can anyone give me a hint or idea of how this can be achievable? I asked my collegue but he says this is not possible in PushPad. I have no other means of getting information regarding this issue. Thanks for help in advance.


Solution

  • Yes, you can target specific users as described in the docs.

    1. Keep track of the user ID on subscription

    When you subscribe a user to push notifications, attach some metadata to its subscription:

    pushpad('subscribe', null, uid: 'User1', uidSignature: 'YOUR_SIGNATURE');
    
    • You can use any string as the user ID (uid): in this example I use 'User1', but you can simply call it '1'
    • The uidSignature can be generated using the PHP library: Pushpad\Pushpad::signature_for($uid);
    • You can read more about the pushpad('subscribe') method and the similar pushpad('uid') method in the Javascript SDK reference

    2. Send notifications to specific users

    When you send push notifications from your server (with the PHP library) you can target specific users:

    $notification = new Pushpad\Notification(array(
      'body' => "Hello world!"
    ));
    
    # deliver to a user
    $notification->deliver_to('User1');
    
    # deliver to a group of users
    $notification->deliver_to(['User1', 'User2', 'User3']);