1

I want to send notification using FCM. I have added project to Firebase Console got the API key and device_token.

Now I am sending a push notification from PHP, I get the message in logs, but it's showing some exception. I have followed this tutorial.

PHP script function:

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

Exception:

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

What's going wrong here?

I also want to make notification responsive. As it should have Accept and Reject option and on click of that, I want to perform an action.

Can anyone help with this please? Thank you..

AL.
  • 36,815
  • 10
  • 142
  • 281
Sid
  • 2,792
  • 9
  • 55
  • 111
  • I think the problem is coma after hi. It is marking rest of your text as new parameter. Remove it and then try – Vivek Mishra Oct 12 '16 at 06:35
  • removing , did not help.Still getting same exception.@VivekMishra – Sid Oct 12 '16 at 06:44
  • am also getting this type of Unterminated object at character exception when i remove spaces and // like this working fine – Harsha Nov 23 '16 at 11:35

2 Answers2

0

Try with below example with manually device token pass

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

Hope this will help!

Ashok Chandrapal
  • 1,020
  • 7
  • 27
0

This exception is thrown when you have used special characters.Try removing the , before the fullstop. And to make it responsive like adding accept and reject you can look into the firebase documentation this is a good explanation

Community
  • 1
  • 1
Arpan Sharma
  • 2,142
  • 11
  • 22
  • removing , did not help.Still getting same exception.@Arpan Sharma – Sid Oct 12 '16 at 06:44
  • I did it now it is like "message"=>"Hi add me to your unique contact list and you never need to update any changes anymore","title"=>"You got an Invitation" @Arpan Sharma – Sid Oct 12 '16 at 06:47
  • http://stackoverflow.com/questions/7327069/android-json-string-with-spaces-gives-unterminated-object-at-exception check the accepted answer – Arpan Sharma Oct 12 '16 at 06:55
  • Also you should validate the json using online jsonvalidator – Arpan Sharma Oct 12 '16 at 06:57
  • I checked sending same message from firbase with , . How dose that work and not this? Can you please show how to do? @Arpan Sharma – Sid Oct 12 '16 at 07:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125469/discussion-between-sid-and-arpan-sharma). – Sid Oct 12 '16 at 07:07