我有一个基于 Delphi 构建的后端服务器,我通过纯 HTTP 请求使用 Google FCM 推送通知服务。 Google 实施 FCM API HTTP V1 后,我的后端无法再发送推送通知。
根据我对文档和示例的审查,现在要向设备发送推送通知需要两个步骤:
获取不记名代币
在消息新端点请求的 HTTP POST 请求授权部分中使用此承载令牌: https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:发送
由于我只使用纯 HTTP 请求,并且我不打算用使用 FCM Admin SDK 的另一种语言构建代码。
HTTP API 中是否有任何端点可以获取 Bearer Token?或者有什么方法可以使用 API HTTP V1 发送推送通知而无需此 Bearer Token?
最后一个问题:是否可以在 Delphi 上使用 FCM Admin SDK?
您需要使用 service_account.json 生成访问令牌,您可以从 Firebase 控制台下载该令牌。
对于我的情况,我使用Python3作为后端,有3种发送通知的方式,我使用firebase_admin:
data = {
"title": "Notification title",
"body": "Description"
}
is_android = True
device_tokens = ["token1", "token2"]
if is_android:
message = messaging.MulticastMessage(
tokens=device_tokens,
data=data,
android=messaging.AndroidConfig(
data=data
),
)
else:
message = messaging.MulticastMessage(
notification=messaging.Notification(title=data.get("title"), body=data.get("body")),
tokens=device_tokens,
data={k: v for k, v in data.items() if k not in ("body", "title", "badge")},
apns=messaging.APNSConfig(
payload=messaging.APNSPayload(
aps=messaging.Aps(
content_available=True,
badge=1,
mutable_content=True,
custom_data=data,
alert=messaging.ApsAlert(
title=data.get("title"),
body=data.get("body")
)
),
custom_data=data
),
),
)
if data:
message.data = data
response = messaging.send_each_for_multicast(message)
from pyfcm import FCMNotification
fcm = FCMNotification(service_account_file="/location/to/project-firebase-admin-sdk.json", project_id="project-name")
result = fcm.notify(
fcm_token='device-token',
notification_title="Test",
notification_body="Test desc",
data_payload={
"payload_key1": "value123"
},
)
from google.oauth2 import service_account
import google.auth.transport.requests
def get_access_token():
credentials = service_account.Credentials.from_service_account_file(
"/location/to/project-firebase-admin-sdk.json", scopes=['https://www.googleapis.com/auth/firebase.messaging']
)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
return credentials.token
data = {
"message": {
"token": "device_token",
"data": {
"param1": "value",
},
"notification": {
"title": "Notification title",
"body": "Description",
},
"apns": {
"headers": {
"apns-priority": "10",
},
"payload": {
"aps": {
"mutable-content": 1,
"content_available": 1,
"contentAvailable": True,
},
"type": "feed",
"data": {
"title": "Notification title",
"body": "Description",
"type": "feed"
},
"content_available": True,
"priority": 'high',
"apns-priority": 10,
}
}
}
}
response = post("https://fcm.googleapis.com/v1/projects/>PROJECT_ID</messages:send", json=data, headers= {
"Content-Type": "application/json",
"Authorization": f"Bearer {get_access_token()}"
})
我认为生成访问令牌的最后一部分会对您有所帮助。 请记住,他们更改了发送的请求数据这里