Skip to content

Push Notifications

Set up push notifications with the Tappd Mobile SDK.

Overview

The SDK allows you to register device push tokens and track push notification subscription status. This enables you to send push notifications to users through the Tappd platform.

Prerequisites

Before setting up push notifications:

  1. Firebase Cloud Messaging (FCM) for Android
  2. Apple Push Notification Service (APNs) for iOS
  3. Push notification certificates/keys configured
  4. User must be identified first

Installation

bash
npm install @react-native-firebase/app @react-native-firebase/messaging

For iOS:

bash
cd ios && pod install && cd ..

Alternative: React Native Push Notification

bash
npm install react-native-push-notification

Setup

1. Request Permissions

Request push notification permissions:

javascript
import messaging from '@react-native-firebase/messaging';
import { Platform, PermissionsAndroid } from 'react-native';

async function requestPushPermission() {
  if (Platform.OS === 'ios') {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
    return enabled;
  } else {
    // Android - permissions are requested automatically by FCM
    return true;
  }
}

2. Get Push Token

Get the FCM token:

javascript
import messaging from '@react-native-firebase/messaging';

async function getPushToken() {
  try {
    const token = await messaging().getToken();
    return token;
  } catch (error) {
    console.error('Failed to get push token:', error);
    return null;
  }
}

3. Register Token with Tappd

Register the token with Tappd SDK:

javascript
import TappdSDK from '@tappd/mobile-sdk';
import messaging from '@react-native-firebase/messaging';
import { Platform } from 'react-native';

// Initialize SDK
const tappd = new TappdSDK({
  appId: 'YOUR_APP_ID'
});

// Identify user first
await tappd.identify('user_123', {
  email: 'john@example.com'
});

// Get and register token
const token = await messaging().getToken();
if (token) {
  await tappd.registerPushToken(
    token,
    Platform.OS === 'ios' ? 'ios' : 'android'
  );
}

Complete Setup Example

javascript
import React, { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { Platform } from 'react-native';
import TappdSDK from '@tappd/mobile-sdk';

const tappd = new TappdSDK({
  appId: 'YOUR_APP_ID'
});

function App() {
  useEffect(() => {
    setupPushNotifications();
  }, []);

  async function setupPushNotifications() {
    try {
      // Request permission
      if (Platform.OS === 'ios') {
        const authStatus = await messaging().requestPermission();
        const enabled =
          authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
          authStatus === messaging.AuthorizationStatus.PROVISIONAL;
        
        if (!enabled) {
          console.log('Push notifications not authorized');
          return;
        }
      }

      // Get token
      const token = await messaging().getToken();
      
      if (token && tappd) {
        // Register with Tappd (user must be identified first)
        await tappd.registerPushToken(
          token,
          Platform.OS === 'ios' ? 'ios' : 'android'
        );
        console.log('Push token registered');
      }

      // Listen for token refresh
      messaging().onTokenRefresh(async (newToken) => {
        if (tappd) {
          await tappd.registerPushToken(
            newToken,
            Platform.OS === 'ios' ? 'ios' : 'android'
          );
          console.log('Push token refreshed');
        }
      });
    } catch (error) {
      console.error('Push notification setup failed:', error);
    }
  }

  return (
    // Your app
  );
}

Check Subscription Status

Check if a user has subscribed to push notifications:

javascript
async function checkSubscription() {
  try {
    const status = await tappd.checkPushSubscription();
    
    console.log('Subscribed:', status.subscribed);
    console.log('Status:', status.status); // 'subscribed', 'opted_in', or 'unsubscribed'
    console.log('Device Count:', status.deviceCount);
    
    return status;
  } catch (error) {
    console.error('Failed to check subscription:', error);
    return null;
  }
}

Handle Token Refresh

Tokens can be refreshed by FCM. Listen for token refresh events:

javascript
import messaging from '@react-native-firebase/messaging';
import { Platform } from 'react-native';

messaging().onTokenRefresh(async (newToken) => {
  try {
    await tappd.registerPushToken(
      newToken,
      Platform.OS === 'ios' ? 'ios' : 'android'
    );
    console.log('Token refreshed and registered');
  } catch (error) {
    console.error('Failed to register refreshed token:', error);
  }
});

Handle Push Notifications

Foreground Messages

Handle messages when app is in foreground:

javascript
import messaging from '@react-native-firebase/messaging';

messaging().onMessage(async (remoteMessage) => {
  console.log('Foreground message:', remoteMessage);
  
  // Track notification received event
  await tappd.track('push_notification.received', {
    notificationId: remoteMessage.messageId,
    title: remoteMessage.notification?.title,
    body: remoteMessage.notification?.body
  });
  
  // Show notification UI
  // ...
});

Background Messages

Handle messages when app is in background:

javascript
// In index.js
import messaging from '@react-native-firebase/messaging';

messaging().setBackgroundMessageHandler(async (remoteMessage) => {
  console.log('Background message:', remoteMessage);
  
  // Track notification received
  // Note: SDK may not be initialized in background handler
  // Track via API directly if needed
});

Notification Taps

Handle when user taps a notification:

javascript
import messaging from '@react-native-firebase/messaging';

// Check if app was opened from notification
messaging()
  .getInitialNotification()
  .then(async (remoteMessage) => {
    if (remoteMessage) {
      // App opened from notification
      await tappd.track('push_notification.opened', {
        notificationId: remoteMessage.messageId,
        title: remoteMessage.notification?.title
      });
    }
  });

// Listen for notification opened while app is running
messaging().onNotificationOpenedApp(async (remoteMessage) => {
  await tappd.track('push_notification.opened', {
    notificationId: remoteMessage.messageId,
    title: remoteMessage.notification?.title
  });
});

Best Practices

  1. Identify user first - Push tokens require identified users
  2. Handle token refresh - Always listen for token refresh events
  3. Track notification events - Track received and opened events
  4. Error handling - Wrap token registration in try-catch
  5. Platform detection - Use Platform.OS to determine platform

iOS Specific Setup

1. Enable Push Notifications Capability

In Xcode:

  1. Open your project
  2. Select your target
  3. Go to "Signing & Capabilities"
  4. Click "+ Capability"
  5. Add "Push Notifications"

2. Configure APNs

Upload your APNs certificate or key to Firebase Console:

  1. Go to Firebase Console → Project Settings → Cloud Messaging
  2. Upload APNs Authentication Key or Certificate

Android Specific Setup

1. Configure FCM

  1. Download google-services.json from Firebase Console
  2. Place it in android/app/
  3. Add to android/build.gradle:
gradle
dependencies {
  classpath 'com.google.gms:google-services:4.3.15'
}
  1. Add to android/app/build.gradle:
gradle
apply plugin: 'com.google.gms.google-services'

Troubleshooting

Token Not Registering

Problem: registerPushToken() fails

Solutions:

  1. Ensure user is identified first
  2. Check FCM/APNs configuration
  3. Verify network connectivity
  4. Check error logs

Notifications Not Received

Problem: Notifications not arriving

Solutions:

  1. Verify token is registered
  2. Check subscription status
  3. Verify FCM/APNs setup
  4. Check device permissions

Next Steps

Released under the MIT License.