Firebase Cloud Messaging not working for programmatically sent messages using Python

Question:

If I go into my firebase console and setup a campaign my end devices receive the notification just fine, but for messages to specific devices using the device’s registration token, sent from django/python, I get no notification on my mobile devices.

Not sure if this matters but my app is still in development, it is not in production, so if this matters please let me know.

My frontend is flutter, here is the flutter code I am using to get the registration token and send it to the backend:

Future<StreamedResponse> AddProductPut(context, pk, name, quantity, cost, selling, XFile? chosenImage) async {
  String id_token = await FirebaseAuth.instance.currentUser!.getIdToken();
  late String? fcm_token;
  await FirebaseMessaging.instance.getToken().then((token) async {
    fcm_token = token!;
  }).catchError((e) {
    print(e);
  });
  print(fcm_token);
  var url = backend + "/pm/createproduct/" + pk.toString() + "/";
  var request = http.MultipartRequest('PUT', Uri.parse(url));
  print("FCM TOKEN");
  print(fcm_token);
  request.headers["Authorization"] = "Token " + id_token;
  request.fields["name"] = name;
  request.fields["quantity"] = quantity.toString();
  request.fields["cost_price"] = cost.toString();
  request.fields["selling_price"] = selling.toString();
  request.fields["barcode"] = "11111";
  request.fields["token"] = fcm_token!;
  request.files.add(
      await http.MultipartFile.fromPath(
          'image',
          chosenImage!.path
      )
  );

  return await request.send();
}

Here is the python code in my django serializer to send the notification message:

registration_token = self.context['request'].data["token"],
        print(registration_token[0])
        print(type(registration_token[0]))
        # See documentation on defining a message payload.
        message = Message(
            notification=Notification(
                title='New Product Added',
                body='A new product called ' + validated_data['name'] + ' has been added to your account.',
            ),
            token=registration_token[0]
        )

        # Send a message to the device corresponding to the provided
        # registration token.
        response = send(message)
        print(response)

I am not getting any errors in my django/python console when sending this message, and response prints something like this:

projects/<project name>/messages/16641.......0329

My registration token is something like this:

cmLYCAbL0EsJrxppKzXvhF:APA..............qdt5ySYLbkQC_bpqwL6RdCwSzK_tX8iclp-e0QZB................lgw9g2eFNzfXpn2C4U................UnMphyWa6L9d-wUg
Asked By: kbessemer

||

Answers:

Not sure what the problem is, but I am receiving FCM messages on Apple and Android now…

            registration_token = subuser.fcm
            print(registration_token)
            message = Message(
                notification=Notification('Added As A Sub-User', f'A user with the phone {instance.userprofile.phone} has added you to their account as a sub user.'),
                token=registration_token
            )

and my flutter code that updates the database with the user’s fcm registration token…

    FirebaseMessaging.instance.getToken().then((token) async {
      print(token);
      String id_token = await FirebaseAuth.instance.currentUser!.getIdToken();
      String uid = await FirebaseAuth.instance.currentUser!.uid;
      final result = await http.put(
        Uri.parse(backend + "/pm/setfcm/" + uid + "/"),
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Token " + id_token
        },
        body: jsonEncode({
          "fcm": token,
        })
      );
    }).catchError((e) {
      print(e);
    });

    FirebaseMessaging.instance.onTokenRefresh.listen((newToken) async {
      print(newToken);
      String id_token = await FirebaseAuth.instance.currentUser!.getIdToken();
      String uid = await FirebaseAuth.instance.currentUser!.uid;
      final result = await http.put(
          Uri.parse(backend + "/pm/setfcm/" + uid + "/"),
          headers: {
            "Content-Type": "application/json",
            "Authorization": "Token " + id_token
          },
          body: jsonEncode({
            "fcm": newToken,
          })
      );

    });

            response = send(message)
            print(response)
Answered By: kbessemer