我一直在阅读有关如何获取承载访问令牌的谷歌文档,但我已经好几个星期都无法获取它了,但我终于做到了。用访问令牌替换服务器密钥的部分在文档中并不明确... GitHubLink
希望这也能为您节省一些时间。
确保您已安装所有这些
firebase_消息传递,
firebase_核心,
http
googleapis_auth
另外,从 cloud firestore 下载服务帐户文件...
static Future<void> sendNotificationToTopicAllToSee(String title,
String description, String topicTOSubscribe) async {
try {
String? accessToken = await generateFCMAccessToken();
var notification = {
"message": {
"notification": {
'title': title,
'body': description,
},
'data': <String, String>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
},
"topic": topicTOSubscribe,
}
};
if(token != null){
// Send the notification
final response = await http.post(
Uri.parse(
'https://fcm.googleapis.com/v1/projects/REPLACE_WITH_PROJECT_NAME/messages:send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'Bearer $accessToken',
},
body: jsonEncode(notification),
);
}else{
print("Token is empty/null);
}
if (response.statusCode == 200) {
print('Notification sent successfully');
} else {
print('Failed to send notification: ${response.body}');
}
} catch (e) {
print('Error sending notification: $e');
}
}
**Get the bearer access token**
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 "";
}
当我测试并运行它时,上面的实现工作正常。如果您有更好的方法,请随时改进代码。