0

Я хочу отправить уведомление с использованием FCM. Я добавил проект в Firebase Console получил ключ API и device_token.Получение ошибки при получении push-уведомления FCM с использованием PHP

Теперь я отправляю push-уведомление от PHP, я получаю сообщение в журналах, но он показывает некоторое исключение. Я следил за этим tutorial.

PHP функция сценария:

 function sendInvite() 
    { 

     $database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME); 
     $dbConnection = $database->getDB(); 

     $stmt = $dbConnection->prepare("select * from Invitation where user_name =? and sender_id = ?"); 
     $stmt->execute(array($this->user_name,$this->sender_id)); 
     $rows = $stmt->rowCount(); 


     if ($rows > 0) { 
      $response = array("status" => -3, "message" => "Invitation exists.", "user_name" => $this->user_name); 
      return $response; 
     } 

     $this->date = ""; 
     $this->invitee_no = ""; 
     $this->status = "0"; 
     $this->contact_id = 0; 


     $stmt = $dbConnection->prepare("insert into Invitation(sender_id,date,invitee_no,status,user_name,contact_id) values(?,?,?,?,?,?)"); 

     $stmt->execute(array($this->sender_id, $this->date, $this->invitee_no, $this->status, $this->user_name,$this->contact_id)); 

     $rows = $stmt->rowCount(); 
     $Id = $dbConnection->lastInsertId(); 

     $stmt = $dbConnection->prepare("Select device_id from Users where user_id =?"); 
     $stmt->execute(array($this->sender_id)); 

     $result = $stmt->fetch(PDO::FETCH_ASSOC); 
     $token = $result["device_id"]; 

      $server_key = 'AIzaJaThyLm-PbdYurj-bYQQc'; 

      $fields = array(); 
      $fields['data'] = $data; 
      if(is_array($token)){ 
       $fields['registration_ids'] = $token; 
      }else{ 
       $fields['to'] = $token; 
      } 
//header with content_type api key 
      $headers = array(
       'Content-Type:application/json', 
       'Authorization:key='.$server_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); 
      echo $result;*/ 


      $message = 'Hi,add me to your unique contact list and you never need to update any changes anymore!'; 

     $data = array("message"=>"Hi,add me to your unique contact list and you never need to update any changes anymore!","title"=>"You got an Invitation."); 


      if (!empty($token)) { 
       $url = 'https://fcm.googleapis.com/fcm/send'; 

       $fields = array(
        'to' => $token, 
        'data' => $data 
       ); 
       $fields = json_encode($fields); 

       $headers = array(
        'Authorization: key=' . "AIzaSyBGwwJaThyLm-PhvgcbdYurj-bYQQ7XmCc", 
        'Content-Type: application/json' 
       ); 

       $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_VERIFYPEER, false); 
       curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 

       $result = curl_exec($ch); 
       echo $result; 
       curl_close($ch); 
     } 

     $stmt = $dbConnection->prepare("select * from Invitation where invitation_id=?"); 
     $stmt->execute(array($Id)); 
     $invitation = $stmt->fetch(PDO::FETCH_ASSOC); 

     if ($rows < 1) { 

      $response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason"); 
      return $response; 

     } else { 
      $response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation); 
      return $response; 

     } 

    } 

MessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); 
    public static final String PUSH_NOTIFICATION = "pushNotification"; 
    private NotificationUtils notificationUtils; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     Log.e(TAG, "From: " + remoteMessage.getFrom()); 

     if (remoteMessage == null) 
      return; 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody()); 
      handleNotification(remoteMessage.getNotification().getBody()); 
     } 

     // Check if message contains a data payload. 
     if (remoteMessage.getData().size() > 0) { 
      Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString()); 

      try { 
       JSONObject json = new JSONObject(remoteMessage.getData().toString()); 
       handleDataMessage(json); 
      } catch (Exception e) { 
       Log.e(TAG, "Exception: " + e.getMessage()); 
      } 
     } 
    } 

    private void handleNotification(String message) { 
     if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { 
      // app is in foreground, broadcast the push message 
      Intent pushNotification = new Intent(PUSH_NOTIFICATION); 
      pushNotification.putExtra("message", message); 
      LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); 

      // play notification sound 
      NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); 
      notificationUtils.playNotificationSound(); 
     }else{ 
      // If the app is in background, firebase itself handles the notification 
     } 
    } 

    private void handleDataMessage(JSONObject json) { 
     Log.e(TAG, "push json: " + json.toString()); 

     try { 
      JSONObject data = json.getJSONObject("data"); 

      String title = data.getString("title"); 
      String message = data.getString("message"); 
     // boolean isBackground = data.getBoolean("is_background"); 
      String imageUrl = data.getString("image"); 
      String timestamp = data.getString("timestamp"); 
     // JSONObject payload = data.getJSONObject("payload"); 

      Log.e(TAG, "title: " + title); 
      Log.e(TAG, "message: " + message); 
     // Log.e(TAG, "isBackground: " + isBackground); 
     // Log.e(TAG, "payload: " + payload.toString()); 
      Log.e(TAG, "imageUrl: " + imageUrl); 
      Log.e(TAG, "timestamp: " + timestamp); 


      if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { 
       // app is in foreground, broadcast the push message 
       Intent pushNotification = new Intent(PUSH_NOTIFICATION); 
       pushNotification.putExtra("message", message); 
       LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); 

       // play notification sound 
       NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); 
       notificationUtils.playNotificationSound(); 
      } else { 
       // app is in background, show the notification in notification tray 
       Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class); 
       resultIntent.putExtra("message", message); 

       // check for image attachment 
       if (TextUtils.isEmpty(imageUrl)) { 
        showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent); 
       } else { 
        // image is present, show notification with image 
        showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl); 
       } 
      } 
     } catch (JSONException e) { 
      Log.e(TAG, "Json Exception: " + e.getMessage()); 
     } catch (Exception e) { 
      Log.e(TAG, "Exception: " + e.getMessage()); 
     } 
    } 

    /** 
    * Showing notification with text only 
    */ 
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) { 
     notificationUtils = new NotificationUtils(context); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     notificationUtils.showNotificationMessage(title, message, timeStamp, intent); 
    } 

    /** 
    * Showing notification with text and image 
    */ 
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) { 
     notificationUtils = new NotificationUtils(context); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl); 
    } 
} 

Исключение:

E/MyFirebaseMessagingService: From: 321839166342 
10-12 11:49:14.744 21621-27002/com.example.siddhi.contactsapp E/MyFirebaseMessagingService: Data Payload: {title=You got an Invitation., message=Hi,add me to your unique contact list and you never need to update any changes anymore!} 
10-12 11:49:14.745 21621-27002/com.example.siddhi.contactsapp E/MyFirebaseMessagingService: Exception: Unterminated object at character 12 of {title=You got an Invitation., message=Hi,add me to your unique contact list and you never need to update any changes anymore!} 

Что происходит здесь не так?

Я также хочу, чтобы уведомление было отзывчивым. Поскольку он должен иметь параметр «Принять и отклонять» и щелкнуть по нему, я хочу выполнить действие.

Может ли кто-нибудь помочь в этом, пожалуйста? Спасибо ..

+0

Я думаю, что проблема заключается в коме после приветствия. Он помечает остальную часть вашего текста как новый параметр. Удалите его, а затем попробуйте удалить –

+0

, не помогли. Постарайтесь получить такое же исключение. @ VivekMishra – Sid

+0

am также получаю этот тип Unterminited объекта при исключении символа, когда я удаляю пробелы и // как этот рабочий тон – Harsha

ответ

0

Попробовать ниже примера с ручным устройством передачи маркеров

<?php 


define("ANDROID_PUSHNOTIFICATION_API_KEY",'API_KEY_HERE'); // FCM 
define("ANDROID_PUSHNOTIFICATION_URL",'https://fcm.googleapis.com/fcm/send'); // FCM 

function push_android($devicetoken,$param){ 
      $apiKey = ANDROID_PUSHNOTIFICATION_API_KEY; //demo 

      $registrationIDs[] = $devicetoken; 

      // Set POST variables 
      $url = ANDROID_PUSHNOTIFICATION_URL; 

        $fields = array(
         'registration_ids' => $registrationIDs, 
         'data' => $param,  
      ); 


      $headers = array(
      'Au 

thorization: key=' . $apiKey, 
     'Content-Type: application/json' 
     ); 

       // Open connection 
     $ch = curl_init();  
     // Set the url, number of POST vars, POST data 
     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_POSTFIELDS, json_encode($fields)); 

     // Execute post 
     $result = curl_exec($ch); 

       //print_r($result); exit; 

       if ($result === FALSE) { 
      die('Curl failed: ' . curl_error($ch)); 
     }else{ 
      //echo "success notification"; 
      //print_r($result); 
      //echo curl_error($ch); 
     } 

     // Close connection 
     curl_close($ch);  
     return $result; 
    } ?> 

Надеется, что это поможет!

0

Это исключение вызывается, когда вы использовали специальные символы. Попробуйте удалить перед полным стопом. И чтобы сделать его отзывчивым, как добавление приема и отклонения, вы можете ознакомиться с документацией по firebase. this is a good explanation

+0

удаление, не помогло. получение такое же исключение. @ Arpan Sharma – Sid

+0

ok, попробуйте удалить, после Hi. И! в конце –

+0

Я сделал это сейчас, как «message» => «Привет, добавьте меня в свой уникальный список контактов, и вам больше не нужно обновлять какие-либо изменения», «title» => «У вас есть приглашение» @Arpan Sharma – Sid

Смежные вопросы