Sending Firebase Cloud Messaging (FCM) push notifications using core PHP without a library involves constructing HTTP requests to Firebase Cloud Messaging servers. Here's a step-by-step guide on how to do it:
Step 1: Set Up Firebase Project
If you haven't already, create a Firebase project and configure it to allow FCM. Note down the Firebase Server Key, which you will need later.
Step 2: Create the PHP Script
Create a PHP script to send FCM notifications. You'll need to construct an HTTP POST request with the appropriate headers and payload.
<?php
// Your Firebase Server Key
$serverKey = 'YOUR_FIREBASE_SERVER_KEY';
// FCM API endpoint
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
// Recipient device token
$deviceToken = 'RECIPIENT_DEVICE_TOKEN';
// Notification payload
$data = [
'title' => 'Notification Title',
'body' => 'Notification Body',
];
// Construct the HTTP POST request
$headers = [
'Authorization: key=' . $serverKey,
'Content-Type: application/json',
];
$fields = [
'to' => $deviceToken,
'data' => $data,
];
$payload = json_encode($fields);
// Initialize cURL session
$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, $payload);
// Execute cURL session and close
$result = curl_exec($ch);
curl_close($ch);
// Handle the response
if ($result === false) {
echo 'FCM request failed: ' . curl_error($ch);
} else {
echo 'FCM notification sent successfully';
}
?>
Replace 'YOUR_FIREBASE_SERVER_KEY' with your actual Firebase Server Key and 'RECIPIENT_DEVICE_TOKEN' with the FCM token of the device you want to send the notification to. Also, customize the `data` array with your notification payload.
Step 3: Run the PHP Script
Execute your PHP script to send the FCM push notification. Ensure that your server has internet access to communicate with Firebase.
That's it! You've sent an FCM push notification using core PHP without a library. You can integrate this script into your web application or server-side logic to send notifications as needed.
0 Comments