简体   繁体   中英

Firebase fail receiving notification from php

I can succesfully recive notifications from Firebase console, but when I call the PHP function to do it, doesn't recive anything. As I saw on internet, this is more less how I can send these notifications. And what I don't understand what is different when I switch to Firebase console (because it works from there). I don't think the problem is from my app, because I send a request to their server and then they should send to my device. It is very possible to make a mistake, please don't be too rude. I am still a beginner. Thank you for your wise answers!

PHP function

function push_notification_android($device_id,$message){

    //API URL of FCM
    $url = 'https://fcm.googleapis.com/fcm/send';


    $api_key = 'MY_KEY';
                
    $fields = array (
        'to' => $device_id,
        'data' => array(
                "message" => $message,
                "id" => '1',
        ),
    );

    //header includes Content type and api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization: key='.$api_key
    );
                
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);

    curl_close($ch);
    echo $result;
    return $result;
}

{"multicast_id":7370520341381062896,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1611404485967655%6b34551f6b34551f"}]}

By documentation you can send two types of messages to clients:

Notification messages - handled by the FCM SDK automatically.

Data messages - handled by the client app.

If you want to send data message implement your FirebaseMessagingService like this (this is only example what to do, you can use it but improve it with your needs and also test all possible solution to understand how that works)

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            handleDataMessage(remoteMessage.getData());
        }else if (remoteMessage.getNotification() != null) {
            //remove this line if you dont need or improve...
            sendNotification(100, remoteMessage.getNotification().getBody());
        }
    }

    private void handleDataMessage(Map<String, String> data) {
        if(data.containsKey("id") && data.containsKey("message")){
            String message = data.get("message");
            int id;
            try {
                id = Integer.parseInt(data.get("id"));
            }catch (Exception e){
                e.printStackTrace();
                id = 1; // default id or something else for wrong id from server
            }

            sendNotification(id, message);
        }
    }


    private void sendNotification(int id, String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT);
        String channelId = "appChannelId"; //getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon) //TODO set your icon
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.iconpro_round)) //TODO set your icon
                        .setContentTitle("MyApp")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
        if (notificationManager != null) {
            notificationManager.notify(id, notificationBuilder.build());
        }
    }
}

@adnandann's answer explains the reason indeed: you're sending a data message, while the Firebase console always sends a notification message (which is automatically displayed by the operation system).

So you have two options:

  1. Display the data message yourself, which @adnandann's answer shows how to do.

  2. Send a notification message from your PHP code, which you can do with:

     $fields = array ( 'to' => $device_id, 'notification' => array( "title" => "New message from app", "body" => $message ), );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM