我正在尝试使用此 REST API 向设备令牌发送通知,但未发送通知。 也许令牌是错误的? 我不确定访问不记名令牌是否错误。请帮助我。
当用户使用按钮时,会立即调用 sendNotificationForTesting 方法。
static Future<void> sendNotificationForTesting(String deviceToken) async {
try {
// Retrieve the access token
String? token = await getAccessToken();
// Ensure token is not null before proceeding
if (token != null) {
// Make HTTP POST request to send notification
await http.post(
Uri.parse(
'https://fcm.googleapis.com/v1/projects/academy/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $token' // Use the retrieved token here
},
body: jsonEncode(<String, dynamic>{
"message": {
"token": deviceToken,
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"data": {"id": "1"},
"android": {
"notification": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
},
},
}
}),
);
// Notification sent successfully
Fluttertoast.showToast(
backgroundColor: Colors.green,
msg: "Notification sent successfully",
textColor: Colors.white,
);
} else {
// Handle case where access token is null
Fluttertoast.showToast(
backgroundColor: Colors.red,
msg: "Access token is null",
textColor: Colors.white,
);
}
} catch (e) {
// Handle any errors that occur during the process
print("Failed to send Notification for testing: $e");
Fluttertoast.showToast(
backgroundColor: Colors.red,
msg: "Failed to send notification: ${e.toString()}",
textColor: Colors.white,
);
} }
这是我在登录应用程序时使用电子邮件和密码从登录用户那里获取不记名访问令牌的代码。
static Future<String?> getAccessToken() async {
try {
// Get the current user
User? user = _auth.currentUser;
// Check if the user is signed in
if (user != null) {
// Get the access token for the user
final idTokenResult = await user.getIdToken();
accessToken = idTokenResult!;
return accessToken;
} else {
// User is not signed in
return null;
}
} catch (e) {
// Handle any errors that occur during the process
print("Error getting access token: $e");
return null;
} }
希望这也能为您节省一些时间。
确保您已安装所有这些 firebase_messaging, firebase_core,http googleapis_auth
此外,按照以下步骤从 cloud firestore 下载服务帐户文件...
导航到 Cloud Firebase 上的项目
选择齿轮图标(项目设置)
选择服务帐户选项卡
生成文件 5.在本地电脑或机器上找到文件
最后,使用这些变量并填充 getAccessToken 方法上的“FILL_UP”占位符
static Future<String> generateFCMAccessToken() async {
try {
/* get these details from the file you downloaded(generated)
from firebase console
*/
String type = "FILL_UP";
String project_id = "FILL_UP";
String private_key_id = "FILL_UP";
String private_key = "FILL_UP";
String client_email = "FILL_UP";
String client_id = "FILL_UP";
String auth_uri = "FILL_UP";
String token_uri = "FILL_UP";
String auth_provider_x509_cert_url = "FILL_UP";
String client_x509_cert_url = "FILL_UP";
String universe_domain = "FILL_UP";
final credentials = ServiceAccountCredentials.fromJson({
"type": type,
"project_id": project_id,
"private_key_id": private_key_id,
"client_email": client_email,
"private_key": private_key,
"client_id": client_id,
"auth_uri": auth_uri,
"token_uri": token_uri,
"auth_provider_x509_cert_url": auth_provider_x509_cert_url,
"client_x509_cert_url": client_x509_cert_url,
"universe_domain": universe_domain
});
List<String> scopes = [
"https://www.googleapis.com/auth/firebase.messaging"
];
final client = await obtainAccessCredentialsViaServiceAccount(
credentials, scopes, http.Client());
final accessToken = client;
Timer.periodic(const Duration(minutes: 59), (timer) {
accessToken.refreshToken;
});
return accessToken.accessToken.data;
} catch (e) {
Reuse.logger.i("THis is the error: $e");
}
return "";
}