I have setup a javacript cliend for firebase cloud-messaging and I am using laravel at server side.
Currently, I am using javascript to register the user when he visits a route. I want it when he signs up. Also different token for every user.
I want to register user and subscribe him to a topic when signs up on laravel page. How can I do that?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="manifest" href="/manifest.json">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.3.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#config-web-app -->
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
//my-firebase-configs
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
//Request permission to receive notifications
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
messaging.getToken().then((currentToken) => {
if (currentToken) {
console.log(currentToken);
saveToken(currentToken);
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
} else {
console.log('Unable to get permission to notify.');
}
});
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...');
// TODO(developer): Send the current token to your server.
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') === '1';
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}
function saveToken(currentToken) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/save-token-to-db',
method: 'post',
data: {
"token": currentToken
}
}).done(function(result) {
console.log(result);
})
}
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
var title = payload.notification.title;
var options = {
body: payload.notification.body
}
var myNotification = new Notification(title, options);
});
</script>
</body>
</html>
class FireBaseController extends Controller
{
public function index()
{
return view('notification-form');
}
public function notify(Request $request)
{
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60 * 20);
$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody($request->message)
->setSound('default');
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['a_data' => 'my_data']);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$user = User::find(1);
$token = $user->token;
$downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();
//return Array - you must remove all this tokens in your database
$downstreamResponse->tokensToDelete();
//return Array (key : oldToken, value : new token - you must change the token in your database )
$downstreamResponse->tokensToModify();
//return Array - you should try to resend the message to the tokens in the array
$downstreamResponse->tokensToRetry();
// return Array (key:token, value:errror) - in production you should remove from your database the tokens
}
public function userNotifications()
{
return view('user-notifications');
}
public function storeToken(Request $request)
{
$user =User::find(1);
$user->token = $request->token;
$user->save();
}
}
If I put the script on every page, It will generate token everytime?
When It will generate a token?
I want to generate the token only if user is successfully registered.
Can I do this using laravel?