Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

66 Commits

Repository files navigation

Pushpad - Web Push Notifications

Maven CentralBuild Status

Pushpad is a service for sending push notifications from websites and web apps. It uses the Push API, which is a standard supported by all major browsers (Chrome, Firefox, Opera, Edge, Safari).

The notifications are delivered in real time even when the users are not on your website and you can target specific users or send bulk notifications.

Installation

You can add the dependency with Maven:

<dependency>
<groupId>xyz.pushpad</groupId>
<artifactId>pushpad-java</artifactId>
<version>2.0.0</version>
</dependency>

Or Gradle:

implementation 'xyz.pushpad:pushpad-java:2.0.0'

Then import the classes:

importxyz.pushpad.Pushpad;
importxyz.pushpad.PushpadException;
importxyz.pushpad.ApiException;
importxyz.pushpad.notification.*;
importxyz.pushpad.project.*;
importxyz.pushpad.sender.*;
importxyz.pushpad.subscription.*;

Getting started

First you need to sign up to Pushpad and create a project there.

Then create a client with your authentication credentials and project:

StringauthToken = "token";
LongprojectId = 123L;
Pushpadpushpad = newPushpad(authToken, projectId);
  • authToken can be found in the user account settings.
  • projectId can be found in the project settings.

If your application uses multiple projects, you can create one client per project or you can pass the projectId as a param to methods:

Pushpadpushpad = newPushpad("token");
NotificationCreateResponseres1 = pushpad.notifications().create(newNotificationCreateParams()
.setProjectId(123L)
.setBody("Project A message"));
NotificationCreateResponseres2 = pushpad.notifications().create(newNotificationCreateParams()
.setProjectId(456L)
.setBody("Project B message"));

Collecting user subscriptions to push notifications

You can subscribe the users to your notifications using the Javascript SDK, as described in the getting started guide.

If you need to generate the HMAC signature for the uid you can use this helper:

Strings = pushpad.signatureFor("CURRENT_USER_ID");
System.out.printf("User ID Signature: %s%n", s);

Sending push notifications

Use pushpad.notifications().create() (or the send() alias) to create and send a notification:

NotificationCreateParamsn = newNotificationCreateParams()
// required, the main content of the notification
.setBody("Hello world!")
// optional, the title of the notification (defaults to your project name)
.setTitle("Website Name")
// optional, open this link on notification click (defaults to your project website)
.setTargetUrl("https://example.com")
// optional, the icon of the notification (defaults to the project icon)
.setIconUrl("https://example.com/assets/icon.png")
// optional, the small icon displayed in the status bar (defaults to the project badge)
.setBadgeUrl("https://example.com/assets/badge.png")
// optional, an image to display in the notification content// see https://pushpad.xyz/docs/sending_images
.setImageUrl("https://example.com/assets/image.png")
// optional, drop the notification after this number of seconds if a device is offline
.setTtl(604800L)
// optional, prevent Chrome on desktop from automatically closing the notification after a few seconds
.setRequireInteraction(true)
// optional, enable this option if you want a mute notification without any sound
.setSilent(false)
// optional, enable this option only for time-sensitive alerts (e.g. incoming phone call)
.setUrgent(false)
// optional, a string that is passed as an argument to action button callbacks
.setCustomData("123")
// optional, add some action buttons to the notification// see https://pushpad.xyz/docs/action_buttons
.setActions(List.of(newNotificationActionParams()
.setTitle("My Button 1")
.setTargetUrl("https://example.com/button-link") // optional
.setIcon("https://example.com/assets/button-icon.png") // optional
.setAction("myActionName"))) // optional// optional, bookmark the notification in the Pushpad dashboard (e.g. to highlight manual notifications)
.setStarred(true)
// optional, use this option only if you need to create scheduled notifications (max 5 days)// see https://pushpad.xyz/docs/schedule_notifications
.setSendAt(sendAtTime) // OffsetDateTime sendAtTime = OffsetDateTime.of(2022, 12, 25, 0, 0, 0, 0, ZoneOffset.UTC)// optional, add the notification to custom categories for stats aggregation// see https://pushpad.xyz/docs/monitoring
.setCustomMetrics(List.of("examples", "another_metric")); // up to 3 metrics per notificationNotificationCreateResponseresponse = pushpad.notifications().create(n);
// TARGETING:// You can use UIDs and Tags for sending the notification only to a specific audience...// deliver to a userNotificationCreateParamsn1 = newNotificationCreateParams()
.setBody("Hi user1")
.setUids(List.of("user1"));
NotificationCreateResponseres1 = pushpad.notifications().create(n1);
// deliver to a group of usersNotificationCreateParamsn2 = newNotificationCreateParams()
.setBody("Hi users")
.setUids(List.of("user1", "user2", "user3"));
NotificationCreateResponseres2 = pushpad.notifications().create(n2);
// deliver to some users only if they have a given preference// e.g. only "users" who have a interested in "events" will be reachedNotificationCreateParamsn3 = newNotificationCreateParams()
.setBody("New event")
.setUids(List.of("user1", "user2"))
.setTags(List.of("events"));
NotificationCreateResponseres3 = pushpad.notifications().create(n3);
// deliver to segments// e.g. any subscriber that has the tag "segment1" OR "segment2"NotificationCreateParamsn4 = newNotificationCreateParams()
.setBody("Example")
.setTags(List.of("segment1", "segment2"));
NotificationCreateResponseres4 = pushpad.notifications().create(n4);
// you can use boolean expressions// they can include parentheses and the operators !, &&, || (from highest to lowest precedence)// https://pushpad.xyz/docs/tagsNotificationCreateParamsn5 = newNotificationCreateParams()
.setBody("Example")
.setTags(List.of("zip_code:28865 && !optout:local_events || friend_of:Organizer123"));
NotificationCreateResponseres5 = pushpad.notifications().create(n5);
NotificationCreateParamsn6 = newNotificationCreateParams()
.setBody("Example")
.setTags(List.of("tag1 && tag2", "tag3")); // equal to 'tag1 && tag2 || tag3'NotificationCreateResponseres6 = pushpad.notifications().create(n6);
// deliver to everyoneNotificationCreateParamsn7 = newNotificationCreateParams()
.setBody("Hello everybody");
NotificationCreateResponseres7 = pushpad.notifications().create(n7);

You can set the default values for most fields in the project settings. See also the docs for more information about notification fields.

If you try to send a notification to a user ID, but that user is not subscribed, that ID is simply ignored.

These fields are returned by the API:

NotificationCreateResponseresponse = pushpad.notifications().create(n);
// Notification IDSystem.out.println(response.getId()); // => 1000// Estimated number of devices that will receive the notification// Not available for notifications that use SendAtSystem.out.println(response.getScheduled()); // => 5// Available only if you specify some user IDs (UIDs) in the request:// it indicates which of those users are subscribed to notifications.// Not available for notifications that use SendAtSystem.out.println(response.getUids()); // => ["user1", "user2"]// The time when the notification will be sent.// Available for notifications that use SendAtSystem.out.println(response.getSendAt()); // => 2025-10-30T10:09Z

Getting push notification data

You can retrieve data for past notifications:

Notificationnotification = pushpad.notifications().get(42);
// get basic attributesSystem.out.println(notification.getId()); // => 42System.out.println(notification.getTitle()); // => Foo BarSystem.out.println(notification.getBody()); // => Lorem ipsum dolor sit amet, consectetur adipiscing elit.System.out.println(notification.getTargetUrl()); // => https://example.comSystem.out.println(notification.getTtl()); // => 604800System.out.println(notification.getRequireInteraction()); // => falseSystem.out.println(notification.getSilent()); // => falseSystem.out.println(notification.getUrgent()); // => falseSystem.out.println(notification.getIconUrl()); // => https://example.com/assets/icon.pngSystem.out.println(notification.getBadgeUrl()); // => https://example.com/assets/badge.pngSystem.out.println(notification.getCreatedAt()); // => 2025-07-06T10:09:14Z// get statisticsSystem.out.println(notification.getScheduledCount()); // => 1System.out.println(notification.getSuccessfullySentCount()); // => 4System.out.println(notification.getOpenedCount()); // => 2

Or for multiple notifications of a project at once:

List<Notification> notifications = pushpad.notifications().list(newNotificationListParams()
.setPage(1L));
// same attributes as for single notification in example aboveSystem.out.println(notifications.get(0).getId()); // => 42System.out.println(notifications.get(0).getTitle()); // => Foo Bar

The REST API paginates the result set. You can pass a page parameter to get the full list in multiple requests.

List<Notification> notifications = pushpad.notifications().list(newNotificationListParams()
.setPage(2L));

Scheduled notifications

You can create scheduled notifications that will be sent in the future:

OffsetDateTimesendAt = OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(60);
NotificationCreateResponsescheduled = pushpad.notifications().create(newNotificationCreateParams()
.setBody("This notification will be sent after 60 seconds")
.setSendAt(sendAt));

You can also cancel a scheduled notification:

pushpad.notifications().cancel(scheduled.getId());

Getting subscription count

You can retrieve the number of subscriptions for a given project, optionally filtered by tags or uids:

longtotalCount = pushpad.subscriptions().count(newSubscriptionCountParams());
System.out.println(totalCount); // => 100totalCount = pushpad.subscriptions().count(newSubscriptionCountParams()
.setUids(List.of("user1")));
System.out.println(totalCount); // => 2totalCount = pushpad.subscriptions().count(newSubscriptionCountParams()
.setTags(List.of("sports")));
System.out.println(totalCount); // => 10totalCount = pushpad.subscriptions().count(newSubscriptionCountParams()
.setTags(List.of("sports && travel")));
System.out.println(totalCount); // => 5totalCount = pushpad.subscriptions().count(newSubscriptionCountParams()
.setUids(List.of("user1"))
.setTags(List.of("sports && travel")));
System.out.println(totalCount); // => 1

Getting push subscription data

You can retrieve the subscriptions for a given project, optionally filtered by tags or uids:

List<Subscription> subscriptions = pushpad.subscriptions().list(newSubscriptionListParams());
subscriptions = pushpad.subscriptions().list(newSubscriptionListParams()
.setUids(List.of("user1")));
subscriptions = pushpad.subscriptions().list(newSubscriptionListParams()
.setTags(List.of("sports")));
subscriptions = pushpad.subscriptions().list(newSubscriptionListParams()
.setTags(List.of("sports && travel")));
subscriptions = pushpad.subscriptions().list(newSubscriptionListParams()
.setUids(List.of("user1"))
.setTags(List.of("sports && travel")));

The REST API paginates the result set. You can pass page and perPage parameters to get the full list in multiple requests.

List<Subscription> subscriptions = pushpad.subscriptions().list(newSubscriptionListParams()
.setPage(2L));

You can also retrieve the data of a specific subscription if you already know its id:

pushpad.subscriptions().get(123);

Updating push subscription data

Usually you add data, like user IDs and tags, to the push subscriptions using the JavaScript SDK in the frontend.

However you can also update the subscription data from your server:

List<Subscription> subscriptions = pushpad.subscriptions().list(newSubscriptionListParams()
.setUids(List.of("user1")));
for (Subscriptionsubscription : subscriptions) {
// update the user ID associated to the push subscriptionpushpad.subscriptions().update(subscription.getId(), newSubscriptionUpdateParams()
.setUid("myuser1"));
// update the tags associated to the push subscriptionList<String> tags = newArrayList<>(subscription.getTags());
tags.add("another_tag");
pushpad.subscriptions().update(subscription.getId(), newSubscriptionUpdateParams()
.setTags(tags));
}

Importing push subscriptions

If you need to import some existing push subscriptions (from another service to Pushpad, or from your backups) or if you simply need to create some test data, you can use this method:

SubscriptioncreatedSubscription = pushpad.subscriptions().create(newSubscriptionCreateParams()
.setEndpoint("https://example.com/push/f7Q1Eyf7EyfAb1")
.setP256dh("BCQVDTlYWdl05lal3lG5SKr3VxTrEWpZErbkxWrzknHrIKFwihDoZpc_2sH6Sh08h-CacUYI-H8gW4jH-uMYZQ4=")
.setAuth("cdKMlhgVeSPzCXZ3V7FtgQ==")
.setUid("exampleUid")
.setTags(List.of("exampleTag1", "exampleTag2")));

Please note that this is not the standard way to collect subscriptions on Pushpad: usually you subscribe the users to the notifications using the JavaScript SDK in the frontend.

Deleting push subscriptions

Usually you unsubscribe a user from push notifications using the JavaScript SDK in the frontend (recommended).

However you can also delete the subscriptions using this library. Be careful, the subscriptions are permanently deleted!

pushpad.subscriptions().delete(id);

Managing projects

Projects are usually created manually from the Pushpad dashboard. However you can also create projects from code if you need advanced automation or if you manage many different domains.

ProjectcreatedProject = pushpad.projects().create(newProjectCreateParams()
// required attributes
.setSenderId(123L)
.setName("My project")
.setWebsite("https://example.com")
// optional configurations
.setIconUrl("https://example.com/icon.png")
.setBadgeUrl("https://example.com/badge.png")
.setNotificationsTtl(604800)
.setNotificationsRequireInteraction(false)
.setNotificationsSilent(false));

You can also find, update and delete projects:

List<Project> projects = pushpad.projects().list();
for (Projectproject : projects) {
System.out.printf("Project %d: %s%n", project.getId(), project.getName());
}
ProjectexistingProject = pushpad.projects().get(123);
ProjectupdatedProject = pushpad.projects().update(existingProject.getId(), newProjectUpdateParams()
.setName("The New Project Name"));
pushpad.projects().delete(existingProject.getId());

Managing senders

Senders are usually created manually from the Pushpad dashboard. However you can also create senders from code.

SendercreatedSender = pushpad.senders().create(newSenderCreateParams()
// required attributes
.setName("My sender")
// optional configurations// do not include these fields if you want to generate them automatically
.setVapidPrivateKey("-----BEGIN EC PRIVATE KEY----- ...")
.setVapidPublicKey("-----BEGIN PUBLIC KEY----- ..."));

You can also find, update and delete senders:

List<Sender> senders = pushpad.senders().list();
for (Sendersender : senders) {
System.out.printf("Sender %d: %s%n", sender.getId(), sender.getName());
}
SenderexistingSender = pushpad.senders().get(987);
SenderupdatedSender = pushpad.senders().update(existingSender.getId(), newSenderUpdateParams()
.setName("The New Sender Name"));
pushpad.senders().delete(existingSender.getId());

Error handling

API requests can return errors, described by an ApiException that exposes the HTTP status code and response body. Network issues and other errors return a generic PushpadException.

NotificationCreateParamsn = newNotificationCreateParams()
.setBody("Hello");
try {
pushpad.notifications().create(n);
} catch (ApiExceptione) { // HTTP error from the APISystem.out.println(e.getStatusCode() + " " + e.getBody());
} catch (PushpadExceptione) { // network error or other errorsSystem.out.println(e.getMessage());
}

Documentation

License

The library is available as open source under the terms of the MIT License.

About

Java library for sending push notifications from websites and web apps.

Topics

Resources

Stars

10 stars

Watchers

2 watching

Forks

Releases

Contributors

Languages