Capacitor (Ionic) SDK
@pushizo/capacitor — a Capacitor 6/7 plugin wrapping the native Android and iOS SDKs; delegates to @pushizo/web on the web. Push, in-app, notification inbox, preferences.
@pushizo/capacitor wraps the native Pushizo Android (com.pushizo:pushizo-android) and iOS (Pushizo pod / SPM) SDKs; on the web platform it delegates to the Web SDK (@pushizo/web). The queue, sessions, delivery feedback, trigger evaluation and in-app rendering live on the native side. The surface is the same as the legacy provider's v5 and the Cordova plugin. Example: examples/ionic-capacitor.
- Capacitor 6 and 7, Android minSdk 23, iOS 15+.
- All methods return a
Promise; everyadd…call that adds an event listener returns a function that removes the subscription.
Installation
npm install @pushizo/capacitor @pushizo/web
npx cap sync@pushizo/web is only needed if the app also runs on the web; in native builds it is imported dynamically, so it isn't loaded.
Android (FCM)
- Add an Android app in the Firebase console and put the
google-services.jsonfile underandroid/app/. The Capacitor template applies thecom.google.gms.google-servicesplugin automatically if the file exists. - Dashboard → Channels → Android Push → Firebase service account JSON (you can pick Capacitor/Ionic in the setup wizard).
- The plugin depends on the
com.pushizo:pushizo-androidartifact (Maven Central 0.1.0). You can change the version withpushizoAndroidVersioninvariables.gradle. To try it locally from inside the monorepo:cd sdk/android && gradle :pushizo:publishToMavenLocaland addmavenLocal()toandroid/build.gradle→allprojects.repositories. POST_NOTIFICATIONS, the FCM service and the notification-open Activity are merged from the SDK manifest. Notification icon: thecom.pushizo.sdk.default_notification_iconmeta-data inAndroidManifest.xml.
The plugin stores the settings from the first initialize call made from JS (only the app ID and public settings); when the process restarts because of a notification tap or an FCM message, the SDK is initialized before the WebView loads, so the tap and the received record aren't lost.
iOS (APNs)
- Xcode → Signing & Capabilities: Push Notifications, Background Modes → Remote notifications.
- Dashboard → Channels → iOS Push →
.p8key (Key ID, Team ID, bundle id) or.p12certificate. - Forward the APNs token to the plugin (
ios/App/App/AppDelegate.swift):
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}- CocoaPods:
npx cap sync iosinstalls the plugin'sPushizoCapacitorpod; this pod depends on thePushizopod (~> 0.1) from CocoaPods trunk, so you don't need to add a separate line toios/App/Podfile. SPM (Capacitor 7): the package is resolved from thehttps://github.com/pushizo/pushizo-ios.gitrepository. - For rich media, badges and the
receivedrecord while the app is closed, add a Notification Service Extension target (iOS 15), writetarget 'PushizoNSE' do pod 'Pushizo/Extension' endin the Podfile and delegate theNotificationServiceclass to thePushizoNotificationServiceExtension(appId:apiUrl:appGroup:)helper. Enable the same App Group in the app and the NSE and write it to the app's Info.plist asPushizoAppGroup(defaultgroup.<bundle id>.pushizo). Details: iOS SDK.
The Pushizo SDK takes over the UNUserNotificationCenter delegate; don't use @capacitor/push-notifications in the same app.
Web
Put the PushizoSDKWorker.js file at the root of your site; if needed, use initialize(appId, { web: { serviceWorkerPath: '/PushizoSDKWorker.js', serviceWorkerScope, allowLocalhostAsSecureOrigin } }). On the web, removeNotification, User.getEmails and User.getSmsNumbers are not available (UNAVAILABLE), clearAll closes service worker notifications, and a blocked foreground notification can't be displayed later. The badge, User.setProperty, the sendEvent eventId, the FeatureFlags / Inbox observers and Chat.show() (the Web SDK chat widget) are forwarded to their @pushizo/web counterparts; the Chat message flow calls (start, getMessages, sendMessage, startListening …) return PLATFORM_NOT_SUPPORTED on the web.
Initialization
import { Pushizo } from '@pushizo/capacitor';
// Add the click listener as early as possible: when the app is opened from a notification, the pending tap is delivered to the first listener.
Pushizo.Notifications.addClickListener((event) => {
console.log(event.notification.title, event.result.actionId, event.result.url);
});
await Pushizo.initialize('app_…', {
apiUrl: 'https://api.pushizo.com',
requiresPrivacyConsent: false,
logLevel: 'warn', // none | error | warn | info | debug
});
await Pushizo.setConsentGiven(true); // if requiresPrivacyConsent: true; no network calls are made until theninitialize also accepts a single object: Pushizo.initialize({ appId: 'app_…', apiUrl }).
Permission
const granted = await Pushizo.Notifications.requestPermission(); // Android 13+ POST_NOTIFICATIONS, iOS UNAuthorization
const current = await Pushizo.Notifications.getPermission();
const stop = Pushizo.Notifications.addPermissionObserver(({ permission }) => {});
stop(); // or removePermissionObserver(cb)The permission event comes from the native SDK's permission observer: it is delivered only on an actual change, when a permission request completes and when the app returns to the foreground (if it was changed in settings).
User, subscription, tags and aliases
await Pushizo.login('user_42', identityHash); // the hash is required if identity verification is on
await Pushizo.logout();
await Pushizo.User.addTag('plan', 'pro'); await Pushizo.User.addTags({ plan: 'pro', level: 3, vip: true }); // numbers/booleans are converted to strings, null/undefined are skipped
await Pushizo.User.removeTag('plan'); await Pushizo.User.removeTags(['plan', 'level']);
const tags = await Pushizo.User.getTags(); await Pushizo.User.setLanguage('tr');
await Pushizo.User.addAlias('crm_id', '1001'); // addAliases({ … }), removeAlias('crm_id')
const externalId = await Pushizo.User.getExternalId();
const hsId = await Pushizo.User.getId();
const emails = await Pushizo.User.getEmails(); // those registered with addEmail on this device; getSmsNumbers() works the same way
const state = await Pushizo.User.pushSubscription.getState(); // { id, token, optedIn, permission }
await Pushizo.User.pushSubscription.getId(); // getToken(), getOptedIn()
await Pushizo.User.pushSubscription.optIn(); await Pushizo.User.pushSubscription.optOut();
const unsubscribe = Pushizo.User.pushSubscription.addObserver((s) => console.log(s.id, s.optedIn)); // removeObserver(cb)Email and SMS
await Pushizo.User.addEmail('ali@pushizo.com'); // INVALID_ARGUMENT if invalid
await Pushizo.User.removeEmail('ali@pushizo.com');
await Pushizo.User.addSms('+905551112233');
await Pushizo.User.removeSms('+905551112233');User preferences
const { preferences, categories } = await Pushizo.User.getPreferences();
for (const c of categories) console.log(c.key, c.name.tr ?? c.name.en, c.channels, c.defaultOptedIn);
const updated = await Pushizo.User.setPreferences([ // 1-100 records; returns the updated list
{ category: 'promo', optedIn: false }, // no channel/null = all channels
{ category: 'news', channel: 'email', optedIn: true }, // ios_push | android_push | web_push | email | sms
]);Preferences require a subscription (otherwise NOT_READY); proof of ownership is added by the native SDK. An undefined category is rejected with HS_NOT_FOUND, and a channel the category doesn't cover with HS_VALIDATION_ERROR. updatedAt is epoch milliseconds. On the web, setPreferences reads the current list, checks the category/channel and hands the write to the web SDK's offline queue. Category model: Preferences.
Notification events
Pushizo.Notifications.addForegroundLifecycleListener((event) => {
if (event.notification.data.silent_in_app === '1') {
event.preventDefault(); // don't show; to show it later: await event.display()
}
});
Pushizo.Notifications.removeClickListener(cb); // removeForegroundLifecycleListener(cb)When a foreground listener is added, the native SDK holds the display until JS decides; if no listener calls preventDefault(), the notification is shown immediately. On iOS, a blocked notification can be shown with display() within at most 25 s. Notification object: title, body, url, imageUrl, deliveryId, messageId, data, androidNotificationId (Android only).
In-app messages
await Pushizo.InAppMessages.addTriggers({ level: 5, vip: true }); // addTrigger, removeTrigger(s), clearTriggers, getTriggers
await Pushizo.InAppMessages.setScreen('checkout'); // setScreen(null) when leaving the screen
await Pushizo.InAppMessages.setPaused(true); // await getPaused()
Pushizo.InAppMessages.addClickListener((e) => console.log(e.message.id, e.result.actionId, e.result.url));
Pushizo.InAppMessages.addLifecycleListener({ willDisplay: (e) => {}, didDisplay: (e) => {}, willDismiss: (e) => {}, didDismiss: (e) => {} });Messages are rendered with the native SDK's own view (Android Dialog, iOS UIWindow).
Notification inbox
const page = await Pushizo.Inbox.list({ limit: 20 }); // { items, unreadCount, nextCursor, hasMore }
await Pushizo.Inbox.markRead(page.items[0].id); // returns the updated item
const unread = await Pushizo.Inbox.markAllRead(); // remaining unread count
await Pushizo.Inbox.archive(page.items[0].id);
const count = await Pushizo.Inbox.unreadCount();
const next = page.hasMore ? await Pushizo.Inbox.list({ cursor: page.nextCursor! }) : null;A registered subscription and user are required (otherwise NOT_READY). limit is 1-200 (default 50). Times are epoch milliseconds.
Content cards
const feed = await Pushizo.ContentCards.list(20); // { cards, unviewedCount }
await Pushizo.ContentCards.logImpression(feed.cards[0].id);
await Pushizo.ContentCards.logClick(id); // click (also counts as an impression)
await Pushizo.ContentCards.dismiss(id); // removes it from the feedCards do not appear in the notification inbox; the feed is ordered pinned → priority → newest. limit is 1-100 (default 50). A registered subscription and user are required (otherwise NOT_READY). Log an impression when a card is shown and a click when it is tapped; the stats appear on the campaign detail page.
Android delivery hardening
On vendors such as Xiaomi, Huawei, Oppo, Vivo and Samsung, the battery and auto-start manager stops apps in the background, so notifications arrive late or not at all. Pushizo.Delivery reads the restrictions on the device and takes the user to the relevant settings screen. Details: Android delivery hardening.
const status = await Pushizo.Delivery.status(); // { supported, vendor, rom, risk, restricted, recommendedSettings, … }
if (await Pushizo.Delivery.shouldShowGuidance()) { // at risk and the dialog was not shown in the last 14 days
const opened = await Pushizo.Delivery.showGuidance(); // ready-made dialog (22 languages); opens the settings screen if accepted
}
await Pushizo.Delivery.openSettings('auto_start'); // from your own UIrisk: none, elevated, high. Screens: auto, notifications, auto_start, battery_optimization, app_details (TypeError for an invalid value). shouldShowGuidance(30) changes the interval and showGuidance({ setting, message }) the screen and the text; the SDK never shows the dialog on its own. Android only: on iOS and the web status() returns supported: false and risk: 'none', and openSettings and showGuidance return false without doing anything.
Profile, consent, advertising ID and badge
await Pushizo.login('user_42', { jwt, profile: { email: 'ali@ornek.com', sms: '+905551112233', tags: { plan: 'pro' }, aliases: { crm: 'c-1' } } });
await Pushizo.User.setAdsPersonalizationConsent(true); // ads personalization consent; returns the current preferences
const consents = await Pushizo.User.getConsents(); // [{ purpose, granted, source, updatedAt }]
await Pushizo.Ads.setAdvertisingId(gaidOrIdfa); // null deletes the record
const shown = await Pushizo.Notifications.setBadgeCount(3); // true when this device can show the badge
await Pushizo.Notifications.clearBadge();
if (await Pushizo.Location.permissionGranted() && !(await Pushizo.Location.backgroundPermissionGranted())) {
await Pushizo.Location.requestBackgroundPermission('To let you know when you are near a store'); // same as requestAlwaysPermission on iOS
}
const listening = await Pushizo.Chat.isListening();
const ready = await Pushizo.isInitialized();The login profile writes the email, SMS number, tags and aliases in the same call as the login; an invalid email, phone number or alias is rejected with INVALID_ARGUMENT before the login (validation lives in the native SDKs: Android login(id, HsUserProfile), iOS login(_:profile:)). Ads.setAdvertisingId takes the ID from your app (the SDK ships no ad library and no ATT prompt); the ID reaches an audience only for users with the ads_personalization consent, and only as a SHA-256 hash. setBadgeCount and clearBadge return true when this device can show the badge: on iOS they set the app badge and the counter shared with the notification extension (always true); Android has no "set the count" API for the launcher badge, so the native SDK stores the count and writes it to the following notifications (false before Android 8, or when notifications or the channel badge are turned off); on the web the App Badging API is used (installed PWA; false when the browser doesn't support it). Notifications.getBadgeCount() returns the current count. Location.permissionGranted() and backgroundPermissionGranted() are read from the native SDK and never prompt. requestBackgroundPermission(rationale?) and requestAlwaysPermission() request the same permission (Android ACCESS_BACKGROUND_LOCATION, iOS "Always"); they return false when the permission is not declared in the app's manifest or Info.plist. User.registerAdm(token) writes the Fire OS ADM registration ID (Android only; does nothing on iOS). On the web the ADM and advertising ID calls do nothing and the background location permission queries return false; Location.permissionGranted() returns the last known state of the browser's location permission; consent and the profile (login(id, proof, profile)) are forwarded to the @pushizo/web SDK.
User properties, observers, event ID and the built-in chat screen
await Pushizo.User.setProperty('plan', 'pro'); // string, number, boolean
await Pushizo.User.setProperty('address', { city: 'İzmir', tags: ['vip'] }); // array / plain object
await Pushizo.User.setProperty('plan', null); // null deletes the property
const removeFlags = Pushizo.FeatureFlags.addObserver(async () => {
applyTheme(await Pushizo.FeatureFlags.getValue('theme', 'light'));
});
const removeInbox = Pushizo.Inbox.addObserver(({ type, itemId, unreadCount }) => setBadge(unreadCount));
// When the same ID is given to the ad pixel, the server deduplicates the event.
await Pushizo.Session.sendEvent('purchase', { sku: 'A1' }, 49.9, { eventId: 'order_42:purchase' });
await Pushizo.Chat.show(); // built-in chat screen
if (await Pushizo.Chat.isPresented()) await Pushizo.Chat.hide();User.setProperty(key, value) writes a user property and null deletes it; key is 1-64 characters and value is a string, a finite number, a boolean, or an array/plain object of those (a nested null, a Date or a function throws TypeError). FeatureFlags.addObserver(cb) is called every time the flag values are refreshed from the server (at session start and on refresh()). Inbox.addObserver(cb) delivers the inbox change event (type: listed, read, read_all, archived, count; itemId only on single-item events; unreadCount is the current unread count): read / read_all / archived are reported on every operation, listed / count only when the unread count changes. Both addObserver calls return a function that removes the subscription; removeObserver(cb) does the same. The eventId in the fourth argument of sendEvent is the deduplication ID (8-64 characters; letters, digits and . _ : -); when the format is invalid the native SDK generates its own ID. Chat.show() opens the built-in chat screen (Android HsChatActivity, iOS modal HSChatViewController; web: the Web SDK chat widget), Chat.hide() closes it and Chat.isPresented() tells whether it is open; before initialize, show() is rejected with NOT_READY. The native Android SDK doesn't expose the presentation state, so the bridge tracks the HsChatActivity lifecycle. Native views (HsChatView, HsContentCardsView) and InAppMessages.setRenderer can't be bridged. For the web-only DOM APIs (ContentCards.render, Placements.render, Search), use @pushizo/web directly.
Events (outcomes) and the notification tray
await Pushizo.Session.sendEvent('purchase', { sku: 'A1' }, 49.9); // the name also fires in-app event triggers
await Pushizo.Notifications.clearAll(); // tray/Notification Center + badge
await Pushizo.Notifications.removeGroupedNotifications('orders'); // Android android_group / iOS thread-id
await Pushizo.Notifications.removeNotification(n.androidNotificationId!); // Android tray ID
await Pushizo.Notifications.removeNotification('request-id'); // iOS: UNNotificationRequest.identifier
await Pushizo.Debug.setLogLevel('debug');Error codes
The code field of a rejected Promise:
| Code | Meaning |
|---|---|
INVALID_ARGUMENT | Invalid email/phone or a missing field. |
NOT_READY | initialize wasn't called, or the subscription/user isn't registered yet. |
NOT_FOUND | The deferred foreground notification wasn't found or was already shown (event.display()). |
UNAVAILABLE | Operation not supported on the web (removeNotification, getEmails/getSmsNumbers, a later display() of a blocked notification). |
HS_… | Server error code; catalog: Errors. |
Empty/invalid arguments throw TypeError / RangeError before reaching the bridge.
Testing
cd sdk/capacitor && npm install && npm run typecheck && npm test && npm run buildTroubleshooting
| Symptom | Cause / fix |
|---|---|
| No subscription created on iOS | The capacitorDidRegisterForRemoteNotifications notification isn't posted in AppDelegate, or the Push Notifications capability is missing. |
| Click/foreground events don't arrive | @capacitor/push-notifications or another push plugin is taking over the UNUserNotificationCenter delegate; remove it. |
Android: pushizo-android can't be resolved | publishToMavenLocal wasn't run, or the mavenLocal() repository wasn't added. |
| Tap is lost when opening from a notification | Add addClickListener before initialize, at app startup. |
requestPermission always false | Permission denied on Android 13+; Push capability missing on iOS. Other symptoms: Android, iOS. |
React Native SDK
@pushizo/react-native — a TurboModule bridge wrapping the native Android and iOS SDKs, plus an Expo config plugin; push, in-app, notification inbox, preferences.
Cordova SDK
cordova-plugin-pushizo — a plugin wrapping the native Android and iOS SDKs over the cordova.exec bridge; push, in-app, notification inbox, preferences.