Search code examples
pythonandroidflaskfirebase-cloud-messagingpyfcm

Sending fcm from PYTHON(flask) but not receiving on android side


Here are three different ways I try to send data message fcm.

1. With 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. With 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. With 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

The strange thing is all three of them run correctly and show a success message, with success_id, but none of fcm is received on the android side.

I tried sending from POSTMAN, and from postman, fcm are received on Andriod side. Can anyone please tell me what is the issue in my code?


Solution

  • All the three methods for sending fcm is correct, later we figure out it was the issue from the frontend guy. So anyone can use these three methods if they want to.