firebase / firebase-js-sdk

Firebase Javascript SDK
https://firebase.google.com/docs/web/setup
Other
4.82k stars 884 forks source link

messaging.usePublicVapidKey not defined #8471

Open 0wwafa opened 1 week ago

0wwafa commented 1 week ago

Operating System

any

Environment (if applicable)

Chrome latest (128)

Firebase SDK Version

10.13.1

Firebase SDK Product(s)

Messaging

Project Tooling

my hands. (HTML)

Detailed Problem Description

In my old code I had:

const messaging = firebase.messaging();
messaging.usePublicVapidKey('MYKEY');

now usePublicVapidKey is not existant anymore.

Steps and code to reproduce issue

firebase.initializeApp({ THE CONFIG  });
const messaging = firebase.messaging();
messaging.usePublicVapidKey('MYKEY');
google-oss-bot commented 1 week ago

I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

GuillermoPeralta commented 1 week ago

Im having the same issue.

Any idea?

Thank you

0wwafa commented 1 week ago

no idea.

zwu52 commented 1 week ago

usePublicVapidKey is deprecated. If you wish to use the modular SDK, please read the doc carefully https://firebase.google.com/docs/reference/js/messaging_sw.gettokenoptions.md#gettokenoptions_interface

0wwafa commented 1 week ago

usePublicVapidKey is deprecated. If you wish to use the modular SDK, please read the doc carefully https://firebase.google.com/docs/reference/js/messaging_sw.gettokenoptions.md#gettokenoptions_interface

I know that. There are no examples anywhere (not just about the get token) but about vapid.

GuillermoPeralta commented 1 week ago

usePublicVapidKey is deprecated. If you wish to use the modular SDK, please read the doc carefully https://firebase.google.com/docs/reference/js/messaging_sw.gettokenoptions.md#gettokenoptions_interface

I know that. There are no examples anywhere (not just about the get token) but about vapid.

True, its clear we have to change, but doc about this change is not so clear for me.

@Owwafa FYI, chatGPT helped me a little bit, maybe you can ask as well. Im not done yet, but looks good, if i get success I reply here.

GuillermoPeralta commented 1 week ago

I solved this and looks its working fine.

I wil try to explain what i did to solve. Maybe it helps someone.

You have to remove this, because is not longer necesary. Now you have to use getToken with the 'MYKEY' messaging.usePublicVapidKey('MYKEY');

lso you have to change this

messaging.onTokenRefresh(() => { messaging.getToken().then((refreshedToken) => { // Indicate that the new Instance ID token has not yet been sent to the // app server. // Send Instance ID token to app server. // [START_EXCLUDE] // Display new Instance ID token and clear UI of all previous messages. // [END_EXCLUDE] }).catch((err) => { //console.log('Unable to retrieve refreshed token ', err); showToken('Unable to retrieve refreshed token ', err); }); });`

with this

Notification.requestPermission().then((permission) => { if (permission === 'granted') { messaging.getToken({ vapidKey: usePublicVapidKey }).then((currentToken) => { if (currentToken) { // Send Instance ID token to app server. // [START_EXCLUDE] // Display new Instance ID token and clear UI of all previous messages. } else { console.warn(Unable to retrieve FCM token.'); } }).catch((err) => { console.warn('Unable to retrieve FCM token.', err); }); } else { console.warn('Denied.'); } }).catch((err) => { console.error('Error.', err); });

Now your sw.js file (in your root page) will call onMessage method fron firebase.messaging.

Also you have to change the server side. Until now, you just needed to send a request including your authorization key in headers, but after change, firebase needs an oAUTH grant. In my case, I was using php so I included Google library in my project.

You need to generate a service account private key (which will dwnload a json with the key)

You can go to your firebase project console -> configuration -> service account tab -> Generate new private key button (it will download a json.

You have to be sure that you have 'API HTTP v1 " enabled on firebase cloud messaging You can go to your firebase project console -> configuration -> Cloud messaging and check if tis correct

Once you have it, you have to include the Json in googles service and generate the Bearer key. here is an example with the php code

$json = 'yout_private_key_json_generated_path.json'; $client = new Google(); $client->setAuthConfig($json) $client->addScope('https://www.googleapis.com/auth/firebase.messaging'); $accessToken = $client->fetchAccessTokenWithAssertion()['access_token']; $fcmUrl = 'https://fcm.googleapis.com/v1/projects/erp-zafiro/messages:send'; $headers = [ 'Authorization: Bearer ' . $accessToken, 'Content-Type: application/json' ]; $notification = [ 'message' => [ 'token' => 'client_id_notifications_token', 'notification' => [ 'title' => 'Your title', 'body' => 'Message', ], 'data' => [ 'attribute_key' => 'value1', 'attribute_key2' => 'value2', ] ] ];

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $fcmUrl );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $jsonEnvio );
    $response = curl_exec($ch);

I hope its clear... For me was enough to do this.

Sorry for my english as well, i tried to do my best. I know its not the best english gramar and vocabulary

Regards

0wwafa commented 1 week ago

@GuillermoPeralta thanks for your message. Before I was able to do everything CLIENT SIDE. My program (a webapp) was:

1) subscribing to notifications 2) subscribing to group "xxxxxx" 3) waiting for notifications 4) on user action, it sent a notification to group "xxxxxx"

(in group "xxxxxx"there were always only 2 users, thus allowing the two users to message each other and send a notification to each other too!) it was working perfectly until a month ago.