Welcome notifications with Pushpad

Do you want to send a welcome message when a user subscribes to your web push notifications? Here’s how to create welcome notifications using Pushpad Pro.

Inside your web page, where the user subscribes to push notifications, add the following code (it uses the Javascript SDK):

// Generate a random token (e.g. https://stackoverflow.com/questions/10726909)
var nonce =  '...';

pushpad('status', function (isSubscribed) {
  if(!isSubscribed) {
    // the user is not subscribed...
    pushpad('subscribe', function (isSubscribed) {
      if(isSubscribed) {
        // ... and then is subscribed:
        // let's send the welcome notification from the backend
        fetch('/send_welcome_message', {
          method: 'POST',
          body: 'recipient_nonce=' + nonce
        });
      }
    }, {
      // make sure that the subscription has a unique tag
      // so that you can target that subscription from your server
      tags: 'welcome_' + nonce 
    });
  }
});

Now you just need to implement the server-side part (/send_welcome_message) that sends the notification. You can use the libraries. For example with PHP:

$notification = new Pushpad\Notification([
  "body" => "Thanks for subscribing to push notifications!"
]);
$notification->broadcast([
  "tags" => ["welcome_" + $_POST["recipient_nonce"]]
]);

If your users are logged in on your website we recommend to use the user IDs instead of tags. Moreover, if users are logged in, you may want to check out this alternative method for welcome series.

Leave a Reply

Your email address will not be published. Required fields are marked *