С 9:00 до 21:00 Без выходных

system/library/notification/whatsapp_notification.php

Вот содержимое файла system/library/notification/whatsapp_notification.php:

<?php
// WhatsApp Notification Library for Task Manager - Handles sending notifications to users via WhatsApp

class WhatsAppNotification {

    private $api_url;
    private $access_token;
    private $phone_number;
    private $message;

    // Constructor to initialize WhatsApp API parameters
    public function __construct($access_token, $phone_number, $message) {
        $this->access_token = $access_token;
        $this->phone_number = $phone_number;
        $this->message = $message;
        $this->api_url = "https://graph.facebook.com/v13.0/" . $this->phone_number . "/messages";
    }

    // Method to send WhatsApp notification
    public function sendWhatsAppNotification() {
        // Prepare the data to send to WhatsApp API
        $data = array(
            'messaging_product' => 'whatsapp',
            'to' => $this->phone_number,
            'text' => array(
                'body' => $this->message
            )
        );

        // Set headers for WhatsApp API request
        $headers = array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->access_token
        );

        // Initialize cURL to send the notification
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api_url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the cURL request and capture the response
        $response = curl_exec($ch);
        curl_close($ch);

        // Return the response from WhatsApp API
        return $response;
    }

    // Method to send task-related WhatsApp notifications
    public function sendTaskNotification($task_name, $phone_number) {
        $this->message = "You have a new task assigned to you: " . $task_name;
        $this->phone_number = $phone_number;

        return $this->sendWhatsAppNotification();
    }

    // Method to send task completion WhatsApp notifications
    public function sendTaskCompletionNotification($task_name, $phone_number) {
        $this->message = "The task " . $task_name . " has been completed successfully.";
        $this->phone_number = $phone_number;

        return $this->sendWhatsAppNotification();
    }

    // Method to send task reminder WhatsApp notifications
    public function sendTaskReminderNotification($task_name, $phone_number, $reminder_time) {
        $this->message = "Reminder: Task " . $task_name . " is due at " . $reminder_time . ".";
        $this->phone_number = $phone_number;

        return $this->sendWhatsAppNotification();
    }

    // Method to send task overdue WhatsApp notifications
    public function sendTaskOverdueNotification($task_name, $phone_number) {
        $this->message = "The task " . $task_name . " is overdue. Please take immediate action.";
        $this->phone_number = $phone_number;

        return $this->sendWhatsAppNotification();
    }

    // Method to send task status change WhatsApp notifications
    public function sendTaskStatusChangeNotification($task_name, $phone_number, $new_status) {
        $this->message = "The status of the task " . $task_name . " has changed to: " . $new_status;
        $this->phone_number = $phone_number;

        return $this->sendWhatsAppNotification();
    }

    // Method to handle WhatsApp Webhooks for task notifications
    public function handleWebhookNotification($task_name, $phone_number, $status) {
        $this->message = "Webhook Notification: The task " . $task_name . " status is now " . $status;
        $this->phone_number = $phone_number;

        return $this->sendWhatsAppNotification();
    }
}
?>

Объяснение кода:

  • Класс WhatsAppNotification:

    • Этот класс используется для отправки уведомлений пользователям через WhatsApp API. Он позволяет отправлять сообщения о различных событиях, таких как создание задач, их завершение, напоминания и изменение статусов.

  • Конструктор:

    • Конструктор принимает параметры, такие как access_token (токен доступа для WhatsApp Business API), phone_number (номер телефона получателя) и message (сообщение уведомления). Эти параметры используются для отправки сообщений через WhatsApp API.

  • Методы:

    • sendWhatsAppNotification(): Этот метод отправляет уведомление пользователю через WhatsApp API. Он использует cURL для отправки POST-запроса в WhatsApp с данными уведомления.

    • sendTaskNotification(): Отправляет уведомление о новой задаче.

    • sendTaskCompletionNotification(): Отправляет уведомление о завершении задачи.

    • sendTaskReminderNotification(): Отправляет уведомление с напоминанием о задаче.

    • sendTaskOverdueNotification(): Отправляет уведомление о просроченной задаче.

    • sendTaskStatusChangeNotification(): Отправляет уведомление об изменении статуса задачи.

    • handleWebhookNotification(): Этот метод обрабатывает уведомления через вебхуки, например, для получения обновлений статуса задачи через WhatsApp.

Зависимости:

  • WhatsApp Business API: Требуется доступ к WhatsApp Business API для отправки сообщений через WhatsApp.

  • cURL: Для выполнения HTTP запросов.

Примечания:

  • Убедитесь, что у вас есть доступ к WhatsApp Business API и правильный access_token.

  • Убедитесь, что ваш сервер поддерживает cURL для отправки запросов в WhatsApp.

Этот класс позволяет интегрировать WhatsApp-уведомления в ваш модуль "Менеджер задач", обеспечивая отправку уведомлений о задачах и их изменениях через WhatsApp.