0
I’m really lost on how to make notifications work. I find their documentation very confusing. But following as I understood and some tutorials, I think I managed to solve a good part and should be missing little.
I’ll spend everything I’ve ever done:
In the foreground on the homepage is like this:
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase-messaging.js"></script>
<script>
var config = {
apiKey: "meu api key",
authDomain: "meusite.firebaseapp.com", // Tenho dominio próprio e não sei se devo colocar ele aqui.
databaseURL: "https://meusite.firebaseio.com", // Não sei pra que serve isso.
projectId: "meusite",
storageBucket: "",
messagingSenderId: "470112242644" // Não lembro da onde eu tirei esse número.
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
navigator.serviceWorker.register('plugins/firebase/firebase-messaging-sw.js').then((registration) => {
messaging.usePublicVapidKey("um key que uso que tbm não lembro de onde tirei");
messaging.useServiceWorker(registration);
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
if(isTokenSentToServer()){
console.log('Token ja salvo.');
} else {
getRegToken();
}
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
});
function getRegToken() {
messaging.getToken().then(function(currentToken) {
if (currentToken) {
saveToken(currentToken);
console.log(currentToken);
setTokenSentToServer(true);
} else {
console.log('No Instance ID token available. Request permission to generate one.');
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') === '1';
}
function saveToken(currentToken) {
// Enviar Token para firebase database
}
messaging.onMessage(function(payload) {
console.log('Mensagem Recebida ', payload);
notificationTitle = payload.data.title;
notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
image: payload.data.image
};
var notification = new Notification(notificationTitle, notificationOptions);
});
</script>
So far I can get the browser token, but I don’t know where to store it. In the tutorial I saw, I would have to put in a database of my own, but then send msg one by one. And I think that I would have problems sending msg to more than 100 thousand people who request notifications. So I thought it would be better to do by topics, but I can’t imagine how it’s done, and I’d really like some help with that.
In the serviceworker archive firebase-messaging-sw.js is as follows:
importScripts('https://www.gstatic.com/firebasejs/5.6.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.6.0/firebase-messaging.js');
var config = {
apiKey: "meu api key",
authDomain: "meusite.firebaseapp.com",
databaseURL: "https://meusite.firebaseio.com",
projectId: "meusite",
storageBucket: "",
messagingSenderId: "470112242644"
};
// Até aqui tenho as mesmas duvidas do script na pagina inicial, e nem sei se precisa mesmo repetir tudo assim
firebase.initializeApp(config);
var messaging = firebase.messaging();
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = payload.data.title;
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
image: payload.data.image
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
// [END background_handler]
I tried to test it through the firebase console, but I couldn’t get any messages, I don’t think it’s working. I made a script in php and tbm did not work to send msg.
The php script is as follows Firebasenotifications.class.php:
class FireBaseNotifications {
private $serverAPiKey = "meu server key";
private $tokens = [];
private $firebaseurl = "https://fcm.googleapis.com/fcm/send";
public function setServerAPiKey($serverAPiKey) {
$this->serverAPiKey = $serverAPiKey;
}
public function setTokens($tokens) {
$this->tokens = $tokens;
}
public function SendNotification($icon, $titulo, $mensagem, $image) {
$msg = ['icon'=>$icon, 'title'=>$titulo, 'body'=>$mensagem, 'image'=>$image];
$payloads = ['registration_ids' => $this->tokens, 'data' => $msg];
return $this->CurlExecute($this->firebaseurl, $payloads);
}
private function getHeader() {
return ['Authorization: Key='.$this->serverAPiKey,'Content-Type: Application/json'];
}
private function CurlExecute($url, $postfields) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($postfields),
CURLOPT_HTTPHEADER => $this->getHeader()
));
$result['response'] = curl_exec($curl);
$result['err'] = curl_error($curl);
curl_close($curl);
return $result;
}
}
I created this class alone and I don’t even know if I did it right, I’d like to adapt it to accept topics or devices, but I don’t know how it does it. If anyone has any ideas and can guide me, I would really appreciate it.
And to use the link above I do so:
$fbcn = new FireBaseNotifications();
$fbcn->setTokens(["token do usuario 1", "token do usuário 2"...]);
$fbcn->SendNotification("linkDeImagemDoIcone.jpg", "Titulo da Mensagem", "Minha Mensagem", "linkDeImagemdaNotificacao.jpg");
But none of this is working yet. I’m totally lost. And everything I find on the net is in English. And what I find in Portuguese is only for android app, I can’t find anything for web version.
Could someone help me and explain me a little better about how it works and how to work with topics and devices??
Thank you for answering, I only saw your answer today. I’m sorry for the delay. I’ll take a closer look at your code and see where I’m going wrong. Then I’ll come back here to answer if it’s okay?? Thank you
– Samanta Silva