0

I'm trying to create a push notification using PHP. I have created my firebase account and add what's needs to be add in my android app. I tested it by using the firebase console and it receives the notification.

Now I'm trying to create a push notification using PHP below is my code

 $apiKey = "apikey"; //Server Key Legacy
 $fcmUrl = 'https://fcm.googleapis.com/fcm/send';
 $token= 'singletoken';

 $notification = array('title' =>'test title',
                       'body' => 'hello message');

 $notifdata = array('title' =>'test title data',
                     'body' => 'hello',
                     'image' => 'path'
              );

 $fcmNotification = array (
                        'to'        => $token, 
                        'notification' => $notification,
                        'data' => $notifdata 
                    );


                $headers = array( 'Authorization: key='.$apiKey, 'Content-Type: application/json');

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL,$fcmUrl);
                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($fcmNotification));
                $result = curl_exec($ch);
                curl_close($ch);

In my Login Activity, I use below code to get my register id

 FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( this,  new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            device_key = instanceIdResult.getToken();
            Log.e(TAG, device_key);
        }
    });

And here is my MyFirebaseMessagingService class

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
}

@Override
public void onMessageReceived(RemoteMessage message) {
    super.onMessageReceived(message);
    sendMyNotification(message.getNotification().getBody());
}


private void sendMyNotification(String message) {

    Intent intent = new Intent(this, NotificationActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    String channelId = "Default";


    Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("My App")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
        manager.createNotificationChannel(channel);
    }
    manager.notify(0, builder.build());

}

}

I'm receiving notifications on my Android Emulator but in the real device I don't receive any notification.

natsumiyu
  • 3,217
  • 7
  • 30
  • 54
  • what is the response code? if response code/status code is 200 the problem is in your NotificationService in android or else it is on your php – L2_Paver Sep 30 '19 at 09:09
  • what do you mean by response code? @L2_Paver the $result variable display nothing as well. – natsumiyu Sep 30 '19 at 09:10
  • I have example here but I use the topic to broadcast it to all subscriber to that topic. While you are using it to single Token only – L2_Paver Sep 30 '19 at 09:15
  • I have updated my question and it returns unauthorized message error 401 @L2_Paver – natsumiyu Sep 30 '19 at 09:18
  • 1
    did you use the Firebase Cloud Messaging Legacy server key not the Web API key? – L2_Paver Sep 30 '19 at 09:23
  • @L2_Paver I edit the api key I successfully received a notification in my emulator but in the real device it says that it has an error `InvalidRegistration` – natsumiyu Sep 30 '19 at 09:30
  • Try posting your android service code here and sufficient Logcat error logs. Every device and emulator have different token. – L2_Paver Sep 30 '19 at 09:33
  • if you want to broadcast your notification to all device, refer to this https://stackoverflow.com/questions/38237559/how-do-you-send-a-firebase-notification-to-all-devices-via-curl. gtg – L2_Paver Sep 30 '19 at 09:40
  • **[You should not switch off `CURLOPT_SSL_VERIFYHOST` or `CURLOPT_SSL_VERIFYPEER`](https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software)**. It could be a security risk! [Here is how to get the certificate bundle if your server is missing one](https://stackoverflow.com/a/32095378/1839439) – Dharman Oct 02 '19 at 22:40

1 Answers1

0

add error output before curl_close

echo curl_error($ch);
Salman Zafar
  • 3,844
  • 5
  • 20
  • 43
bars
  • 107
  • 5