Quick Start Guide
Get up and running with OpenPushAPI in under 5 minutes.
Quick Start
OpenPushAPI lets you send push notifications to web, Android, and iOS users from one unified API. This guide walks you through setup in five steps.
Step 1 — Create an account and app
Create a free account at the console. Once logged in, create a new App. You'll receive two credentials:
app_key— Public key, used in your JavaScript SDK. Safe to embed in frontend code.app_secret— Private key, used for server-side API calls. Never expose this in client-side code.
Step 2 — Install the JavaScript SDK
Add these two lines to the <head> or end of <body> on every page of your website:
<!-- Add to your website -->
<script src="https://sdk.openpushapi.com/v1/sdk.js"></script>
<script>
OpenPush.init({
appKey: 'your-app-key-here',
autoPrompt: true,
promptDelay: 3000
});
</script>
Step 3 — Users opt in automatically
With autoPrompt: true, the SDK will show the browser's native push permission dialog to new visitors after promptDelay milliseconds. Once a user accepts, they're automatically registered as a subscriber in your dashboard.
Step 4 — Send your first notification
Use the REST API to send a push notification to all your subscribers:
curl -X POST https://api.openpushapi.com/v1/notifications \
-H "Content-Type: application/json" \
-H "X-App-Key: your-app-key" \
-H "X-App-Secret: your-app-secret" \
-d '{
"title": "Hello World!",
"body": "Your first push notification from OpenPushAPI.",
"url": "https://yoursite.com",
"target_type": "all"
}'
Response
{
"notification_id": 12345,
"status": "queued",
"total_recipients": 847,
"is_ab_test": false,
"message": "Notification queued successfully"
}
Step 5 — Check delivery stats
Check delivery status and click-through rates for any notification:
curl https://api.openpushapi.com/v1/stats/notifications/12345 \
-H "X-App-Key: your-app-key" \
-H "X-App-Secret: your-app-secret"
Authentication
OpenPushAPI uses two header-based credentials for authentication:
| Header | Usage | Where to find |
|---|---|---|
X-App-Key |
All requests (public & private) | Console → App → Settings |
X-App-Secret |
Server-side API requests only | Console → App → Settings |
SDK requests (subscriber registration from the browser) only need X-App-Key. The app key is safe to include in frontend JavaScript.
API requests (sending notifications, managing subscribers) require both headers. The X-App-Secret must never be exposed in frontend code — keep it server-side only.
Security notice: Treat X-App-Secret like a password. Rotate it immediately if you suspect it has been exposed. You can regenerate it from the console.
Your First Notification
Here's a more complete notification with all the commonly used fields:
{
"title": "New Feature: Dark Mode",
"body": "We've just launched dark mode. Update your settings to try it.",
"url": "https://yourapp.com/settings/appearance",
"icon_url": "https://yourapp.com/icons/feature-icon.png",
"image_url": "https://yourapp.com/images/dark-mode-preview.jpg",
"target_type": "tags",
"target_tags": {
"plan": "pro"
},
"target_platforms": ["web", "android"],
"actions": [
{ "title": "Try Dark Mode", "url": "https://yourapp.com/settings/appearance" },
{ "title": "Maybe Later" }
],
"ttl_seconds": 86400
}
Targeting options
target_type |
Description | Required field |
|---|---|---|
"all" |
Send to all active subscribers | — |
"segment" |
Send to a saved segment | target_segment_id |
"tags" |
Send to subscribers matching tags | target_tags |
"external_ids" |
Send to specific user IDs | target_ids |
"subscriber_ids" |
Send to specific subscriber IDs | target_ids |
"topic" |
Send to subscribers of a topic | target_topic_id |
Targeting is strict. Nothing silently falls back to "all": the API answers 422 when the field required by the target_type is missing or unusable — target_segment_id must be a segment of this app with usable rules, target_tags a non-empty object, target_ids a non-empty array (max 10,000; positive integers for subscriber_ids), target_topic_id a topic of this app. Sending a targeting field without the matching target_type (e.g. target_ids with the default "all") is also a 422.
SDK Installation
The OpenPushAPI JavaScript SDK handles Web Push subscription on your website. It registers a Service Worker, manages the subscription lifecycle, and handles all communication with our API.
/v1/).
Breaking changes will be released as /v2/ — existing /v1/ URLs remain stable indefinitely.
Current version: v1
Option 1 — CDN (recommended)
<!-- Core SDK -->
<script src="https://sdk.openpushapi.com/v1/sdk.js"></script>
| File | What it is |
|---|---|
sdk.js | The core Web SDK (readable source). Recommended for every site. |
sdk.min.js | Currently the same file as sdk.js (not minified) — kept so existing embeds keep working. Either URL is fine; serve it with gzip/brotli. |
sdk.full.js / sdk.full.min.js | The core SDK bundled with the optional modules (conversion tracking, geolocation, live activities, rich media, soft-prompt dialog), so they are not loaded on demand from /v1/modules/. No polyfills are included — the SDK needs a browser with Service Worker and Push API support. |
openpush-sw.js | The service worker. Must be served from your own domain root. |
Option 2 — Self-hosted
Download the SDK files and host them yourself. You'll also need to serve the Service Worker file (openpush-sw.js) from the root of your domain.
# Download SDK + Service Worker and place in your web root
curl -O https://sdk.openpushapi.com/v1/sdk.js
curl -O https://sdk.openpushapi.com/v1/openpush-sw.js
# Serve openpush-sw.js from https://yourdomain.com/openpush-sw.js
SDK Configuration
Pass a configuration object to OpenPush.init():
OpenPush.init({
appKey: 'your-app-key', // Required
autoPrompt: false, // Show permission prompt automatically
promptDelay: 3000, // Delay in ms before auto-prompt (if autoPrompt: true)
serviceWorkerUrl: '/openpush-sw.js', // Custom Service Worker path
softPrompt: { // Optional: show a custom UI before the browser dialog
title: 'Get notified',
body: 'Stay up to date with the latest news.',
acceptText: 'Yes, notify me',
denyText: 'No thanks',
icon: '/icon.png', // Optional icon URL
},
topics: ['news', 'deals'], // Auto-subscribe to these topics on registration
externalId: 'user_12345', // Optional: your user ID (see Identity verification)
externalIdAuth: '9f2c…', // Optional: hex HMAC-SHA256(externalId, app secret) from YOUR server
onSubscribe: function(subscriberId) {
console.log('Subscribed:', subscriberId);
},
onError: function(err) {
console.error('Push error:', err);
}
});
| Option | Type | Default | Description |
|---|---|---|---|
appKey |
string | — | Required. Your public app key. |
autoPrompt |
boolean | false |
Trigger the permission flow automatically on page load. |
promptDelay |
number | 0 |
Delay in ms before auto-prompt fires (requires autoPrompt: true). |
serviceWorkerUrl |
string | '/openpush-sw.js' |
Path to the Service Worker file. Must be served from your domain root. |
softPrompt |
object | null | null |
Show a custom UI card before the native browser permission dialog. Pass null to skip and go straight to the browser dialog. Fields: title, body, acceptText, denyText, icon. |
topics |
string[] | [] |
Topic slugs to subscribe to automatically on first registration. |
externalId |
string | null |
Your own user ID for this browser. Sent with the registration (or applied to the existing subscriber). |
externalIdAuth |
string | null |
Signature that proves externalId really belongs to the signed-in user: hex HMAC-SHA256 of the external ID with your app secret as the key, computed on your server. Required when the app's identity verification is required — see Identity verification. |
onSubscribe |
function | null |
Called with subscriberId after successful registration. |
onError |
function | null |
Called with an error object if subscription fails. |
SDK Methods
// Manually trigger the permission flow (shows softPrompt if configured)
await OpenPush.prompt();
// Set tags for the current subscriber
await OpenPush.setTags({ plan: 'pro', cohort: 'beta-users' });
// Remove specific tag keys
await OpenPush.removeTags(['cohort', 'source']);
// Set external ID (your own user ID) — pass the server-side signature as `auth`
// (required when identity verification is "required", see below)
await OpenPush.setExternalId('user_12345', { auth: signatureFromYourServer });
// Subscribe to topics
await OpenPush.subscribeToTopics(['breaking-news', 'deals']);
// Unsubscribe from topics
await OpenPush.unsubscribeFromTopics(['deals']);
// Get current subscribed topics
const topics = await OpenPush.getTopics();
// Check if user is subscribed
const subscribed = OpenPush.isSubscribed(); // synchronous, returns boolean
// Get current subscriber ID
const subscriberId = OpenPush.getSubscriberId(); // synchronous, returns string | null
// Unsubscribe the current user (removes from API + browser)
await OpenPush.unsubscribe();
// Contact data for e-mail / SMS fallback — needs a verified identity
await OpenPush.setEmail('jane@example.com', { auth: signatureFromYourServer });
await OpenPush.setPhone('+420601234567', { auth: signatureFromYourServer }); // E.164
// Location for geo-fence campaigns — the SDK never asks for geolocation itself
navigator.geolocation.getCurrentPosition(p =>
OpenPush.setLocation(p.coords.latitude, p.coords.longitude));
await OpenPush.setLocation(null, null); // clears the stored location
// Conversion event (revenue is recorded only from your server — see below)
OpenPush.trackConversion('purchase', { revenue: 49.0, currency: 'EUR' });
The setters (setExternalId, setEmail, setPhone, setLocation) never throw; they resolve with { ok, status, error?, message?, identityVerified? } and report errors through console.error and the onError init option. Registration is single-flight: autoPrompt, a button calling prompt() and a second init() share one registration, and setters called meanwhile wait for it — there is no need to sequence these calls yourself.
Conversions: trackConversion(eventName, { revenue, currency, metadata }) posts to /v1/conversions with the device token. Events sent from the browser are recorded without revenue (stored as 0) — the API accepts revenue only from server-side calls with the app secret or an AI token, so post revenue-bearing conversions from your backend. An invalid currency code is dropped (the API then defaults to USD).
Identity Verification (external ID)
The public app key identifies your app, not a user — anyone can copy it from your page. An external_id sent from the browser or a mobile app is therefore only a claim. Identity verification lets your server vouch for it, so nobody can register a device under another user's ID and receive that user's pushes.
How it works
- Your server computes
external_id_auth= hex HMAC-SHA256 of the external ID, with your app secret as the key, and hands it to the page or app together with the user ID (never send the secret itself). - The SDK sends it with the registration or the update:
OpenPush.init({ externalId, externalIdAuth })orOpenPush.setExternalId(id, { auth }); Flutter:OpenPushConfig(externalId: …, externalIdAuth: …)orOpenPushAPI.setExternalId(id, auth: …). Raw API calls put it in the request body as"external_id_auth"next to"external_id". - The same signature unlocks contact data: from the SDK,
emailandphone(used for e-mail/SMS fallback) are accepted only with a validexternal_id_authfor the subscriber's external ID, otherwise403 identity_verification_required— whatever the mode below. - The response contains
"identity_verified": true|false, so you can see whether the signature was accepted.
// PHP — on your server, for the signed-in user
$externalIdAuth = hash_hmac('sha256', (string)$user->id, getenv('OPENPUSH_APP_SECRET'));
// Node.js — on your server
const externalIdAuth = require('crypto')
.createHmac('sha256', process.env.OPENPUSH_APP_SECRET)
.update(String(user.id))
.digest('hex');
Modes (identity_verification app setting)
| Value | Behaviour for SDK calls (public app key) |
|---|---|
off / optional (default) | An external ID without a valid signature is accepted but stored only on the calling device's own subscriber row. It never merges with, takes over or deactivates another subscriber that has the same external ID. A valid signature makes it verified. |
required | A non-empty external ID without a valid external_id_auth is rejected with 403 {"error": "identity_verification_required"}. The Web SDK then registers the device without the ID (push still works) and reports the error through onError. |
Set the mode with PUT /v1/apps/{id} and {"identity_verification": "required"} (server-side call). Calls made with your app secret or an AI token are trusted and never need a signature — linking a user from your backend (PUT /v1/subscribers/{id} with {"external_id": "…"}) always works.
Flutter SDK — Installation
The openpushapi_flutter package has no mandatory Google/Firebase dependency. iOS uses Apple's native APNs directly. For Android, you provide the FCM token yourself — using whichever push client you prefer.
1. Download and add the SDK
The SDK is distributed as a ZIP (it is not published on pub.dev, so a version constraint such as ^1.2.0 will not resolve). The archive contains a single root folder named flutter/ — that folder is the package (it holds pubspec.yaml). Unzip it into your project and point a path dependency at it:
# from your Flutter project root
curl -O https://sdk.openpushapi.com/v1/openpushapi_flutter.zip
unzip -o openpushapi_flutter.zip -d packages/ # creates packages/flutter/pubspec.yaml
flutter pub get
# pubspec.yaml — local path dependency (the folder that contains the SDK's pubspec.yaml)
dependencies:
openpushapi_flutter:
path: ./packages/flutter
You may rename the folder (e.g. to packages/openpushapi_flutter) as long as path: points at it. To upgrade, unzip the new archive over the same folder and run flutter pub get. Check the installed version with OpenPushAPI.version.
2. iOS — enable Push Notifications capability
In Xcode: open Runner → Signing & Capabilities → click + Capability → add Push Notifications.
Then pick one way of getting the APNs device token (OpenPushConfig.manageApns):
manageApns: true(default) — the SDK requests permission and obtains the APNs token itself (through its internalflutter_apns_onlydependency — do not add or call that package yourself). No native code needed.manageApns: false— your app already obtains the APNs token natively (e.g. inAppDelegate.didRegisterForRemoteNotificationsWithDeviceToken) and passes it withOpenPushAPI.registerToken(token, platform: 'ios'). The SDK then makes no APNs call at all (no permission prompt, no token listener), so it never registers the device behind your app's back. Use this mode whenever you have native APNs code — running both would register through two paths.
3. Android — add your push provider (optional)
Android push requires FCM (Google). Add it only if you need Android support:
dependencies:
firebase_core: ^3.0.0
firebase_messaging: ^15.0.0
Follow the FlutterFire setup guide to add google-services.json to your Android project. This dependency lives in your app, not in the SDK.
Flutter SDK — Initialization
iOS: with the default manageApns: true the SDK requests APNs permission and registers the device token automatically. With manageApns: false call registerToken(token, platform: 'ios') from your native token callback.
Android: call registerToken() after obtaining the FCM token yourself.
import 'dart:io';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:openpushapi_flutter/openpushapi_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// iOS: APNs handled by the SDK (manageApns defaults to true)
await OpenPushAPI.init(
config: const OpenPushConfig(
appKey: 'YOUR_APP_KEY',
// manageApns: false, // only if YOUR native code obtains the APNs token
debug: true, // set false in production
),
);
// Android: provide FCM token yourself
if (!kIsWeb && Platform.isAndroid) {
// Uses firebase_messaging — add it to YOUR pubspec, not required by the SDK
// final token = await FirebaseMessaging.instance.getToken();
// if (token != null) {
// await OpenPushAPI.registerToken(token, platform: 'android');
// }
// FirebaseMessaging.instance.onTokenRefresh.listen((t) {
// OpenPushAPI.registerToken(t, platform: 'android');
// });
}
runApp(const MyApp());
}
OpenPushConfig options
| Option | Type | Default | Description |
|---|---|---|---|
appKey | String | — | Required. Your public app key. |
apiUrl | String | https://api.openpushapi.com/v1 | API base URL. Override for testing. |
autoRequestPermission | bool | true | Request notification permission on init (iOS, only with manageApns: true). |
manageApns | bool | true | iOS: true = the SDK obtains the APNs token itself; false = your app obtains it natively and passes it via registerToken(token, platform: 'ios'), and the SDK makes no APNs call. |
externalId / externalIdAuth | String? | null | Your user ID and its server-side signature (see Identity verification); sent with the registration and re-sent whenever the device registers again. |
onError | Function(Object)? | null | Receives errors the SDK cannot throw to you — e.g. a failed automatic iOS token registration or an identity rejected at registration. |
vapidKey | String? | null | Deprecated, ignored. Flutter Web is not active yet — use the JavaScript SDK on the web. |
debug | bool | false | Print SDK logs to console. |
Flutter SDK — API Reference
| Method | Description |
|---|---|
OpenPushAPI.init(config:) | Initialize the SDK. On iOS with manageApns: true (default) it also obtains and registers the APNs token. |
OpenPushAPI.registerToken(token, platform:) | Register a push token: Android FCM token ('android'), or the iOS APNs token ('ios') when manageApns: false. Registration is single-flight: repeated or concurrent calls (token refresh, several call sites) are serialized and a token being registered is never registered twice, so call it from every place that obtains a token. |
OpenPushAPI.setExternalId(id, auth: …) | Link subscriber to your own user ID (call after login). auth = the server-side signature from Identity verification. Returns identity_verified (null if the device is not registered yet — the ID then goes with the registration). Apps set to required reject an unsigned ID: it throws OpaApiException with isIdentityVerificationRequired. |
OpenPushAPI.setEmail(email, auth: …) / setPhone(phone, auth: …) | Contact data for e-mail/SMS fallback. Needs a verified identity (auth, or a prior setExternalId(id, auth: …)); phone in E.164 (spaces, dashes, dots and brackets are removed). Invalid values throw ArgumentError before any request; null clears. |
OpenPushAPI.setLocation(lat, lng) | Device location for geo-fence campaigns. The SDK never asks for the location permission itself; (null, null) clears it. |
OpenPushAPI.setTags(map) | Set or update segmentation tags. Merged server-side. Only keys on the app's SDK-writable tags list are accepted. |
OpenPushAPI.unsubscribe() | Delete subscriber from OpenPushAPI and clear local state. |
OpenPushAPI.trackClick(notifId) | Record a notification click. Not automatic — call it from your tap handler with the payload's notificationId as a String (see Click tracking in mobile apps). |
OpenPushAPI.subscriberId | Current subscriber ID, or null if not yet registered. |
OpenPushAPI.isInitialized | Whether SDK has been successfully initialized. |
// Link to your user after login
await OpenPushAPI.setExternalId(currentUser.id);
// Segment by plan and country
await OpenPushAPI.setTags({'plan': 'pro', 'country': 'US'});
// Unsubscribe on logout
await OpenPushAPI.unsubscribe();
// Read the subscriber ID
print(OpenPushAPI.subscriberId);
Flutter Web — Not active yet
Not active yet — use the JavaScript SDK on the web. On Flutter Web, OpenPushAPI.init() only prints OpenPushAPI.webUnsupportedMessage and every other call does nothing (no API request); OpenPushAPI.isSupported is false. OpenPushConfig.vapidKey is deprecated and ignored.
For a Flutter app compiled to the web, load the JavaScript SDK in web/index.html and serve openpush-sw.js from the root of your domain — it handles the whole browser subscription. The same Dart code can keep calling the Flutter SDK on all platforms; on the web those calls are no-ops.
<!-- web/index.html of your Flutter app -->
<script src="https://sdk.openpushapi.com/v1/sdk.js"></script>
<script>
OpenPush.init({ appKey: 'YOUR_APP_KEY' });
</script>
REST API — Authentication
The base URL for all API requests is https://api.openpushapi.com/v1. Requests with a body must send Content-Type: application/json. The API accepts three authentication modes:
| Mode | Headers | Used for |
|---|---|---|
| SDK | X-App-Key (+ X-Subscriber-Token for an existing subscriber) | Browsers and mobile apps: registering a device and managing that device only (tags, topics via /v1/subscribers/{id}/topics, in-app inbox, unsubscribe). |
| API | X-App-Key + X-App-Secret | Your server: sending notifications, reading data, managing apps, segments, topics, webhooks. |
| AI | Authorization: Bearer opa_ai_… | AI coding agents provisioning resources on the account owner's behalf. |
Include both headers in every server-side request:
curl https://api.openpushapi.com/v1/subscribers \
-H "X-App-Key: your-app-key" \
-H "X-App-Secret: your-app-secret"
Device token (SDK mode)
POST /v1/subscribers returns subscriber_id and a subscriber_token. Store both on the device; every later SDK call about that subscriber must send the token as X-Subscriber-Token, otherwise the API answers 403 subscriber_token_required (the official SDKs do this and re-register automatically). Endpoints that act on other subscribers or on the whole app — for example GET /v1/apps/{id}/health, GET /v1/apps/{id}/registration-attempts and POST/DELETE /v1/topics/{id}/subscribe — require API or AI mode and return 403 to the public key alone.
AI mode (Bearer tokens)
The account owner creates an AI access token (opa_usr_…) in the console under AI access. That master token can only be exchanged for a short-lived session key via POST /v1/ai/request-session-key; the session key (opa_ai_…, at most 7 days / 10,000 uses) is then sent as Authorization: Bearer opa_ai_… instead of X-App-Key/X-App-Secret. Each session key carries scopes — resource:create, resource:read, resource:update, resource:delete — and every route requires the matching scope (default-deny, 403 otherwise). For app-scoped resources (subscribers, notifications, segments, …) also send X-App-Key or include "app_id" in the JSON body. The full agent flow is documented for AI tools at forai.openpushapi.com (access key from the console).
Apps API
Manage your applications programmatically.
| Method | Endpoint | Description |
|---|---|---|
POST | /v1/apps | Create a new app |
GET | /v1/apps | List all apps |
GET | /v1/apps/{id} | Get app details |
PUT | /v1/apps/{id} | Update app settings (incl. identity_verification: off | optional | required) |
DELETE | /v1/apps/{id} | Delete an app |
GET | /v1/apps/{id}/health | Diagnostic snapshot (subscribers per platform, recent registrations, 24 h delivery stats, warnings). API or AI mode only. |
GET | /v1/apps/{id}/registration-attempts | Recent POST /v1/subscribers attempts incl. rejections (filters: platform, result, since). API or AI mode only — it contains end-user data. |
All Apps endpoints except GET /v1/apps/vapid-public-key require API or AI mode; the public app key alone gets 403.
Subscribers API
| Method | Endpoint | Description |
|---|---|---|
POST | /v1/subscribers | Register a subscriber (from SDK) |
GET | /v1/subscribers | List subscribers (filterable) |
GET | /v1/subscribers/{id} | Get subscriber details |
PUT | /v1/subscribers/{id} | Update subscriber (tags, external_id) |
DELETE | /v1/subscribers/{id} | Unsubscribe |
POST | /v1/subscribers/{id}/tags | Add tags |
DELETE | /v1/subscribers/{id}/tags | Remove tags |
GET | /v1/subscribers/{id}/topics | Topics of this subscriber |
POST | /v1/subscribers/{id}/topics | Subscribe this subscriber to topics — body {"topics": ["slug", …]} (used by the SDKs) |
DELETE | /v1/subscribers/{id}/topics | Unsubscribe from topics — same body |
From a browser or app (SDK mode) these calls need the device's X-Subscriber-Token; from your server use the app secret. In SDK mode an external_id is handled as described in Identity verification.
Subscriber fields and validation
| Field | Rules |
|---|---|
endpoint (web) | Must be an https URL (port 443, max 500 chars) of a browser push service: fcm.googleapis.com, updates.push.services.mozilla.com, web.push.apple.com, *.push.apple.com, *.notify.windows.com. Anything else → 422 endpoint_not_allowed. |
email, phone | Contact data for e-mail/SMS fallback. email: valid address, max 255 chars; phone: E.164, e.g. +420601234567 (otherwise 422); null or "" clears. From the SDK (public key) they are accepted only together with a valid external_id_auth for the subscriber's external_id — otherwise 403 identity_verification_required. Your server (app secret) can always set them. |
latitude, longitude | Numbers, sent together (−90…90, −180…180), otherwise 422; null for both clears. Used by geo-fence campaigns (only locations updated in the last 30 days count). |
tags | JSON object, max 50 keys, keys ≤ 64 chars, scalar values (strings ≤ 255 chars). From the SDK only keys on the app's SDK-writable tags list (Console → App settings) are accepted — on POST/PUT /v1/subscribers as well as /tags; other keys → 403 tag_key_not_writable_from_sdk with the denied and allowed keys. With an empty list the SDK cannot write tags at all; set them from your server instead. |
subscription_token | Required on registration, max 4096 chars. Rotating a subscriber (PUT or /reactivate) to a token that is already registered as another subscriber → 409 subscription_token_in_use — register it with POST /v1/subscribers instead. |
New SDK registrations are limited to 30 per hour per client IP and app (429 registration_rate_limited, Retry-After: 3600); devices that are already registered are not affected. Registrations beyond your plan's subscriber limit — counted across all your apps — get 429 with "scope": "account"; test apps get 403 test_app_limit above 100 active subscribers.
Filter subscribers
# Filter by platform
GET /v1/subscribers?platform=web
# Filter by active status
GET /v1/subscribers?is_active=1
# Filter by tag
GET /v1/subscribers?tags[plan]=pro
# Pagination
GET /v1/subscribers?limit=50&offset=100
Notifications API
| Method | Endpoint | Description |
|---|---|---|
POST | /v1/notifications | Send a notification |
GET | /v1/notifications | List notifications |
GET | /v1/notifications/{id} | Get notification + stats |
POST | /v1/notifications/{id}/cancel | Cancel a scheduled notification |
Full notification payload
{
"title": "Hi {{first_name}}, Flash Sale — 24 hours only!",
"body": "50% off all Pro plans. Offer ends tonight.",
"url": "https://yourapp.com/sale",
"icon_url": "https://yourapp.com/icons/sale.png",
"image_url": "https://yourapp.com/images/sale-banner.jpg",
"badge_url": "https://yourapp.com/icons/badge.png",
"target_type": "segment",
"target_segment_id": 42,
"target_platforms": ["web", "android", "ios"],
"target_countries": ["US", "GB", "DE"],
"geo_fence_id": null,
"channels": "push",
"actions": [
{ "title": "Claim Offer", "url": "https://yourapp.com/sale" },
{ "title": "Remind Me Later" }
],
"ttl_seconds": 43200,
"send_at": "2026-04-24T09:00:00Z",
"timezone_delivery": true,
"send_time_optimized": false,
"is_ab_test": false
}
Idempotency-Key (safe retries)
Send an Idempotency-Key header with POST /v1/notifications so a retried request (timeout, network error) never creates a second campaign:
curl -X POST https://api.openpushapi.com/v1/notifications \
-H "Content-Type: application/json" \
-H "X-App-Key: your-app-key" \
-H "X-App-Secret: your-app-secret" \
-H "Idempotency-Key: order-1234-shipped" \
-d '{"title": "Your order shipped", "body": "Track it in the app.", "target_type": "external_ids", "target_ids": ["user_42"]}'
- 8–128 characters from
A–Z a–z 0–9 . _ : -(otherwise422); keys are per app and kept for 24 hours. - Same key + same body again →
200with the originalnotification_id, its currentstatusand"idempotent_replay": true. No new notification is created and no recipients are counted again (the call itself still counts as an API call). - Same key + a different body →
409. A second identical request while the first is still being processed →409(retry a moment later).
Delivery channels
channels decides where a campaign goes: push (default), push_inapp (push and a copy in the subscriber's in-app inbox) or inapp (inbox only — no push is sent). The inbox is what the notification center widget and GET /v1/inapp show. Any other value returns 422.
Segments API
| Method | Endpoint | Description |
|---|---|---|
POST | /v1/segments | Create a segment |
GET | /v1/segments | List segments |
PUT | /v1/segments/{id} | Update segment rules |
DELETE | /v1/segments/{id} | Delete segment |
GET | /v1/segments/{id}/count | Count matching subscribers |
// Create a segment: Pro users in the US on web
{
"name": "Pro Web US",
"rules": {
"platform": "web",
"country_code": "US",
"tags.plan": "pro"
}
}
Topics API
Topics are named channels subscribers opt into (news, deals, …). Send to a topic with "target_type": "topic", "target_topic_id": 5. All /v1/topics routes are server-side (API or AI mode):
| Method | Endpoint | Description |
|---|---|---|
POST | /v1/topics | Create a topic (name, optional slug, description) |
GET | /v1/topics | List topics |
GET / PUT / DELETE | /v1/topics/{id} | Read, update or delete a topic |
POST / DELETE | /v1/topics/{id}/subscribe | Add / remove a subscriber — body {"subscriber_id": 98765}. API or AI mode only (403 with the public key). |
GET | /v1/topics/{id}/subscribers | List subscribers of a topic |
Browsers and apps manage their own topics through /v1/subscribers/{id}/topics with X-Subscriber-Token — that is what OpenPush.subscribeToTopics() / unsubscribeFromTopics() use.
Stats API
| Method | Endpoint | Description |
|---|---|---|
GET | /v1/stats/overview | Overall subscriber & delivery stats |
GET | /v1/stats/notifications/{id} | Per-notification stats |
How metrics are defined
These definitions are the contract behind every number in the console and the Stats API (metrics contract v1, 2026-09).
| Metric | Definition |
|---|---|
total_recipients | Devices targeted by the campaign after segment, tag, topic, platform, quiet-hours and frequency-cap filters. For A/B tests: the test sample only; the holdout is counted on the winner ("W") notification. |
delivered | The push provider (browser push service, FCM, APNs) accepted the message. This does not prove it was displayed on the device. |
failed | The provider rejected the message permanently (invalid token, missing credentials, 4xx other than 429). Transient errors (429, 5xx, network) are retried and are not counted as failed until retries are exhausted. |
expired | Subscription no longer exists (410/404) — the subscriber is unsubscribed automatically. |
clicked | Unique clicks: at most one per subscriber per notification. Clicks that cannot be tied to a subscriber are counted at most once per notification per client address per 24 h. |
| CTR | clicked / delivered (provider-accepted deliveries), not clicked / total_recipients. |
| Conversions | Events posted to /v1/conversions. Revenue is only accepted from your server (app secret / AI token) and is reported per currency — amounts in different currencies are never summed. |
| A/B winner | Higher CTR after a 4 h window with at least 100 provider-accepted deliveries per variant. A two-proportion z-score is recorded (ab_winner_z; |z| ≥ 1.96 ≈ 95 % confidence). The winner is then sent to the holdout. |
Tracking API
Use the tracking endpoint to record notification click events from mobile apps and custom integrations. On the web the SDK's service worker (openpush-sw.js) reports clicks automatically. Mobile apps must report taps themselves — the Flutter SDK does not track clicks automatically; call OpenPushAPI.trackClick(notificationId) from your notification tap handler (example below).
| Method | Endpoint | Description |
|---|---|---|
POST | /v1/track/click | Record a notification click |
curl -X POST https://api.openpushapi.com/v1/track/click \
-H "Content-Type: application/json" \
-H "X-App-Key: your-app-key" \
-d '{
"notification_id": "12345",
"subscriber_id": "98765"
}'
Authentication: the public X-App-Key is enough to record a click, but a click is attributed to subscriber_id only with that device's X-Subscriber-Token (or from your server with the app secret). Without a valid token the click is counted anonymously — once per notification and client IP per 24 h, not attributed to the subscriber, and not counted at all for A/B test variants. The web service worker sends the token automatically.
The click is deduplicated per subscriber — calling this endpoint multiple times for the same subscriber and notification only increments the counter once. A click is attributed to a subscriber only if that subscriber actually received the push. An unknown or foreign notification_id still returns 200 {"status":"ok"} and counts nothing, so a wrong payload key shows up as "clicks stay at 0", not as an error.
Where the notification ID is in the push
| Platform | Location | Key | Type |
|---|---|---|---|
| Web Push | JSON payload read by openpush-sw.js (stored as notification.data.notificationId) | notificationId | number |
| Android (FCM) | message.data (Flutter: RemoteMessage.data) | notificationId | string |
| iOS (APNs) | top level of the payload next to aps (= top level of userInfo) | notificationId | number |
Every push also carries url (empty string if the campaign has none). No other custom keys are delivered.
Click tracking in mobile apps
// Flutter (Android, firebase_messaging) — call after OpenPushAPI.init(...)
Future<void> trackTap(Map<String, dynamic> data) async {
final id = data['notificationId']; // string on Android, number on iOS
if (id != null) await OpenPushAPI.trackClick(id.toString());
}
// App in background → opened by a tap
FirebaseMessaging.onMessageOpenedApp.listen((m) => trackTap(m.data));
// App launched from a terminated state by a tap
final initial = await FirebaseMessaging.instance.getInitialMessage();
if (initial != null) await trackTap(initial.data);
// iOS: forward userInfo["notificationId"] from your
// UNUserNotificationCenter didReceive(response) handler the same way.
trackClick does nothing until the device is registered (OpenPushAPI.subscriberId != null). Verify with GET /v1/notifications/{id} → clicked. trackClick is best effort (never throws) and sends the device's X-Subscriber-Token, so the click is attributed to the subscriber. Apps still on SDK 1.2.1 send no token — their clicks are counted anonymously; upgrade to 1.2.2.
Webhooks
Webhooks let OpenPushAPI post delivery events to your server shortly after each delivery batch. You can use them to sync delivery stats, trigger workflows, or log events.
| Method | Endpoint | Description |
|---|---|---|
POST | /v1/webhooks | Register a webhook endpoint |
GET | /v1/webhooks | List registered webhooks |
PUT | /v1/webhooks/{id} | Update a webhook |
DELETE | /v1/webhooks/{id} | Delete a webhook |
Registering a webhook
curl -X POST https://api.openpushapi.com/v1/webhooks \
-H "Content-Type: application/json" \
-H "X-App-Key: your-app-key" \
-H "X-App-Secret: your-app-secret" \
-d '{
"url": "https://yourserver.com/hooks/push",
"events": ["delivered", "failed"],
"is_active": true
}'
Webhook secret
- Omit
secretand one is generated (32 hex characters). Or pass your own: 16–64 printable ASCII characters (otherwise422). - The plain secret is returned only once — in the
201response ofPOST /v1/webhooksand in the response of thePUTthat changes it. Store it then;GETresponses show only a masked hint such as"secret": "••••abcd". - Rotate with
PUT /v1/webhooks/{id}and{"secret": ""}(new generated secret) or{"secret": "your-new-secret"}. The old secret stops working immediately, so update your receiver at the same time. - Secrets are stored encrypted.
POST /v1/webhooks/{id}/testsends a signed test ping ("event": "test").
Available events
| Event | Triggered when |
|---|---|
delivered | The push service (browser push service, FCM, APNs) accepted messages for one or more devices |
failed | Delivery failed permanently (invalid token, missing credentials, …) — includes error_code and error_message |
clicked, subscribed, unsubscribed | Accepted when registering a webhook, but not emitted yet. Use the Stats API for clicks. |
Webhook payload
One request per event type per delivery batch; deliveries lists the devices in that batch.
{
"event": "failed",
"notification_id": 12345,
"app_id": 7,
"timestamp": "2026-11-02T10:23:11.000Z",
"deliveries": [
{ "subscriber_id": 98765, "platform": "ios", "error_code": "BadDeviceToken", "error_message": "..." }
]
}
Signature verification (v2)
Every webhook request carries these headers:
| Header | Value |
|---|---|
X-OpenPush-Event | Event type, e.g. delivered |
X-OpenPush-Timestamp | Unix time in seconds when the request was signed |
X-OpenPush-Delivery | UUID of this delivery — the same value on every retry; use it to de-duplicate |
X-OpenPush-Signature | sha256= followed by the hex HMAC-SHA256 of <timestamp>.<raw body>, keyed with your webhook secret |
To verify: read the raw request body (before any JSON parsing), compute the HMAC over the timestamp, a dot and the body, compare in constant time, and reject requests whose timestamp is more than 300 seconds away from your clock (replay protection). Then skip deliveries whose X-OpenPush-Delivery you have already processed.
<?php
// PHP
$secret = getenv('OPENPUSH_WEBHOOK_SECRET');
$raw = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_OPENPUSH_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_OPENPUSH_SIGNATURE'] ?? '';
if (!ctype_digit($timestamp) || abs(time() - (int)$timestamp) > 300) {
http_response_code(400); exit; // stale or missing timestamp
}
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $raw, $secret);
if (!hash_equals($expected, $signature)) {
http_response_code(401); exit;
}
$deliveryId = $_SERVER['HTTP_X_OPENPUSH_DELIVERY'] ?? '';
// if ($deliveryId was already processed) { http_response_code(200); exit; }
$event = json_decode($raw, true);
// Node.js (Express) — keep the raw body for the signature
const crypto = require('crypto');
const express = require('express');
const app = express();
app.post('/hooks/push', express.raw({ type: 'application/json' }), (req, res) => {
const ts = req.get('X-OpenPush-Timestamp') || '';
const sig = req.get('X-OpenPush-Signature') || '';
if (!/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return res.sendStatus(400);
const expected = 'sha256=' + crypto.createHmac('sha256', process.env.OPENPUSH_WEBHOOK_SECRET)
.update(ts + '.').update(req.body).digest('hex');
const a = Buffer.from(expected), b = Buffer.from(sig);
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return res.sendStatus(401);
const deliveryId = req.get('X-OpenPush-Delivery'); // de-duplicate on this
const event = JSON.parse(req.body.toString('utf8'));
res.sendStatus(200);
});
Answer with any 2xx status within 5 seconds. Failed deliveries are retried (up to 5 attempts) with the same X-OpenPush-Delivery value.
Error Handling
All error responses follow a consistent JSON format:
{
"error": "Subscriber not found"
}
HTTP status codes
| Code | Meaning |
|---|---|
200 | OK — request succeeded |
201 | Created — resource created successfully |
204 | No Content — deleted successfully |
400 | Bad Request — missing or invalid parameters |
401 | Unauthorized — missing or invalid X-App-Key / X-App-Secret |
403 | Forbidden — action not allowed: endpoint needs the app secret, plan feature not available, subscriber_token_required, identity_verification_required, tag_key_not_writable_from_sdk, test_app_limit (test app at 100 active subscribers) |
404 | Not Found — resource does not exist |
409 | Conflict — Idempotency-Key reused with a different body; subscription_token_in_use (rotating a subscriber to a token another subscriber already has) |
415 | Unsupported Media Type — a request body without Content-Type: application/json |
422 | Unprocessable Entity — validation failed (incl. missing targeting data, endpoint_not_allowed, invalid email/phone/location) |
429 | Too Many Requests — per-minute rate limit, monthly_api_quota_exceeded, registration_rate_limited (30 new SDK registrations per hour per IP and app), subscriber limit reached ("scope": "account"), test_app_limit (monthly test-app recipients) |
500 | Internal Server Error — contact support if this persists |
Rate limits
Requests are rate-limited per app per minute (fixed 60-second windows; the allowance depends on the plan). The current state is returned in response headers; on 429 wait until X-RateLimit-Reset:
| Header | Description |
|---|---|
X-RateLimit-Limit | Maximum requests per minute |
X-RateLimit-Remaining | Requests remaining in current window |
X-RateLimit-Reset | Unix timestamp when the window resets |
Quotas & test apps
Server-side calls (X-App-Secret or an AI token) count towards your plan's monthly API call quota, shared by all apps you own. SDK calls from browsers and devices (public app key only) do not count. Every counted response carries:
| Header | Meaning |
|---|---|
X-Quota-Limit | Calls allowed this month (unlimited on Enterprise, test-app for test apps) |
X-Quota-Used | Calls used this month, including this one |
X-Quota-Reset | Unix time when the quota resets (1st day of next month, UTC) |
Over the limit the API answers 429 with "error": "monthly_api_quota_exceeded", the limit, used, reset and an upgrade_url. The per-minute rate limit (see Rate limits) is separate.
Test apps
Mark an app as a test app in App settings → General. Test apps are meant for development and staging: their API calls, subscribers and notifications are not counted towards your plan limits or usage, and they carry a Test badge in the console. Instead they have small fixed caps: at most 3 test apps per account, 100 active subscribers per test app (403 test_app_limit on registration) and 1,000 recipients per test app per calendar month (429 test_app_limit). Don't use a test app for production traffic.
Device token (SDK)
Since Web SDK 1.2.0, registration returns a subscriber_token that proves the browser owns its subscriber record. Every later SDK call about that subscriber (update, tags, topics, in-app inbox, conversions) must send it as X-Subscriber-Token; without it the API returns 403 subscriber_token_required and the SDK registers again automatically. Server-side calls with your app secret don't need it.
Personalization
Use {{variable}} placeholders in the title, body, or url of any notification. Each subscriber receives their own version with the placeholders replaced.
Supported variables
| Variable | Source |
|---|---|
{{first_name}} | Subscriber's first_name field |
{{last_name}} | Subscriber's last_name field |
{{external_id}} | Your own user ID linked to this subscriber |
{{platform}} | web, android, or ios |
{{country}} | 2-letter country code (US, DE, …) |
{{city}} | Subscriber's city |
{{language}} | Subscriber's browser/device language |
{{tags.KEY}} | Any tag value — e.g. {{tags.plan}} |
Missing or unknown variables are silently replaced with an empty string.
{
"title": "Hey {{first_name}}, your {{tags.plan}} trial ends soon!",
"body": "Upgrade today and keep all your {{tags.plan}} features.",
"url": "https://yourapp.com/upgrade?ref={{external_id}}",
"target_type": "all"
}
Personalization works on all platforms — Web Push, Android (FCM), and iOS (APNs). The substitution happens in the delivery engine, so your original notification record stores the template, not the resolved text.
A/B Testing
Test two notification variants against each other. Subscribers are randomly split according to the ab_split_percent you specify. The winner (highest CTR) is automatically selected after both variants have been delivered for at least 4 hours and each has reached 100+ deliveries.
Sending an A/B test
Set is_ab_test: true and include the variant B fields in the payload:
{
"title": "New Feature Available",
"body": "We just launched something you'll love.",
"url": "https://yourapp.com/new",
"target_type": "all",
"is_ab_test": true,
"ab_split_percent": 50,
"title_b": "You're going to love this",
"body_b": "Check out the latest update — it's live now."
}
A/B test fields
| Field | Type | Description |
|---|---|---|
is_ab_test | boolean | Enable A/B split for this notification |
ab_split_percent | integer | % of the test sample that receives variant A (10–90, default 50) |
ab_test_pct | integer | % of the audience used as the test sample (5–100, default 20). The remaining subscribers are the holdout and receive the winning variant automatically after 4 hours. 100 = plain split test without a winner send. |
title_b | string | Title for variant B |
body_b | string | Body text for variant B |
Variants A and B share the same targeting, URL, icon, schedule, and TTL. Stats for both variants appear side by side in the console notification detail page.
A/B testing requires the Pro plan or higher.
Geo-targeting
Restrict delivery to subscribers in specific countries using the target_countries field. Pass an array of ISO 3166-1 alpha-2 country codes.
{
"title": "Black Friday — US & Canada only",
"body": "Exclusive deal available in your region.",
"url": "https://yourapp.com/black-friday",
"target_type": "all",
"target_countries": ["US", "CA"]
}
Geo-targeting can be combined with any target_type — it acts as an additional filter on top of segment, tag, or ID targeting. If target_countries is omitted or empty, the notification is delivered to all countries.
Country codes are matched against the country_code field on the subscriber, which is automatically detected from the subscriber's IP address at registration time.
Geo-fences (Pro plan and higher)
To reach subscribers inside a circle on the map, create a geo-fence in the console (Geo-fences) and pass its ID as geo_fence_id. Like target_countries it filters on top of any target_type. Only subscribers that sent latitude/longitude (see Subscribers) within the last 30 days and lie inside the fence receive it. An ID that is not an active geo-fence of this app → 422; plans without geo-fences → 403.
{
"title": "Flash sale in our Prague store",
"body": "Today only — 20 % off.",
"target_type": "all",
"geo_fence_id": 3
}
Smart Send Time
When send_time_optimized: true, the delivery engine sends the notification to each subscriber at their personal optimal hour — the time of day when that subscriber has historically clicked push notifications most often.
{
"title": "Weekly digest is ready",
"body": "Here's what happened this week.",
"target_type": "all",
"send_time_optimized": true
}
The preferred hour per subscriber is computed nightly from their delivery and click history. Subscribers without enough history receive the notification immediately.
How it works: The engine delivers only to subscribers whose preferred_hour matches the current local hour (±1). Subscribers not yet in their window are skipped in the current run and picked up in subsequent runs. Subscribers without a recorded preferred hour receive the notification immediately.
In-App Notification Bell
The notification center widget adds a bell icon to your web app that shows a dropdown inbox of the subscriber's in-app messages (campaigns sent with channels push_inapp or inapp).
Works only in a browser that registered through the Web SDK. The inbox belongs to a subscriber (a device), and the API returns it only with that device's token (X-Subscriber-Token), which sdk.js stores when the browser subscribes. Load sdk.js and call OpenPush.init() first — the widget then picks up the subscriber ID and token automatically. A different browser of the same user has its own (separate) inbox. To show an inbox elsewhere, fetch it from your server with the app secret and render it yourself.
Installation
<!-- Add a target element where the bell should appear -->
<div id="openpush-center"></div>
<!-- The Web SDK registers this browser and keeps its device token -->
<script src="https://sdk.openpushapi.com/v1/sdk.js"></script>
<script src="https://sdk.openpushapi.com/v1/notification-center.js"></script>
<script>
OpenPush.init({ appKey: 'your-app-key' });
// Mount the bell once this browser is registered
if (OpenPush.getSubscriberId()) {
OpenPushCenter.init({
appKey: 'your-app-key',
targetSelector: '#openpush-center', // where to mount the bell
maxItems: 20, // max notifications to show
// subscriberId / subscriberToken default to this browser's registration
});
}
</script>
In-App API endpoints
| Method | Endpoint | Description |
|---|---|---|
GET | /v1/inapp?subscriber_id={id} | List unread in-app notifications (SDK: needs X-Subscriber-Token) |
PUT | /v1/inapp/{id}/read | Mark single notification as read (SDK: needs X-Subscriber-Token of the owning device) |
POST | /v1/inapp/read-all | Mark all as read for a subscriber (SDK: needs X-Subscriber-Token) |
# Fetch unread in-app notifications (from the device: app key + its device token)
curl "https://api.openpushapi.com/v1/inapp?subscriber_id=98765&limit=20" \
-H "X-App-Key: your-app-key" \
-H "X-Subscriber-Token: subscriber-token-from-registration"
# Mark all as read
curl -X POST https://api.openpushapi.com/v1/inapp/read-all \
-H "Content-Type: application/json" \
-H "X-App-Key: your-app-key" \
-H "X-Subscriber-Token: subscriber-token-from-registration" \
-d '{"subscriber_id": 98765}'
# From your server instead: X-App-Key + X-App-Secret (no device token needed)
Without a valid X-Subscriber-Token a public-key request gets 403 subscriber_token_required. The widget is not real-time: it loads the inbox when the page opens and then polls every 60 seconds, so a new message can take up to a minute to appear (or a page reload).
Automation (Journeys)
Journeys let you build multi-step automated notification sequences triggered by subscriber events. For example: send a welcome push immediately after signup, wait 3 days, then send a follow-up only if the subscriber hasn't clicked anything.
Journey triggers
| Trigger | When it fires |
|---|---|
subscriber_created | A new subscriber registers |
tag_added | A specific tag is added to a subscriber |
segment_enter | A subscriber enters a segment |
event | A custom event is tracked via the API |
manual | Manually enrolled via the console or API |
Step types
| Type | Description |
|---|---|
send_push | Send a push notification |
wait | Pause for N minutes / hours / days |
condition | Branch based on subscriber field value |
ab_split | Randomly split enrollment into A/B paths |
Journeys are configured and managed from the console at Automation → Journeys. The engine processes active journey enrollments every minute.
Console only: Journeys are currently managed exclusively from the console builder at Automation → Journeys. REST API support for journeys is coming soon.
Unsubscribe Reason Tracking
When a subscriber opts out, you can capture why they unsubscribed. This data appears in the Analytics section of the console and helps you improve retention.
Passing a reason
Include a reason field when calling the unsubscribe endpoint:
curl -X DELETE https://api.openpushapi.com/v1/subscribers/98765 \
-H "Content-Type: application/json" \
-H "X-App-Key: your-app-key" \
-H "X-Subscriber-Token: subscriber-token-from-registration" \
-d '{"reason": "too_many"}'
# (or from your server with X-App-Secret instead of X-Subscriber-Token)
Valid reason values
| Value | Meaning |
|---|---|
too_many | Receiving too many notifications |
not_relevant | Notifications are not relevant |
never_signed_up | Subscriber didn't intentionally opt in |
other | Other / not specified |
The Web SDK can also show a built-in reason dialog before unsubscribing:
// Show reason dialog, then unsubscribe
await OpenPush.unsubscribe({ showReasonDialog: true });
// Or unsubscribe with a known reason directly
await OpenPush.unsubscribe({ reason: 'too_many' });
Web Push (VAPID)
Web Push uses the VAPID (Voluntary Application Server Identification) protocol. OpenPushAPI automatically generates VAPID keys for each app — you don't need to manage them yourself.
Browser support: Chrome 50+, Firefox 44+, Edge 17+, Safari 16+ (macOS Ventura), Opera 42+.
The SDK registers a Service Worker in the browser, which handles incoming push messages even when the page is closed. It is the same openpush-sw.js file for every app (it reads your app's settings from the SDK at runtime) — download it once and serve it from your domain root; re-download it when the changelog announces a new version.
Custom Service Worker integration
If you already have a Service Worker, you can import ours from within it:
// your-service-worker.js
importScripts('https://sdk.openpushapi.com/v1/openpush-sw.js');
// Your existing SW code below...
self.addEventListener('fetch', (event) => {
// ...
});
Android — Firebase Cloud Messaging (FCM)
To send push notifications to Android apps, you need to configure FCM credentials in your OpenPushAPI app settings.
- Create a Firebase project at console.firebase.google.com
- Go to Project Settings → Cloud Messaging and copy your Server Key and Project ID
- In OpenPushAPI console, navigate to your App → Platform Settings → Android and enter the credentials
- In your Android app, use the Firebase SDK to get the FCM registration token and register it via our API
// Android — Register FCM token with OpenPushAPI
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
val token = task.result
// Register with OpenPushAPI
val client = OkHttpClient()
val body = JSONObject().apply {
put("platform", "android")
put("subscription_token", token)
}.toString()
val request = Request.Builder()
.url("https://api.openpushapi.com/v1/subscribers")
.addHeader("X-App-Key", "your-app-key")
.post(body.toRequestBody("application/json".toMediaType()))
.build()
client.newCall(request).enqueue(...)
}
The response contains subscriber_id and subscriber_token. Store both on the device and send the token as X-Subscriber-Token on every later call for this subscriber (update, tags, topics, unsubscribe). Report taps with POST /v1/track/click using the notificationId from message.data (see Tracking).
iOS — Apple Push Notification Service (APNs)
To send push notifications to iOS apps, you need an APNs .p8 key from your Apple Developer account. The key file is uploaded directly in the console — no server-side configuration needed.
Step 1 — Get your APNs key from Apple
- Log in to developer.apple.com
- Navigate to Certificates, Identifiers & Profiles → Keys
- Click + to create a new key, enable Apple Push Notifications service (APNs)
- Download the
.p8file — you can only download it once - Note your Key ID (10 characters) and Team ID (found under Membership)
Step 2 — Upload in OpenPushAPI Console
- Go to Console → Apps → select your app → Platform Settings → iOS (APNs)
- Fill in Key ID, Team ID, and Bundle ID (e.g.
com.yourcompany.yourapp) - Click Choose file, select your
.p8file, and click Save APNs Settings - A green checkmark confirms the key is stored. You can replace it at any time by uploading a new file, or remove it with the Remove checkbox.
.p8 key file is stored securely on the server and is never exposed via the API. It cannot be set through the REST API — only through the Console UI.
// iOS — Register APNs token with OpenPushAPI
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
// Register with OpenPushAPI
var request = URLRequest(url: URL(string: "https://api.openpushapi.com/v1/subscribers")!)
request.httpMethod = "POST"
request.setValue("your-app-key", forHTTPHeaderField: "X-App-Key")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"platform": "ios",
"subscription_token": token
])
URLSession.shared.dataTask(with: request).resume()
}
As on Android, keep subscriber_id and subscriber_token from the response and send X-Subscriber-Token on later calls. The notification ID for click tracking is the top-level notificationId key of userInfo (a number).
Migrate from OneSignal
Browsers grant notification permission to your site, not to a push provider. Visitors who allowed notifications for OneSignal have already allowed them for you — after the switch the SDK re-subscribes them without showing a new prompt the next time they visit. You can also bring your existing subscriber list along so nobody is lost in between.
1. Create the app and choose your keys
- Create an app in the console and add your site's origin to Allowed origins.
- If you have your own VAPID key pair (you generated it yourself or your provider let you export it), open App settings → Web Push and paste the private key. The public key is derived and checked automatically. Existing subscriptions made with that key keep working — import them in step 3 and you can send to them straight away.
- If you don't have the private key (the usual case with OneSignal-managed keys), keep the keys OpenPushAPI generated. Old subscriptions can't be reused with a new key, but the SDK replaces them automatically on each visitor's next visit (step 2).
One cut-over, no parallel sending. A browser can only have one push service worker per scope. As soon as openpush-sw.js replaces the OneSignal worker (step 2), OneSignal pushes to your site no longer display correctly — and if you imported the key pair, both providers would push to the same subscriptions. So prepare your server code first (step 4), then deploy step 2 and switch your server to OpenPushAPI in the same release, and stop sending from OneSignal from that moment on.
2. Swap the SDK and the service worker
Remove the OneSignal script and init code, delete OneSignalSDKWorker.js (or make it an empty file for a while so browsers that still request it get a valid response), and add OpenPushAPI:
<script src="https://sdk.openpushapi.com/v1/sdk.js"></script>
<script>
OpenPush.init({ appKey: 'YOUR_APP_KEY' });
// Visitors who already allowed notifications (e.g. via OneSignal) are
// re-subscribed silently — no permission prompt is shown to them.
if ('Notification' in window && Notification.permission === 'granted') {
OpenPush.prompt();
}
</script>
Serve /openpush-sw.js from your site root (see Installation). Registering it at the same scope replaces the OneSignal worker. Web SDK 1.2.1+ removes a leftover subscription that was made with a different key before subscribing again.
3. Import your subscribers (optional)
In OneSignal, export your subscribers as CSV and upload the file unchanged under Import / Export. The importer recognises OneSignal's column names:
| OneSignal column | OpenPushAPI field |
|---|---|
identifier | push endpoint |
web_p256, web_auth | subscription keys |
external_user_id | external_id |
language, tags | same |
invalid_identifier = true | row is skipped |
Imported subscribers keep their external_id and tags, so your segments and server-side targeting by user ID keep working. Duplicates (same endpoint) are skipped and your plan's subscriber limit applies.
Import only if you imported the key pair in step 1. A subscription only works with the key it was created with; without OneSignal's private key the imported web subscribers would just fail on every send. In that case skip the import — each returning visitor is re-subscribed by the SDK (step 2), and your site sets their external ID again when they sign in (OpenPush.setExternalId(userId, { auth }) — see Identity verification).
4. Update your server code (deploy together with step 2)
| OneSignal | OpenPushAPI |
|---|---|
POST /notifications with include_aliases.external_id | POST /v1/notifications with "target_type": "external_ids", "target_ids": [...] |
included_segments: ["Subscribed Users"] | "target_type": "all" |
filters on tags | "target_type": "tags", "target_tags": {...} or a segment |
headings / contents / url | title / body / url |
| REST API key | X-App-Key + X-App-Secret headers (server-side only) |
5. Check it
Before the cut-over, use Test in your browser on a staging copy of your site to confirm the keys and delivery work. After it, watch the subscriber count grow as visitors return. Do not send web pushes from OneSignal any more — keep the OneSignal account only until you have exported what you need. Native mobile apps are separate: they keep receiving OneSignal pushes until you ship an app release with the OpenPushAPI SDK, so switch their sending per app release, not per website deploy.
Test in your browser
App settings → Web Push → Test in this browser subscribes the browser you are using as a test subscriber of the app and sends it one real push through the delivery engine. It shows each step — permission, subscription, queued, accepted by the push service, shown, clicked — and the push service's error message if something fails (for example a mismatched VAPID key). It needs the send permission on the app and is limited to 20 tests per hour.