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);
}
}
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;
}