【问题标题】:Getting error while receiving an FCM push notification using PHP使用 PHP 接收 FCM 推送通知时出错
【发布时间】:2016-10-12 06:29:28
【问题描述】:

我想使用 FCM 发送通知。我已将项目添加到 Firebase 控制台,获得了 API 密钥和 device_token。

现在我正在从 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;

        }

    }

消息服务

 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!}

这里出了什么问题?

我还想让通知响应。因为它应该有接受和拒绝选项,点击它,我想执行一个动作。

有人可以帮忙吗?谢谢。。

【问题讨论】:

  • 我认为问题是 hi 后昏迷。它将您的文本的其余部分标记为新参数。删除它然后尝试
  • 删除,没有帮助。仍然得到同样的异常。@VivekMishra
  • 当我删除空格和//像这样工作正常时,我也会在字符异常处获得这种类型的未终止对象

标签: php android firebase-cloud-messaging firebase-notifications


【解决方案1】:

尝试使用以下示例手动传递设备令牌

    <?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;
    } ?>

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    当您使用特殊字符时会引发此异常。尝试删除句号之前的 ,。 为了让它像添加接受和拒绝一样响应,你可以查看firebase文档 this is a good explanation

    【讨论】:

    • 删除,没有帮助。仍然得到同样的异常。@Arpan Sharma
    • 我现在做到了,就像“消息”=>“您好,将我添加到您的唯一联系人列表中,您再也不需要更新任何更改了”,“标题”=>“您收到了邀请" @Arpan Sharma
    • 另外你应该使用在线 jsonvalidator 验证 json
    • 我检查了从 firbase 发送相同的消息,带有 , 。它是如何起作用的,而不是这个?你能告诉我怎么做吗? @Arpan Sharma
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2018-04-22
    • 2017-06-13
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多