Pushizo Docs
SDK rehberleri

React Native SDK

@pushizo/react-native — Android ve iOS yerel SDK'larını saran TurboModule köprüsü ve Expo config plugin; push, in-app, bildirim kutusu, tercihler.

@pushizo/react-native, yerel Android (com.pushizo:pushizo-android) ve iOS (Pushizo) SDK'larını sarar: kuyruk, oturum, teslimat geri bildirimi (received/opened), tetik değerlendirme ve in-app çizimi yerel tarafta çalışır. Yüzey OneSignal v5 React Native API'siyle uyumludur. Örnek: examples/react-native (bare RN 0.87, New Architecture).

  • React Native ≥ 0.74; New Architecture (TurboModule, codegen RNPushizoSpec) ve eski mimari desteklenir.
  • Android minSdk 24, iOS 15.0+.
  • Expo: yalnızca development build (expo prebuild / EAS Build); Expo Go yerel modül içermediğinden desteklenmez.

Kurulum

npm install @pushizo/react-native

Android

  1. Firebase konsolundan Android uygulaması ekleyip google-services.json dosyasını android/app/ altına koyun. android/build.gradle → buildscript.dependencies içine classpath("com.google.gms:google-services:4.4.2"), android/app/build.gradle içine apply plugin: "com.google.gms.google-services".
  2. Dashboard → Kanallar → Android Push → Firebase servis hesabı JSON'u.
  3. INTERNET, POST_NOTIFICATIONS ve FCM servisi yerel SDK manifestinden otomatik birleşir. Varsayılan bildirim ikonu için <application> içine:
<meta-data android:name="com.pushizo.sdk.default_notification_icon" android:resource="@drawable/ic_notification" />
  1. Monorepo içinden derliyorsanız android/settings.gradle:
include ':pushizo'
project(':pushizo').projectDir = new File(rootProject.projectDir, '../../../sdk/android/pushizo')

Bu modül yoksa köprü com.pushizo:pushizo-android artefaktını kullanır (Maven Central ya da publishToMavenLocal).

iOS

  1. cd ios && pod install. Yerel geliştirmede ios/Podfile → pod 'Pushizo', :path => '<repo>/sdk/ios'.
  2. Xcode → hedef → Signing & Capabilities: Push Notifications, Background Modes → Remote notifications ve (rozet/NSE paylaşımı için) App Groups (group.<bundle id>.pushizo).
  3. SDK swizzling kullanmaz; APNs token'ını AppDelegate'ten iletin:
import Pushizo

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  Pushizo.setDeviceToken(deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  Pushizo.setDeviceTokenError(error)
}

Objective-C AppDelegate.mm: #import <PushizoReactNative/PushizoRNPush.h> ve aynı metotlarda [PushizoRNPush didRegisterForRemoteNotificationsWithDeviceToken:deviceToken] / [PushizoRNPush didFailToRegisterForRemoteNotificationsWithError:error].

  1. Dashboard → Kanallar → iOS Push → .p8 anahtarı (Key ID, Team ID).
  2. Zengin medya, aksiyon düğmeleri, rozet artışı ve received kaydı için Notification Service Extension: hedefi ekleyip sdk/react-native/plugin/templates/PushizoNotificationServiceExtension/NotificationService.swift dosyasını kopyalayın, hedefin Info.plist'ine PushizoAppId (isteğe bağlı PushizoApiUrl, PushizoAppGroup) ekleyin ve Podfile'a target 'PushizoNotificationServiceExtension' do pod 'Pushizo/Extension' end yazın. Ayrıntı: iOS SDK.

Expo

{
  "expo": {
    "ios": { "bundleIdentifier": "com.example.app" },
    "android": { "package": "com.example.app", "googleServicesFile": "./google-services.json" },
    "plugins": [
      ["@pushizo/react-native", { "mode": "development", "appId": "app_…", "androidSmallIcon": "./assets/notification-icon.png", "androidAccentColor": "#FF5A1F" }]
    ]
  }
}

Ardından npx expo prebuild (veya EAS Build). Plugin iOS'ta aps-environment, Background Modes, App Group, AppDelegate token iletimi, Info.plist anahtarları ve PushizoNotificationServiceExtension hedefini; Android'de POST_NOTIFICATIONS, küçük ikon, vurgu rengi ve erken başlatma meta-data'sını ekler; android.googleServicesFile verilmişse dosyayı android/app/google-services.json olarak kopyalar ve com.google.gms.google-services Gradle eklentisini uygular (idempotent). Erken başlatma requiresPrivacyConsent ve logLevel değerlerini iOS'ta Info.plist'ten (PushizoRequiresPrivacyConsent, PushizoLogLevel), Android'de manifest meta-data'sından okur; onay gerekiyorsa SDK JS yüklenmeden önce de ağa çıkmaz.

SeçenekAçıklama
modeZorunlu. development | production (APNs ortamı; TestFlight/App Store için production).
appIdErken başlatma ve NSE için; NSE açıkken zorunlu.
apiUrl, requiresPrivacyConsent, logLevelErken başlatma ayarları (JS initialize ile aynı olmalı).
iosAppGroupgroup. ile başlayan App Group (varsayılan group.<bundle id>.pushizo).
iosNotificationServiceExtensionNSE hedefi (varsayılan true).
iosDeploymentTarget, devTeamNSE dağıtım hedefi (varsayılan 15.0) ve imzalama ekibi.
iosSdkPath, androidSdkPathMonorepo: yerel SDK'ları kaynaktan bağlar.
androidSmallIcon, androidAccentColorPNG ikon (beyaz şekil, saydam arka plan) ve #RRGGBB vurgu rengi.
androidDefaultChannelId, androidDefaultChannelNameErken başlatmada varsayılan bildirim kanalı (JS defaultChannelId / defaultChannelName ile aynı olmalı).

Geçersiz seçenekler prebuild sırasında hangi alanın nasıl düzeltileceğini söyleyen hatayla durur.

Başlatma

import { Pushizo, LogLevel } from '@pushizo/react-native';

await Pushizo.initialize('app_…', {
  apiUrl: 'https://api.example.com',
  requiresPrivacyConsent: false,
  logLevel: LogLevel.Warn,
  // iOS: appGroup, apnsEnvironment, provisionalAuthorization · Android: defaultChannelId, defaultChannelName
});

Pushizo.setConsentGiven(true);   // requiresPrivacyConsent: true ise; false kuyruğu ve yerel kimliği temizler

Aynı appId ile ikinci initialize yerel SDK'yı yeniden kurmaz. Soğuk açılışta SDK'nın JS yüklenmeden başlaması için (oturum başlangıcı, iOS bildirim merkezi temsilcisi) Android'de <application> içine com.pushizo.reactnative.app_id (isteğe bağlı …api_url, …requires_privacy_consent, …log_level) meta-data'sı, iOS'ta Info.plist PushizoAppId (isteğe bağlı PushizoApiUrl) ekleyin; Expo plugin appId verildiğinde bunları ekler.

İzin

const granted = await Pushizo.Notifications.requestPermission();   // Android 13+ POST_NOTIFICATIONS, iOS UNAuthorization
const current = await Pushizo.Notifications.getPermissionAsync();  // sistemden sorgular
Pushizo.Notifications.permission;                                  // son bilinen durum (eşzamanlı)
Pushizo.Notifications.addEventListener('permissionChange', ({ permission }) => {});

permissionChange yerel SDK izin gözlemcisinden gelir: izin isteği sonuçlandığında ve uygulama ön plana döndüğünde (ayarlardan değiştiyse) yalnızca gerçek değişiklikte gönderilir. İzin yoksa abonelik pending kalır; izin verilince otomatik kaydedilir.

Kullanıcı, abonelik, tag ve alias

await Pushizo.login('user_42', identityHashFromBackend);   // identity verification açıksa hash zorunlu
Pushizo.logout();

await Pushizo.User.addTag('plan', 'pro');     await Pushizo.User.addTags({ plan: 'pro', city: 'istanbul' });
await Pushizo.User.removeTag('plan');         await Pushizo.User.removeTags(['plan', 'city']);
const tags = await Pushizo.User.getTags();    await Pushizo.User.setLanguage('tr');
await Pushizo.User.addAlias('crm_id', '1001'); // addAliases({ … }) (en fazla 20), removeAlias('crm_id')
const externalId = await Pushizo.User.getExternalId();
const hsId = await Pushizo.User.getPushizoId();
const emails = await Pushizo.User.getEmails();     // bu cihazda addEmail ile kaydedilenler; getSmsNumbers() aynı biçimde

const subId = await Pushizo.User.pushSubscription.getIdAsync();
const token = await Pushizo.User.pushSubscription.getTokenAsync();
const optedIn = await Pushizo.User.pushSubscription.getOptedInAsync();
Pushizo.User.pushSubscription.optIn();        Pushizo.User.pushSubscription.optOut();
Pushizo.User.pushSubscription.addEventListener('change', ({ previous, current }) => {}); // id, token, optedIn, permission

E-posta ve SMS

await Pushizo.User.addEmail('Ali@Example.com');     // → ali@example.com; geçersizse INVALID_ARGUMENT
await Pushizo.User.removeEmail('ali@example.com');
await Pushizo.User.addSms('+90 532 123 45 67');      // → +905321234567 (E.164)
await Pushizo.User.removeSms('+905321234567');

Kullanıcı tercihleri

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([
  { category: 'promo', optedIn: false },                   // channel yok/null = tüm kanallar
  { category: 'news', channel: 'email', optedIn: true },  // ios_push | android_push | web_push | email | sms
]);

Abonelik henüz kayıtlı değilse NOT_READY. Girdi köprüden önce doğrulanır (1-100 kayıt, kategori 1-64 karakter, bilinen kanal ya da null); geçersizse TypeError. Sahiplik kanıtı yerel SDK tarafından eklenir. UserPreference: category, channel, optedIn, explicit, source, updatedAt (epoch ms). Kategori modeli: Tercihler.

Bildirim olayları

Pushizo.Notifications.addEventListener('click', (e) => {
  console.log(e.notification.title, e.notification.data, e.result.actionId, e.result.url);
});
Pushizo.Notifications.addEventListener('foregroundWillDisplay', (e) => {
  if (e.getNotification().data.silent === '1') e.preventDefault();  // ön planda gösterme
  // asenkron karar: e.preventDefault(); sonra (≤ 25 sn) e.getNotification().display();
});
Pushizo.Notifications.removeEventListener('click', listener);

Bildirime dokunularak açılan uygulamada tıklama, JS'te click dinleyicisi eklenene kadar yerelde bekletilir. foregroundWillDisplay dinleyicisi yokken yerel SDK bildirimi kendisi gösterir. Bildirim nesnesi: title, body, url, imageUrl, deliveryId, messageId, data.

In-app mesajlar

await Pushizo.InAppMessages.addTrigger('level', 'gold');  // addTriggers({…}), removeTrigger(s), clearTriggers(), getTriggers()
Pushizo.InAppMessages.setScreen('cart');                   // ekrandan çıkarken setScreen(null)
Pushizo.Session.sendEvent('cart_viewed');
Pushizo.InAppMessages.setPaused(true);                     // await Pushizo.InAppMessages.getPaused()
Pushizo.InAppMessages.addEventListener('click', ({ messageId, actionId, url }) => {});
Pushizo.InAppMessages.addEventListener('didDisplay', ({ messageId }) => {}); // willDisplay | didDisplay | willDismiss | didDismiss

Mesajlar yerel SDK'nın varsayılan çizimiyle gösterilir (Android Dialog, iOS UIWindow). Tetik anahtarı 1-64, değer en fazla 200 karakterdir; tetik kuralları, sıklık ve aksiyonlar tüm SDK'larda aynıdır.

Bildirim kutusu

const page = await Pushizo.Inbox.list({ limit: 20, cursor: null }); // items, unreadCount, nextCursor, hasMore
const item = await Pushizo.Inbox.markRead(page.items[0].id);
const remaining = await Pushizo.Inbox.markAllRead();
await Pushizo.Inbox.archive(item.id);
const unread = await Pushizo.Inbox.unreadCount();

limit 1-200 (varsayılan 50; aralık dışıysa RangeError). Zamanlar (readAt, archivedAt, expiresAt, createdAt) epoch milisaniyedir.

Olaylar (outcome) ve diğerleri

Pushizo.Session.sendEvent('purchase', { sku: 'A1' }, 49.9); // ad in-app event tetiklerini de çalıştırır
Pushizo.Notifications.clearAll();                           // Pushizo bildirimleri (iOS'ta rozet de sıfırlanır)
await Pushizo.Notifications.removeGroupedNotifications('orders'); // Android android_group / iOS thread-id
await Pushizo.Notifications.removeNotification(n.androidNotificationId!); // Android tepsi kimliği (iOS'ta null)
await Pushizo.Notifications.removeNotification('istek-kimligi');          // iOS: UNNotificationRequest.identifier
Pushizo.Debug.setLogLevel(LogLevel.Debug);                  // None | Error | Warn | Info | Debug

Hata kodları

Promise reddinin code alanı:

KodAnlam
INVALID_ARGUMENTGeçersiz e-posta/telefon/alias/tetik/tercih (yerel doğrulama).
NOT_READYinitialize çağrılmadı ya da abonelik henüz kayıtlı değil (bildirim kutusu, tercihler).
NO_ACTIVITYAndroid'de izin isteği için ön planda Activity yok.
HS_…Sunucu hata kodu (ör. HS_FORBIDDEN, HS_NOT_FOUND); katalog: Hatalar.
HS_ERRORSınıflandırılmamış yerel hata.

Boş/hatalı argümanlar köprüye gitmeden TypeError / RangeError fırlatır.

Test

cd sdk/react-native && npm install && npm run typecheck && npm test && npm run build
cd examples/react-native/android && ./gradlew :pushizo_react-native:compileDebugKotlin

Sorun giderme

BelirtiNeden / çözüm
"yerel modülü bulunamadı" hatası (ilk çağrıda)Expo Go kullanılıyor, iOS'ta pod install çalıştırılmadı ya da uygulama paket kurulduktan sonra yeniden derlenmedi (Metro yeniden yükleme yetmez); development build ve tam yeniden derleme.
iOS'ta token yok, abonelik oluşmuyorAppDelegate'te Pushizo.setDeviceToken iletilmiyor veya Push Notifications yeteneği eksik.
Bildirimden açılışta tıklama kayboluyorclick dinleyicisini kök bileşende erken ekleyin; erken başlatma meta-data/Info.plist anahtarlarını verin.
Expo prebuild hatasımode eksik ya da NSE açıkken appId verilmedi.
requestPermission hep falseAndroid 13+'ta izin reddedildi (ayarlardan açılmalı); iOS'ta Push yeteneği eksik. Diğer belirtiler: Android, iOS.

Bu sayfada