2

这是我尝试发送数据消息 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.带休息api

def send_fcm_with_rest(tokens, title=None, body=None, image=None, data_message=None):
    headers = {
        'Content-Type': 'application/json',
        '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。

我尝试从邮递员发送,从邮递员那里收到 fcm 在 Andriod 端。谁能告诉我我的代码有什么问题?

4

2 回答 2

1

您的代码没问题,但是您应该使用flask==1.1.2版本,因为它是稳定版本。

于 2020-11-25T17:46:49.617 回答
0

三种发送 fcm 的方法都是正确的,后来我们发现是前端的问题。因此,任何人都可以根据需要使用这三种方法。

于 2020-11-25T18:18:31.183 回答