Firebase Cloud Messaging Integration
The Tribe platform uses Firebase Cloud Messaging (FCM) to deliver push notifications to mobile devices. This document explains how the integration works and provides information for developers working with the mobile application.
Overview
When a push notification is sent through the Tribe API, the following process occurs:
- A notification record is created in the Tribe database
- The notification is added to the Firebase Cloud Messaging
ff_push_notificationscollection - Firebase Cloud Messaging delivers the notification to user devices
- Users can interact with the notification to navigate to specific pages in the app
Firebase Cloud Messaging Collection Structure
Push notifications are stored in the ff_push_notifications collection with the following structure:
{
tribe_notification_id: 123, // ID from the Tribe database
initial_page_name: "Content", // Page to navigate to when tapped
notification_sound: "default", // Sound to play
notification_text: "Check out our latest content!", // Message body
notification_title: "New Content Available", // Notification title
parameter_data: "{\"contentId\": 456}", // JSON string with additional data
target_audience: "All", // Target audience (always "All")
timestamp: Timestamp, // When the notification was created
user_refs: "/user/uid1,/user/uid2,/user/uid3", // Comma-separated list of user references
scheduled_time: Timestamp, // Optional: when to send the notification
tribeGroupId: 789, // Optional: associated group ID
groupRef: DocumentReference // Optional: reference to the group document
}
Mobile App Implementation
Handling Notifications in Flutter
The mobile app should implement FCM handlers to process incoming notifications:
// Initialize Firebase Messaging
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
// Request permission
Future<void> requestNotificationPermissions() async {
NotificationSettings settings = await _firebaseMessaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
print('User granted permission: ${settings.authorizationStatus}');
}
// Set up message handlers
void setupMessaging() {
// Handle messages when the app is in the foreground
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
// Show an in-app notification
showLocalNotification(message);
}
});
// Handle when a user taps on a notification to open the app
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('A new onMessageOpenedApp event was published!');
// Navigate to the appropriate page
navigateBasedOnNotification(message);
});
}
// Navigate to the appropriate page based on the notification
void navigateBasedOnNotification(RemoteMessage message) {
final String pageName = message.data['initial_page_name'] ?? 'Home';
final String parameterData = message.data['parameter_data'] ?? '{}';
// Parse the parameter data
Map<String, dynamic> params = {};
try {
params = json.decode(parameterData);
} catch (e) {
print('Error parsing parameter data: $e');
}
// Navigate to the appropriate page
switch (pageName) {
case 'Content':
if (params.containsKey('contentId')) {
Navigator.pushNamed(context, '/content/${params['contentId']}');
}
break;
case 'Events':
if (params.containsKey('eventId')) {
Navigator.pushNamed(context, '/events/${params['eventId']}');
}
break;
default:
Navigator.pushNamed(context, '/$pageName'.toLowerCase());
break;
}
}
Testing Notifications
To test push notifications during development:
- Ensure your platform has Firebase credentials configured
- Use the Firebase Console to send test messages to specific devices
- Use the Tribe API to send test notifications to your test users
- Verify that notifications are delivered and that tapping them navigates to the correct page
Troubleshooting
Common issues with push notifications:
- Notifications not being delivered: Check that the device has granted notification permissions and that the user's Firebase token is valid
- Navigation not working: Ensure that the
initial_page_nameandparameter_datavalues are correct and that the app handles them properly - Scheduled notifications not sending: Verify that the
scheduled_timeis in the future and that the Firebase Cloud Functions are running correctly
Security Considerations
- Firebase security rules should be configured to restrict access to the
ff_push_notificationscollection - Only authenticated administrators should be able to send push notifications
- User tokens should be stored securely and refreshed regularly