React Native集成FCM推送求助:注册后上传用户Token至Firebase
Got it, let's walk through how to set up FCM push notifications in React Native—including capturing the FCM Token after user registration, storing it in Firebase, and using that Token to send targeted pushes. I’ve implemented this flow multiple times, so here’s a step-by-step guide that should work smoothly:
1. Set Up React Native Firebase Dependencies
First, you’ll need to integrate Firebase into your React Native project if you haven’t already:
- Create a project in the Firebase Console, then download
google-services.json(Android) andGoogleService-Info.plist(iOS) and place them in their respective project directories. - Install the required packages:
npm install @react-native-firebase/app @react-native-firebase/messaging @react-native-firebase/firestore @react-native-firebase/auth # Or using yarn: yarn add @react-native-firebase/app @react-native-firebase/messaging @react-native-firebase/firestore @react-native-firebase/auth - For Android, add the Firebase classpath to your
android/build.gradleand apply the google-services plugin inandroid/app/build.gradle(this is covered in the Firebase setup wizard, so follow those steps closely).
2. Capture FCM Token After User Registration
Once the user completes registration, you’ll need to request notification permissions, fetch the FCM Token, and store it in Firebase (we’ll use Firestore here as an example):
Request Notification Permissions
Call this function right after the user registers successfully:
import messaging from '@react-native-firebase/messaging'; async function requestNotificationPermissions() { const authStatus = await messaging().requestPermission(); const hasPermission = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; if (hasPermission) { console.log('Notification permissions granted'); await fetchAndSaveFCMToken(); } else { console.log('Notification permissions denied'); } }
Fetch & Store Token to Firebase
This function retrieves the Token and saves it to Firestore under the user’s document (assuming you’re using Firebase Auth for user management):
import firestore from '@react-native-firebase/firestore'; import auth from '@react-native-firebase/auth'; async function fetchAndSaveFCMToken() { try { const fcmToken = await messaging().getToken(); if (!fcmToken) return; const currentUser = auth().currentUser; if (!currentUser) { console.log('No authenticated user found'); return; } // Save Token to Firestore await firestore() .collection('users') .doc(currentUser.uid) .set( { fcmToken, lastTokenUpdated: firestore.FieldValue.serverTimestamp() }, { merge: true } // Merge to avoid overwriting existing user data ); console.log('FCM Token saved to Firebase successfully'); } catch (error) { console.error('Error fetching/saving FCM Token:', error); } }
Listen for Token Refreshes
FCM Tokens can expire or change, so add a listener to update the stored Token automatically:
messaging().onTokenRefresh(async (newToken) => { await fetchAndSaveFCMToken(newToken); });
3. Send Push Notifications Using the Stored Token
You have a few options to send pushes to the user’s Token:
Option 1: Firebase Console (Quick Testing)
- Go to the Firebase Console → Cloud Messaging.
- Click "Send your first message".
- Under "Target", select "Single device" and paste the FCM Token you stored.
- Fill in the notification title/body, then click "Send test message".
Option 2: Firebase Admin SDK (Backend Integration)
For automated pushes (like welcome messages after registration), use the Firebase Admin SDK on your backend. Here’s a Node.js example:
const admin = require('firebase-admin'); // Initialize Admin SDK (run this once at app startup) admin.initializeApp({ credential: admin.credential.applicationDefault() }); async function sendWelcomePush(userFCMToken) { const message = { notification: { title: 'Welcome Aboard!', body: 'Thanks for registering with us. We’re glad you’re here.' }, token: userFCMToken }; try { const response = await admin.messaging().send(message); console.log('Push notification sent successfully:', response); } catch (error) { console.error('Error sending push notification:', error); } } // Call this function after fetching the user's Token from Firestore sendWelcomePush('USER_FCM_TOKEN_HERE');
Option 3: Handle Notifications in React Native
To handle incoming notifications in your app (both foreground and background):
import { Alert } from 'react-native'; import messaging from '@react-native-firebase/messaging'; // Handle foreground notifications messaging().onMessage(async (remoteMessage) => { Alert.alert( 'New Notification', `${remoteMessage.notification.title}\n${remoteMessage.notification.body}` ); }); // Handle notification taps when app is in background messaging().onNotificationOpenedApp((remoteMessage) => { console.log('Notification opened from background:', remoteMessage); // Navigate to a specific screen, e.g., using React Navigation // navigation.navigate('NotificationDetails', { data: remoteMessage }); }); // Handle notification taps when app is fully closed messaging() .getInitialNotification() .then((remoteMessage) => { if (remoteMessage) { console.log('Notification opened from closed state:', remoteMessage); // Navigate to the relevant screen here } });
Critical Notes for Android
- For Android 8.0+ (API level 26), you must create a notification channel:
import { Platform } from 'react-native'; import messaging from '@react-native-firebase/messaging'; async function createNotificationChannel() { if (Platform.OS === 'android') { const channel = new messaging.NotificationChannel('default', { name: 'Default Notifications', description: 'All app notifications', importance: messaging.Importance.HIGH, sound: true, }); await messaging().createNotificationChannel(channel); } } // Call this function when your app starts createNotificationChannel(); - Ensure your AndroidManifest.xml includes the necessary permissions for notifications.
Let me know if you hit any snags—like permission issues, Token not saving, or notifications not appearing. I can help troubleshoot specific problems!
内容的提问来源于stack exchange,提问作者FortuneCookie

