Code to send Push Notification (PHP to Android)
A push notification is a message that is sent from a server to a mobile device through a push notification service. The purpose of a push notification is to alert the user of a mobile app to a specific event or action that requires their attention, even when the app is not actively in use.
Push notifications can take many forms, such as text messages, images, sounds, and badges, and they can contain various types of information, including news updates, reminders, promotions, and other types of personalized content.
Push notifications are a powerful tool for engaging with mobile app users and can help increase user retention, drive app usage, and improve user experience. However, it’s important to use push notifications judiciously and ensure that they provide value to the user, as too many notifications or irrelevant notifications can lead to users disabling push notifications for your app or even uninstalling it altogether.
We can easily send data payload via push notification. For this we need to have legacy server key.
This function can be used to send push notification to android client.
function sendPushNotification($registrationIDs = null, $data) { $encodedData = json_encode($data); if (!$encodedData) {return;} //$toKey = 'registration_ids'; $toKey = 'to'; //$toValue = $registrationIDs;//["id1","id2"] $toValue = '/topics/all'; $fields = array( $to => $toValue, 'data' => array('data' => $encodedData), ); $encodedFields = json_encode($fields, JSON_UNESCAPED_UNICODE); // legacy key from https://console.firebase.google.com/project/mproject/settings/cloudmessaging/android:package_name $serverKey =oCQ:APA91bEAo8eK3tox4g_qqocGy7ddvEy60rtqoUHqczOguq3YtZGHO2msvDWSKwjAY49FdtSTQztnAgdls1Ho4CQVK_gWIC7cmF; $path_to_firebase_cm = 'https://fcm.googleapis.com/fcm/send'; $headers = array( 'Authorization:key=' . $serverKey, 'Content-Type:application/json', ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $path_to_firebase_cm); 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_IPRESOLVE, CURL_IPRESOLVE_V4); curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedFields); $result = curl_exec($ch); curl_close($ch); return $result; }