@MrCheatEugene
Человек. Учусь кодить.

Как можно отправлять Push-уведеомления с помощью PHP и Firebase Cloud Messaging?

Привет. Ищу простой способ как можно сделать пуш-уведеомления с помощью PHP и Firebase Cloud Messaging?
Я пытался сделать это по гайдам из интернета, но как итог - уведомление не приходит.
Вот мой код.
PHP:
<?php

function push_notification_android($device_id,$message){

    //API URL of FCM
    $url = 'https://fcm.googleapis.com/fcm/send';

    /*api_key available in:
    Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key*/
    $api_key = 'key';
                
    $fields = array (
        'registration_ids' => array (
                $device_id
        ),
        'data' => array (
                "message" => $message
        )
    );

    //header includes Content type and api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$api_key
    );
                
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}var_dump(
push_notification_android("token","hi"));

HTML:
<script src="https://www.gstatic.com/firebasejs/4.10.0/firebase.js"></script>
<script>

const config = {}; //конфиг приложения в Firebase
  firebase.initializeApp(config);
</script>



<script>
function quNot()
{
    switch(Notification.permission.toLowerCase())
    {
        case "granted":
          subscribe();
            break;
        case "denied":
          console.log("=(((");
            break;
        case "default":
          Notification.requestPermission(function(state){
            if(state == "granted")
              subscribe();
            if(state == "default")
              setTimeout("quNot",3000);
            });
            break;
    }
}

quNot();

function subscribe()
{
  var msg = firebase.messaging();
  msg.requestPermission().then(function(){
    msg.getToken().then(function(token){
      console.log(token);
      }).catch(function(err){
      console.log("не удалось получить токен");
      });
    }).catch(function(err){
    console.log(err);
    });
}

</script>

Может кто то знает как починить мой код, или как отправлять уведеомления другим методом?
  • Вопрос задан
  • 653 просмотра
Решения вопроса 1
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы