laravel-notification-channels / fcm

Firebase Cloud Messaging (FCM) notifications channel for Laravel
https://laravel-notification-channels.com/
MIT License
495 stars 127 forks source link

Nested array in data gets json encoded mulitple times #19

Closed Wil2129 closed 4 years ago

Wil2129 commented 4 years ago

Issue There is an issue regarding the json encoding of the data payload inside the FcmMessage. When using nested arrays they will be recursively encoded in json which will add extra backslashes on every keyvaluepair which invalidates the JSON obj.

toFcm method


      $title = 'title; 
      $body = 'body; 
      $priority = FcmMessage::PRIORITY_NORMAL;
      $timeToLive = 86400;
      $nestedArray = [
        'key_1' => 'value_1',
        'key_2' => 'value_2'
      ];
      $data = [
        'key_0' => 'value_0',
        "nestedArray" => $nestedArray
      ];

      $fcmNotification = FcmNotification::create()
          ->setTitle($title)
          ->setBody($body);

      return FcmMessage::create()
          ->setPriority($priority)
          ->setTimeToLive($timeToLive)
          ->setNotification($fcmNotification)
          ->setData($data);

Output {"foreground":true,"from":"680981541020","body":"body.""title":"title","data":{"key_0":"value_0","nestedArray":"{\\"key_1\\":\\"value_1\\",\\"key_2\\":\\"value_2\\"}"}}

Error This is the exception I got (JSON format)

{
"message": "Invalid JSON payload received. Unknown name "key_1" at 'message.data[1].value': Cannot find field.\nInvalid JSON payload received. Unknown name "key_2" at 'message.data[1].value': Cannot find field.",
"exception": "NotificationChannels\Fcm\Exceptions\CouldNotSendNotification",
"line": 11,
...
}
Wil2129 commented 4 years ago

Just found that it's an issue with Firebase Admin PHP SDK. It was referenced in issue#365 ErrorException: Array to string conversion. Apparently it was intentional, so I'll close this issue.

The SDK currently doesn't support multi-dimensional data in the data field, because I understood the respective section in the reference as if the data field should be a one-dimensional list of key/value pairs as strings.

I'll still listen to any recommendation on a way to solve this, so feel free to comment under with a solution