Android & Firebase Push Notifications (FCM)
Send push notifications to Android apps, and to iOS apps that use Firebase, through Firebase Cloud Messaging HTTP v1 with a service account key.
Read the push notifications overview first for how the pieces fit together. For browsers, see the web push guide. For the full list of endpoints, see the Push API reference.
Before you start
Check that you have each of these:
- Bento Chat on your plan. Push runs on Bento Chat, a $30 per month add-on.
- An approved Bento account.
- The administrator role in Bento. You need it to open Push.
- A Firebase project with your Android app, iOS app, or both added to it.
- A backend that can call Bento's push API. Your app sends its device token to your backend, and your backend registers it with Bento. See the backend example.
Which section do I follow?
Everyone completes steps 1 to 3. Then follow the row for your app.
| Your app | What to do |
|---|---|
| Android, written in Kotlin | Steps 1 to 3, then Android (Kotlin) |
| iOS, using Firebase | Steps 1 to 3, step 4, then iOS (Swift) through Firebase |
| React Native | Steps 1 to 3 (and step 4 if you ship to iOS), then React Native |
| Flutter | Steps 1 to 3 (and step 4 if you ship to iOS), then Flutter |
| Expo | Steps 1 to 3 for Android, then Expo. Expo iOS devices use the APNs guide instead. |
When your app is set up, finish with step 6: Send a test.
Step 1: Generate a service account key
- Go to console.firebase.google.com and select your project.
- Click the gear icon, then Project settings.
- Open the Service accounts tab and select Firebase Admin SDK.
- Click Generate new private key, then Generate key. A JSON file downloads.
project_id, client_email, and private_key, and anyone who has it can send pushes to your app.Step 2: Check that the FCM API is enabled
In Project settings > Cloud Messaging, check that Firebase Cloud Messaging API (V1) is enabled. If it is disabled, enable it from the menu next to it.
Step 3: Add the key in Bento
- In Bento, go to Marketing > Push > Apps and choose Set up push.
- The guide walks you through five steps: Platform, Create a key, Add credential, Connect your app, and Send a test.
- Under Platform, pick Android (Kotlin), React Native, Flutter, Expo, or iOS (Swift).
- Under Add credential, open the JSON file from step 1 and paste the whole file into Service account key (JSON).
- Bento checks the key with Google when you save it. If something is wrong, Bento shows the problem to fix.
- The Connect your app step shows the Credential ID. Copy it. Your backend sends it with every device registration.
If you prefer to enter the details yourself, choose Add keys yourself or Add app and fill in:
| Field | What to enter |
|---|---|
| Push service | Firebase (FCM) |
| Name | A name you will recognize, such as your app name |
| App ID | Optional. Defaults to your Firebase project ID. |
| Service account JSON | The whole JSON file from step 1 |
Each app in Push > Apps shows a status:
| Status | Meaning |
|---|---|
| Working | Google accepted the key. |
| Not checked | Bento has not checked the key yet. |
| Not working | Google rejected the key. See Troubleshooting. |
Step 4: Connect your iOS app to Firebase (iOS only)
Skip this step if you only ship to Android.
To send to iOS through FCM, Firebase needs your APNs key.
- Create an APNs key using the steps in the APNs guide.
- In Firebase, go to Project settings > Cloud Messaging > Apple app configuration.
- Upload the key under APNs Authentication Key.
Your iOS app still needs the Push Notifications capability in Xcode. See Add capabilities in Xcode.
Step 5: Add push to your app
Follow the section for your app from the table above. Each section shows how to ask for permission, send the device token to your backend, and report when someone taps a notification.
Android (Kotlin)
Add Firebase
In Firebase, add your Android app with its package name, download google-services.json, and put it in your app module (usually app/).
// settings.gradle.kts or the root build.gradle.kts
plugins {
id("com.google.gms.google-services") version "4.5.0" apply false
}
// app/build.gradle.kts
plugins {
id("com.google.gms.google-services")
}
dependencies {
implementation(platform("com.google.firebase:firebase-bom:34.19.0"))
implementation("com.google.firebase:firebase-messaging")
}Declare the notification permission and your messaging service in AndroidManifest.xml:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application>
<service
android:name=".BentoMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>Create notification channels
Android 8 and later shows notifications only in a channel. Create your channels when the app starts. A campaign can pick a channel by its channel_id. If the app has no channel with that ID, FCM uses its default channel.
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel("general", "General", NotificationManager.IMPORTANCE_DEFAULT)
)
manager.createNotificationChannel(
NotificationChannel("promotions", "Promotions", NotificationManager.IMPORTANCE_DEFAULT)
)
}
}
}Register the device
The app generates an installation ID once and keeps it, then sends the token and permission to your backend. MyBackend.send stands in for your own API client, which adds your login session.
object BentoPush {
fun installationId(context: Context): String {
val prefs = context.getSharedPreferences("push", Context.MODE_PRIVATE)
return prefs.getString("installation_id", null)
?: UUID.randomUUID().toString().also { prefs.edit().putString("installation_id", it).apply() }
}
fun sync(context: Context) {
FirebaseMessaging.getInstance().token.addOnSuccessListener { token -> register(context, token) }
}
fun register(context: Context, token: String) {
val enabled = NotificationManagerCompat.from(context).areNotificationsEnabled()
MyBackend.send("POST", "/me/push-device", mapOf(
"installation_id" to installationId(context),
"token" to token,
"platform" to "android",
"permission" to if (enabled) "granted" else "denied",
"app_version" to context.packageManager.getPackageInfo(context.packageName, 0).versionName,
"os_version" to Build.VERSION.RELEASE,
"locale" to Locale.getDefault().toLanguageTag(),
"timezone" to TimeZone.getDefault().id,
))
}
fun unregister(context: Context) {
MyBackend.send("DELETE", "/me/push-device?installation_id=${installationId(context)}&platform=android")
}
fun reportOpen(openToken: String) {
MyBackend.send("POST", "/me/push-opens", mapOf("open_token" to openToken))
}
}On Android 13 and later, ask for the notification permission, then sync. Sync on every launch too, so Bento has the current token and permission.
class MainActivity : AppCompatActivity() {
private val requestNotifications =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { BentoPush.sync(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) {
requestNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
} else {
BentoPush.sync(this)
}
handlePushTap(intent)
}
}Show notifications and buttons
When the app is in the foreground, FCM calls onMessageReceived and your app builds the notification. This service shows bento_subtitle as sub text, uses BigTextStyle when bento_style is big_text, and adds a button for each entry in bento_actions. It also re-registers when FCM issues a new token.
class BentoMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
BentoPush.register(applicationContext, token)
}
override fun onMessageReceived(message: RemoteMessage) {
val notification = message.notification ?: return
val payload = message.data
val notificationId = System.currentTimeMillis().toInt()
val builder = NotificationCompat.Builder(this, notification.channelId ?: "general")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(notification.title)
.setContentText(notification.body)
.setAutoCancel(true)
.setContentIntent(tapIntent(payload, notificationId))
payload["bento_subtitle"]?.let { builder.setSubText(it) }
if (payload["bento_style"] == "big_text") {
builder.setStyle(NotificationCompat.BigTextStyle().bigText(notification.body))
}
payload["bento_actions"]?.let { json ->
val actions = JSONArray(json)
for (i in 0 until actions.length()) {
val action = actions.getJSONObject(i)
val extras = payload + ("bento_url" to action.optString("url"))
builder.addAction(0, action.getString("title"), tapIntent(extras, notificationId + i + 1))
}
}
getSystemService(NotificationManager::class.java).notify(notificationId, builder.build())
}
private fun tapIntent(extras: Map<String, String>, requestCode: Int): PendingIntent {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
extras.forEach { (key, value) -> putExtra(key, value) }
}
return PendingIntent.getActivity(
this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
}
}When the app is in the background, FCM shows the notification in the system tray itself. In that case bento_subtitle and big_text are not applied, and tapping the notification opens your launcher activity with the data keys as intent extras.
Handle taps
Both paths deliver the data as intent extras, so one handler covers them. Add this to MainActivity:
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handlePushTap(intent)
}
private fun handlePushTap(intent: Intent) {
val openToken = intent.getStringExtra("bento_open_token") ?: return
intent.removeExtra("bento_open_token")
BentoPush.reportOpen(openToken)
intent.getStringExtra("bento_url")?.takeIf { it.isNotEmpty() }?.let { url ->
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
}Removing the extra stops the same open from being reported again when the activity is recreated, such as after a rotation.
Revoke on logout
Call this before you clear the login session:
BentoPush.unregister(context)iOS (Swift) through Firebase
Add GoogleService-Info.plist to your app, add the FirebaseMessaging package, and complete step 4. Firebase gives you an FCM registration token, which is what you send to Bento with platform set to ios.
import FirebaseCore
import FirebaseMessaging
import UIKit
import UserNotifications
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
return true
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
Messaging.messaging().apnsToken = deviceToken
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
guard let fcmToken else { return }
BentoPush.register(token: fcmToken)
}
}BentoPush.register is the same helper as in the APNs guide. Your backend should use the FCM credential ID for these devices. You can also fetch the current token at any time with Messaging.messaging().token { token, error in ... }.
Taps work the same as with APNs: read bento_open_token and bento_url in userNotificationCenter(_:didReceive:withCompletionHandler:). See Handle taps and buttons.
Buttons and images also work through Firebase. Notifications with buttons use the BENTO_ACTIONS category and carry bento_actions, as with APNs. The image arrives in fcm_options.image instead of bento_image_url, so read that key in your Notification Service Extension.
React Native
Use @react-native-firebase/app and @react-native-firebase/messaging. Add google-services.json and GoogleService-Info.plist as the React Native Firebase docs describe.
import { PermissionsAndroid, Platform } from 'react-native';
import {
AuthorizationStatus,
getInitialNotification,
getMessaging,
getToken,
onNotificationOpenedApp,
onTokenRefresh,
requestPermission,
} from '@react-native-firebase/messaging';
const messaging = getMessaging();
async function askPermission() {
if (Platform.OS === 'android') {
if (Platform.Version < 33) return 'granted';
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
return result === PermissionsAndroid.RESULTS.GRANTED ? 'granted' : 'denied';
}
const status = await requestPermission(messaging);
switch (status) {
case AuthorizationStatus.AUTHORIZED: return 'granted';
case AuthorizationStatus.PROVISIONAL: return 'provisional';
case AuthorizationStatus.DENIED: return 'denied';
case AuthorizationStatus.NOT_DETERMINED: return 'not_determined';
default: return 'unknown';
}
}
// myBackend is your own API client. getInstallationId returns an ID you generate once and store.
async function registerDevice(token, permission) {
await myBackend.post('/me/push-device', {
installation_id: await getInstallationId(),
token,
platform: Platform.OS,
permission,
});
}
function reportOpen(remoteMessage) {
const openToken = remoteMessage?.data?.bento_open_token;
if (openToken) myBackend.post('/me/push-opens', { open_token: openToken });
// Open remoteMessage.data.bento_url with your navigation or Linking.openURL.
}
export async function setUpPush() {
const permission = await askPermission();
await registerDevice(await getToken(messaging), permission);
onTokenRefresh(messaging, (token) => registerDevice(token, permission));
onNotificationOpenedApp(messaging, reportOpen);
reportOpen(await getInitialNotification(messaging));
}onNotificationOpenedApp fires when a tap brings the app from the background. getInitialNotification returns the notification that launched the app from a closed state.
Recent versions of React Native Firebase mark requestPermission as deprecated in favour of react-native-permissions. It still works, and you can swap in requestNotifications from react-native-permissions without changing the rest.
Flutter
Use the firebase_core and firebase_messaging packages, configured with flutterfire configure.
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
final messaging = FirebaseMessaging.instance;
String bentoPermission(AuthorizationStatus status) => switch (status) {
AuthorizationStatus.authorized => 'granted',
AuthorizationStatus.provisional => 'provisional',
AuthorizationStatus.denied => 'denied',
AuthorizationStatus.notDetermined => 'not_determined',
};
// myBackend is your own API client. getInstallationId returns an ID you generate once and store.
Future<void> registerDevice(String token, String permission) async {
await myBackend.post('/me/push-device', {
'installation_id': await getInstallationId(),
'token': token,
'platform': Platform.isIOS ? 'ios' : 'android',
'permission': permission,
});
}
void reportOpen(RemoteMessage message) {
final openToken = message.data['bento_open_token'];
if (openToken != null) myBackend.post('/me/push-opens', {'open_token': openToken});
// Open message.data['bento_url'] with your router or url_launcher.
}
Future<void> setUpPush() async {
final settings = await messaging.requestPermission();
final permission = bentoPermission(settings.authorizationStatus);
// On iOS, FCM needs the APNs token before it can issue its own token.
if (Platform.isIOS && await messaging.getAPNSToken() == null) return;
final token = await messaging.getToken();
if (token != null) await registerDevice(token, permission);
messaging.onTokenRefresh.listen((token) => registerDevice(token, permission));
FirebaseMessaging.onMessageOpenedApp.listen(reportOpen);
final initial = await messaging.getInitialMessage();
if (initial != null) reportOpen(initial);
}On iOS the APNs token can arrive a moment after launch. If getAPNSToken returns null, call setUpPush again shortly or on the next launch.
On Android, requestPermission asks for POST_NOTIFICATIONS on Android 13 and later. Create your Android notification channels natively (see Create notification channels under Android (Kotlin)) or with a package such as flutter_local_notifications.
Expo
Expo apps use expo-notifications. Push tokens need a development build or a store build. Expo Go does not support them.
getDevicePushTokenAsync(), not the Expo push token from getExpoPushTokenAsync().On Android the native token is an FCM token, so use an FCM credential. On iOS it is an APNs token, so use an APNs credential for iOS devices.
For Android, set android.googleServicesFile in your app config to your google-services.json.
import { useEffect } from 'react';
import { Platform } from 'react-native';
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleNotification: async () => ({ shouldShowBanner: true, shouldShowList: true, shouldPlaySound: true, shouldSetBadge: false }),
});
function bentoPermission(permissions) {
if (permissions.ios?.status === Notifications.IosAuthorizationStatus.PROVISIONAL) return 'provisional';
if (permissions.status === 'granted') return 'granted';
if (permissions.status === 'denied') return 'denied';
return 'not_determined';
}
// myBackend is your own API client. getInstallationId returns an ID you generate once and store.
async function registerDevice(token, permission) {
await myBackend.post('/me/push-device', {
installation_id: await getInstallationId(),
token,
platform: Platform.OS,
permission,
});
}
function reportOpen(response) {
const data = response?.notification.request.content.data ?? {};
if (data.bento_open_token) myBackend.post('/me/push-opens', { open_token: data.bento_open_token });
// Open data.bento_url with your router or Linking.openURL.
}
export async function setUpPush() {
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('promotions', {
name: 'Promotions',
importance: Notifications.AndroidImportance.DEFAULT,
});
}
const permission = bentoPermission(await Notifications.requestPermissionsAsync());
const { data: token } = await Notifications.getDevicePushTokenAsync();
await registerDevice(token, permission);
reportOpen(await Notifications.getLastNotificationResponseAsync());
}
export function usePushListeners() {
useEffect(() => {
const tokenSubscription = Notifications.addPushTokenListener(({ data }) => registerDevice(data, 'granted'));
const responseSubscription = Notifications.addNotificationResponseReceivedListener(reportOpen);
return () => {
tokenSubscription.remove();
responseSubscription.remove();
};
}, []);
}The token listener assumes permission is still granted, since a new token only matters for a device that can receive pushes. For iOS, the backend should pick the APNs credential for the build's environment, as described in Sandbox and production.
Step 6: Send a test
Once your app has registered a device, send yourself a test push. You can do this in two places:
- The last step of the Set up push guide, Send a test.
- Send a test on any push campaign.
Enter the subscriber email the device was registered with. If nothing arrives, check Troubleshooting.
Troubleshooting
These are the most common problems and how to fix them:
| Problem | Cause | Fix |
|---|---|---|
SENDER_ID_MISMATCH | The token was issued for a different Firebase project than the service account. | Use a service account from the same project as the app's google-services.json or GoogleService-Info.plist. |
UNREGISTERED | The app was uninstalled or the token expired. | Nothing to do. Bento stops sending to that device, and the app registers a fresh token on its next launch. |
| Bento says Firebase rejected the credentials | The key was revoked or deleted in Google Cloud, or the Firebase Cloud Messaging API is disabled. | Enable the API (see step 2), generate a new key, and save it in Bento. |
| iOS devices through FCM get nothing | Firebase has no APNs key, or the app lacks the Push Notifications capability. | Upload the APNs key to Firebase (see step 4) and add the capability in Xcode. |
| Subtitle or big text missing on Android | The app was in the background, so FCM showed the notification itself. | This is expected. The title, body, and tap still work. |
422 "Check the subscriber's email address or uuid." | The visitor_id isn't a subscriber on this site, or the email or uuid isn't valid. | Register with the subscriber's email or uuid. Bento adds them if they're new. |
For APNs errors such as BadDeviceToken on Expo iOS devices, see APNs troubleshooting.