如何在DART中生成访问令牌以发送Firebase推送通知? 我正在使用DART将推动通知从我的Flutter应用程序发送到Firebase Cloud Messaging(FCM)设备。要通过FCM发送通知,我需要使用携带者来验证我的请求...

问题描述 投票:0回答:1

import 'dart:convert'; import 'dart:io'; import 'package:googleapis_auth/googleapis_auth.dart' as auth; import 'package:http/http.dart' as http; // Load the service account key file Future<auth.AccessCredentials> getAccessToken() async { final serviceAccount = File('path/to/service-account.json'); // Set correct path final serviceJson = jsonDecode(await serviceAccount.readAsString()); final credentials = auth.ServiceAccountCredentials.fromJson(serviceJson); final client = http.Client(); final accessCredentials = await auth.obtainAccessCredentialsViaServiceAccount( credentials, ['https://www.googleapis.com/auth/firebase.messaging'], client, ); client.close(); return accessCredentials; } // Send FCM notification Future<void> sendPushNotification() async { final accessCredentials = await getAccessToken(); final accessToken = accessCredentials.accessToken.data; final response = await http.post( Uri.parse('https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send'), headers: { 'Authorization': 'Bearer $accessToken', 'Content-Type': 'application/json', }, body: jsonEncode({ "message": { "token": "DEVICE_FCM_TOKEN", "notification": { "title": "Hello", "body": "This is a test notification" } } }), ); print(response.body); } void main() async { await sendPushNotification(); }
最好不要那样做。最好通过云功能发送推送通知。它可以完美地工作

const functions = require('firebase-functions/v2'); const notifications = require('../services/notification'); const DEBUG_MODE = false; /** * Callable function: Sends notifications to a list of users by their user IDs. */ exports.sendNotification = functions.https.onCall(async (request) => { const data = request.data; if (!data.members || !data.title || !data.message) { return { code: 103, message: "Missing required fields: members or message" }; } const notification = { title: data.title, body: data.message, image: data.image || '', type: data.parentType || '', parentID: data.parentID || '', childID: data.childID || '', options: data.options ? JSON.stringify(data.options) : '{}', }; try { switch (data.handler) { default: await notifications.sendToUserTokens(data.tokens, notification); break; } return { code: 100, message: "Notifications sent successfully" }; } catch (error) { if (DEBUG_MODE) console.error("Error sending notifications:", error); return { code: 103, message: error.message }; } }); /** * Sends a notification to a list of user Tokens. * & sends the notification payload. */ async function sendToUserTokens(tokens, data) { try { // functions.logger.info(`Collected FCM tokens: ${ tokens }`); const response = await messaging.sendEachForMulticast({ tokens: tokens, notification: { title: data.title, body: data.body, }, data: { type: data.type || '', parentID: data.parentID || '', childID: data.childID || '', options: data.options || '{}', image: data.image || '', }, android: { priority: 'high', notification: { sound: 'default', icon: 'default', channel_id: 'high_importance_channel', } }, apns: { payload: { aps: { contentAvailable: true, sound: 'default', }, }, headers: { 'apns-topic': 'io.flutter.plugins.firebase.messaging', 'apns-push-type': 'alert', 'apns-priority': '10', }, }, }); // functions.logger.info(`Notifications sent successfully ${response.successCount}`); } catch (error) { functions.logger.error('Error fetching tokens or sending notifications:', error); } }

flutter firebase push-notification firebase-cloud-messaging bearer-token
1个回答
0
投票
  Future<Map> fcmNotify({required FcmNotification data}) async {
    String callable = 'notificationFunctions-sendNotification';
    Map fcmData = data.toMap();
    Map result = {};

    // Console.json("FCM", fcmData);
    await FirebaseFunctions.instance
        .httpsCallable(callable)
        .call(fcmData.stringValuesOnly)
        .then((response) => result = response.data)
        .catchError((error) => result = {'type': 'error', 'data': '$error'});

    return result;
  }

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.