gg-innovative / larafirebase

MIT License
21 stars 5 forks source link

Sound and link push don't work #3

Open pixsolution opened 5 months ago

pixsolution commented 5 months ago

Hello,

I have tested the package and everything is working fine except the sound and the url, the notification does not sound and I press and nothing, I tried the withSound() and withClickAction() methods but I got the error "Call to undefined method GGInnovative\Larafirebase\ Services\Larafirebase..." at first I thought it was my code:

//Notification class

 return (new FirebaseMessage)
                ->withTitle("titulo")
                ->withBody($message)
               // ->withSound('default')
                //->withClickAction($this->url)
               ->withToken('TOKEN_HERE')
            ->asNotification();

// I tried also with
Larafirebase::withTitle($request->title)
                ->withBody($request->message)
                //->withSound('default')
                //->withClickAction('https://www.google.com')
                ->withToken('1234') // You can use also withTopic
                ->sendNotification();

//layout/app
 <!-- The core Firebase JS SDK is always required and must be listed first -->
            <script src="https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js"></script>
            <script src="https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js"></script>

            <!-- TODO: Add SDKs for Firebase products that you want to use
                    https://firebase.google.com/docs/web/setup#available-libraries -->

            <script>
                // Your web app's Firebase configuration
                var firebaseConfig = {
                    apiKey: "12345",
                    authDomain: "...firebaseapp.com",
                    projectId:"myproject",
                    storageBucket: "...appspot.com",
                    messagingSenderId: "12345",
                    appId: "12345",
                };
                // Initialize Firebase
                firebase.initializeApp(firebaseConfig);

                const messaging = firebase.messaging();

                function initFirebaseMessagingRegistration() {
                    messaging.requestPermission().then(function() {
                        return messaging.getToken()
                    }).then(function(token) {

                        axios.post("{{ route('fcmToken') }}", {
                            _method: "PATCH",
                            token
                        }).then(({
                            data
                        }) => {
                            console.log(data)
                        }).catch(({
                            response: {
                                data
                            }
                        }) => {
                            console.error(data)
                        })

                    }).catch(function(err) {
                        console.log(`Token Error :: ${err}`);
                    });
                }

                initFirebaseMessagingRegistration();

                messaging.onMessage(function({
                    data: {
                        body,
                        title
                    }
                }) {
                    new Notification(title, {
                        body
                    });
                });
            </script>

//in public/firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.3.2/firebase-messaging.js');

firebase.initializeApp({
    apiKey: "12345",
    projectId: "myproject",
    messagingSenderId: "12345",
    appId: "12345"
});

const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function({data:{title,body,icon}}) {
    return self.registration.showNotification(title,{body,icon});
});

I tried also with your example https://github.com/kutia-software-company/larafirebase/tree/a8416730db936bb96da9d66ae3362233e565050e/javascript-client but same result

I'm using "laravel/framework": "^9.19",

What can be?

jonth93 commented 4 months ago

I just started using this package myself as this one allows the json authentication string.

I can send a notification and I can receive them but when attempting to add the with click action, I get : Call to undefined method GGInnovative\Larafirebase\Services\Larafirebase::withClickAction()

app\Console\Commands\FirebaseTest.php:40 36▕ foreach ($user->device_tokens as $t) { 37▕ Larafirebase::withTitle('AcsOS - Test Notification') 38▕ ->withBody('I have something new to share with you!') 39▕ ->withImage('https://firebase.google.com/images/social.png') ➜ 40▕ ->withClickAction('https://www.google.com') 41▕ ->withToken($t) // You can use also withTopic 42▕ ->sendNotification(); 43▕ } 44▕

jonth93 commented 4 months ago

@pixsolution I got it working. Can't say about the sound though as I have no need for it in my application.

Sending the notification, you can specify additional data as an array:

Larafirebase::withTitle('Test Notification')
            ->withBody('I have something new to share with you!')
            ->withImage('https://firebase.google.com/images/social.png')
            ->withAdditionalData([
                'link' => 'https://www.google.com',
            ])
            ->withToken($t)
            ->sendNotification();

Then in my service worker firebase-messaging-sw.js:

self.onnotificationclick = (event) => {
    console.log("On notification click: ", event);
    event.notification.close();

    link = event.notification.data.FCM_MSG.data.link;

    // This looks to see if the current is already open and
    // focuses if it is
    event.waitUntil(
        clients
            .matchAll({
                type: "window",
            })
            .then((clientList) => {
                for (const client of clientList) {
                    if (client.url === link && "focus" in client) return client.focus();
                }
                if (clients.openWindow) return clients.openWindow(link);
            }),
    );
};

link is pulled from the notification data as specified in the additional data array. Make sure the above code is declared before the FCM imports in the service worker.

I imagine you can set the sound in the same way - hope this helps

spingary commented 4 months ago

I used fromRaw() to send a sound and badge with the iOS notification:

    $token = "xyz";
    $payload['ios']['data'] = [
        'test_message' => '1',
    ];
    $payload['ios']['notification'] = [
        'title' => 'Test notification!',
        'body' => 'Test from test application',
    ];
    $raw_payload = [
        "message" => [
            "data" => $payload["ios"]['data'],
            "notification" => $payload["ios"]['notification'],
            "token" => $token,
            "apns" => [
                "payload"=> [ 
                    "aps" => [
                        'sound' => 'default',
                        'badge' => 1
                    ] 
                ]
            ]
        ]                
    ];
    $res =   Larafirebase::fromRaw($raw_payload)->sendNotification();

This worked well.

The "apns" config object is described in the Firebase docs. The "payload" object is what we're interested in here.

You can review the APNS payload info in Apple's docs.