以下是我尝试发送数据消息fcm的三种不同方式。
1.使用pyfcm
def send_fcm(fcm_tokens, title=None, body=None, data_message=None):
push_service = FCMNotification(api_key=app.config['FCM_KEY'])
try:
if type(fcm_tokens) is list:
print(fcm_tokens, data_message)
result = push_service.notify_multiple_devices(registration_ids=fcm_tokens, data_message=data_message)
print(result, '++++++++++++++', flush=True)
else:
print(fcm_tokens, 'single device', data_message)
result = push_service.notify_single_device(registration_id=fcm_tokens, data_message=data_message)
print(result, flush=True)
except errors.InvalidDataError as e:
print(e, flush=True)
2.使用firebase_admin sdk
def send_fcm_with_sdk(tokens, data_message=None):
if type(tokens) is list:
message = messaging.MulticastMessage(
data=data_message,
tokens=tokens, )
response = messaging.send_multicast(message)
print('{0} messages were sent successfully'.format(response.success_count), flush=True)
else:
message = messaging.Message(
data=data_message,
token=tokens,
)
print(message)
response = messaging.send(message)
print('Successfully sent message:', response)
3.使用rest api
def send_fcm_with_rest(tokens, title=None, body=None, image=None, data_message=None):
headers = {
'Authorization': 'key=xxxxxxxKEY',
'Content-Type': 'application/json'
}
url = 'https://fcm.googleapis.com/fcm/send'
if type(tokens) is list:
payload = {
"registration_ids": tokens,
"collapse_key": "type_a",
"data": data_message
}
else:
payload = {
"to": tokens,
"collapse_key": "type_a",
"data": data_message
}
print(json.dumps(payload))
resp = requests.post(url, headers=headers, data=json.dumps(payload))
print(resp.text.encode('utf8'), flush=True)
return resp
奇怪的是,它们三个都正确运行,并显示了一条成功消息,带有success_id,但在android端没有收到任何fcm。
我试着从POSTMAN发送,从邮递员那里,收到了安德里奥德一侧的fcm。有人能告诉我我的代码有什么问题吗?
您的代码还可以,但是您应该使用flask==1.1.2
版本,因为它是稳定版本。
发送fcm的三种方法都是正确的,后来我们发现这是前端人员的问题。因此,任何人都可以使用这三种方法,如果他们愿意的话