system/library/notification/push_notification.php
Вот содержимое файла system/library/notification/push_notification.php
:
<?php
// Push Notification Library for Task Manager - Handles sending push notifications
class PushNotification {
private $device_token;
private $message;
private $title;
private $server_key;
private $url = "https://fcm.googleapis.com/fcm/send"; // Firebase Cloud Messaging (FCM) endpoint
// Constructor to initialize the push notification parameters
public function __construct($device_token, $message, $title, $server_key) {
$this->device_token = $device_token;
$this->message = $message;
$this->title = $title;
$this->server_key = $server_key;
}
// Method to send push notification
public function sendPushNotification() {
// Prepare the payload for the push notification
$data = array(
'to' => $this->device_token,
'notification' => array(
'title' => $this->title,
'body' => $this->message,
'sound' => 'default',
'badge' => '1'
),
'priority' => 'high'
);
// Set up the headers
$headers = array(
'Authorization: key=' . $this->server_key,
'Content-Type: application/json'
);
// Initialize cURL to send the notification
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// Execute the cURL request and capture the response
$response = curl_exec($ch);
curl_close($ch);
// Return the response
return $response;
}
// Method to send task-related push notifications
public function sendTaskNotification($task_name, $device_token) {
$this->title = "Task Notification: " . $task_name;
$this->message = "You have a new task assigned to you: " . $task_name;
$this->device_token = $device_token;
return $this->sendPushNotification();
}
// Method to send task completion push notifications
public function sendTaskCompletionNotification($task_name, $device_token) {
$this->title = "Task Completed: " . $task_name;
$this->message = "The task " . $task_name . " has been completed successfully.";
$this->device_token = $device_token;
return $this->sendPushNotification();
}
// Method to send task reminder push notifications
public function sendTaskReminderNotification($task_name, $device_token, $reminder_time) {
$this->title = "Reminder: " . $task_name;
$this->message = "This is a reminder for your task: " . $task_name . ". The task is due at " . $reminder_time . ".";
$this->device_token = $device_token;
return $this->sendPushNotification();
}
// Method to send task overdue push notifications
public function sendTaskOverdueNotification($task_name, $device_token) {
$this->title = "Task Overdue: " . $task_name;
$this->message = "The task " . $task_name . " is overdue. Please take immediate action.";
$this->device_token = $device_token;
return $this->sendPushNotification();
}
// Method to send task status change push notifications
public function sendTaskStatusChangeNotification($task_name, $device_token, $new_status) {
$this->title = "Task Status Changed: " . $task_name;
$this->message = "The status of your task has been updated to: " . $new_status;
$this->device_token = $device_token;
return $this->sendPushNotification();
}
}
?>
Объяснение кода:
-
Класс
PushNotification
:-
Этот класс используется для отправки push-уведомлений с использованием Firebase Cloud Messaging (FCM). Уведомления отправляются пользователям на их устройства, например, о новых задачах, напоминаниях, завершении задач и т. д.
-
-
Конструктор:
-
В конструкторе передаются параметры, такие как device_token (уникальный токен устройства получателя), message (сообщение уведомления), title (заголовок уведомления) и server_key (ключ сервера для доступа к FCM).
-
-
Методы:
-
sendPushNotification()
: Этот метод создает полезную нагрузку (payload) для push-уведомления и отправляет его через cURL запрос в FCM с заголовками, включая серверный ключ. -
sendTaskNotification()
: Отправляет уведомление о новой задаче. -
sendTaskCompletionNotification()
: Отправляет уведомление о завершении задачи. -
sendTaskReminderNotification()
: Отправляет уведомление о напоминании. -
sendTaskOverdueNotification()
: Отправляет уведомление о просроченной задаче. -
sendTaskStatusChangeNotification()
: Отправляет уведомление о изменении статуса задачи.
-
Зависимости:
-
Firebase Cloud Messaging (FCM): Требуется Firebase проект для получения server_key и device_token.
-
cURL: Для выполнения HTTP запросов к серверу FCM.
Примечания:
-
Убедитесь, что ваш сервер поддерживает cURL и что у вас есть доступ к Firebase для получения
server_key
.
Этот класс будет использоваться для отправки push-уведомлений пользователям, связанным с задачами, например, уведомления о новых задачах, напоминания и изменения статуса задач.