Уведомление Firebase pu sh не работает в android kotlin и PHP - PullRequest
0 голосов
/ 18 апреля 2020

Я пытаюсь отправить уведомление pu sh с моего устройства android через мой сервер, поэтому я написал kotlin код для получения токена из firebase и сохранил его на моем сервере. Следующим шагом я написал php скрипт для извлечения сохраненных токенов с моего сервера и отправки команды сообщения в firebase. Я протестировал тот же API с помощью почтальона, и вы получили сообщение об успехе

{"multicast_id":7524239394194034238,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1587205979775713%03eb2b8403eb2b84"}]}[]

, но сообщение не получено в моем приложении android, когда я напрямую отправляю уведомление с консоли Firebase, уведомление получено в мое приложение, я думаю, проблема в моем PHP скрипте. я новичок в этой конфигурации Firebase и PHP помогите мне завершить эту. ниже я добавлю kotlin код и PHP скрипты

мой kotlin файл

class myfirebasemessaging: FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
    super.onMessageReceived(remoteMessage)
    if (remoteMessage!!.notification != null) {
        val title = remoteMessage.notification!!.title
        val body = remoteMessage.notification!!.body

        NotificationHelper.displayNotification(applicationContext, title!!, body!!)
    }
}
}

получить токен из моей базы данных

   public function getAllTokens($usertype){

    $stmt = $this->con->prepare("SELECT token from fcm_token WHERE user_type=?");
    $stmt->bind_param("s", $usertype);
    $stmt->execute();

     //$stmt->bind_result($token);
     $result = $stmt->get_result();

    $tokens = array(); 

    while($token = $result->fetch_assoc()){

        array_push($tokens, $token['token']);

    }


    return $tokens;

}

Отправка Firebase PHP

class Firebase {

public function send($registration_ids, $message) {
    $fields = array(
        'registration_ids' => $registration_ids,
        'notification' => $message,
    );

    return $this->sendPushNotification($fields);
}

/*
* This function will make the actuall curl request to firebase server
* and then the message is sent 
*/
private function sendPushNotification($fields) {

    //importing the constant files
    require_once '../Constants.php';

    //firebase server url to send the curl request
    $url = 'https://fcm.googleapis.com/fcm/send';

    //building headers for the request
    $headers = array(
        'Authorization: key=' . FIREBASE_API_KEY,
        'Content-Type: application/json'
    );

    //Initializing curl to open a connection
    $ch = curl_init();

    //Setting the curl url
    curl_setopt($ch, CURLOPT_URL, $url);

    //setting the method as post
    curl_setopt($ch, CURLOPT_POST, true);

    //adding headers 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //disabling ssl support
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    //adding the fields in json format 
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    //finally executing the curl request 
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }

    //Now close the connection
    curl_close($ch);

    //and return the result 
    return $result;

}
}

сообщение об урегулировании PHP

<?php 

class Push {
//notification title
private $title;

//notification message 
private $message;

//notification image url 
private $image;

//initializing values in this constructor
function __construct($title, $message, $image) {
     $this->title = $title;
     $this->message = $message; 
     $this->image = $image; 
}

//getting the push notification
public function getPush() {
    $res = array();
    $res['data']['title'] = $this->title;
    $res['data']['message'] = $this->message;
    $res['data']['image'] = $this->image;
    return $res;
}

}

* извините за мой плохой английский sh

1 Ответ

0 голосов
/ 18 апреля 2020

Вы получаете полезную нагрузку уведомления в приложении android, поэтому измените функцию php getPu sh на использование полезной нагрузки уведомления:

public function getPush() {
    $res = array();
    $res['title'] = $this->title;
    $res['body'] = $this->message;
    $res['image'] = $this->image;
    return $res;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...