You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Firebase Cloud Messaging实现打车APP的司机订单通知及超时转派?

Implementing Firebase Cloud Messaging (FCM) for Your Ride-Hailing App

Hey Jennifer, awesome progress on getting the passenger request and nearby driver assignment sorted with Firebase Database! Let's break down exactly how to add FCM push notifications to alert drivers when a ride request comes in, including that critical 15-second acceptance window.

Step 1: Prep Driver Devices & Store FCM Tokens

First, make sure every driver's app is set up to receive FCM notifications:

  • On the driver's app, when they log in, fetch their unique FCM device token using the platform-specific SDK (e.g., FirebaseMessaging.getInstance().getToken() for Android, Messaging.messaging().token() for iOS).
  • Save this token directly to your Firebase Database, linked to the driver's profile (alongside their location, availability status, and other key details). You’ll need these tokens to target specific drivers later.

Step 2: Trigger Notifications via Firebase Cloud Functions

The most secure and scalable way to handle notification logic is with Firebase Cloud Functions (avoids exposing sensitive driver data or FCM logic on the client). Here’s how to hook it into your existing ride request workflow:

Example Cloud Function (Node.js)

This function triggers automatically when a new ride request is added to your Database, fetches nearby drivers, sends notifications, and handles the 15-second timeout:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.sendRideRequestAlerts = functions.database.ref('/ride-requests/{requestId}')
  .onCreate(async (snapshot, context) => {
    const requestData = snapshot.val();
    const requestId = context.params.requestId;
    const passengerLoc = requestData.passengerLocation;

    // 1. Fetch your pre-filtered 5km-range drivers (reuse your existing assignment logic)
    const driversRef = admin.database().ref('/drivers');
    const driverSnapshot = await driversRef.orderByChild('availability').equalTo(true).once('value');
    const nearbyDrivers = filterDriversWithin5km(driverSnapshot.val(), passengerLoc);

    // 2. Collect valid FCM tokens from these drivers
    const driverTokens = nearbyDrivers
      .map(driver => driver.fcmToken)
      .filter(token => token !== null && token !== undefined);

    // 3. Build the FCM notification payload
    const payload = {
      notification: {
        title: "New Ride Request!",
        body: "You have 15 seconds to accept a nearby ride.",
        clickAction: "OPEN_RIDE_REQUEST_SCREEN" // Tells the app which screen to launch
      },
      data: {
        requestId: requestId,
        passengerLat: passengerLoc.lat.toString(),
        passengerLng: passengerLoc.lng.toString(),
        countdown: "15"
      }
    };

    // 4. Send notifications to target drivers
    if (driverTokens.length > 0) {
      await admin.messaging().sendToDevice(driverTokens, payload);
      functions.logger.log(`Sent alerts to ${driverTokens.length} nearby drivers`);
    }

    // 5. 15-second timeout to check if request was accepted
    setTimeout(async () => {
      const updatedRequest = await admin.database().ref(`/ride-requests/${requestId}`).once('value');
      const requestStatus = updatedRequest.val().status;

      // If still pending, trigger notification to next batch of drivers
      if (requestStatus === "pending") {
        functions.logger.log("Request not accepted in 15s — alerting additional drivers");
        // Add your logic to fetch next driver batch and repeat notification flow
      }
    }, 15000); // 15 seconds in milliseconds
  });

// Reuse your existing distance calculation helper
function filterDriversWithin5km(drivers, passengerLoc) {
  return Object.values(drivers).filter(driver => {
    const distance = calculateHaversineDistance(driver.location, passengerLoc);
    return distance <= 5; // 5km threshold
  });
}

function calculateHaversineDistance(driverLoc, passengerLoc) {
  // Implement your Haversine formula logic here
}

Step 3: Handle Notifications on the Driver’s App

On the driver’s side, you’ll need to:

  • Listen for incoming FCM notifications. When one arrives, display a prominent alert with a 15-second countdown and an "Accept" button.
  • When the driver taps "Accept", immediately update the ride request’s status in Firebase Database to accepted and link their driver ID to the request. This will stop the timeout from triggering further notifications.
  • If the countdown expires without acceptance, dismiss the alert and optionally mark the driver as having missed the request.

Step 4: Secure the Workflow

  • Use Firebase Database security rules to ensure only authenticated drivers can update ride request statuses.
  • Validate driver tokens and user IDs in your Cloud Function to prevent unauthorized notification targeting.
  • Limit the number of drivers notified per batch to avoid spamming too many users at once.

That covers the core implementation! Feel free to tweak the payload, timeout logic, or driver filtering to match your app’s exact needs.

内容的提问来源于stack exchange,提问作者Jennifer26

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:04:53