用户注册后如何从Firebase获取令牌

时间:2019-08-13 07:42:52

标签: javascript php laravel firebase-cloud-messaging

我已经为Firebase云消息传递设置了一个Javacript客户端,并且在服务器端使用了laravel。
目前,我正在使用javascript在用户访问路线时对其进行注册。他签约时我想要。每个用户的令牌也不同。
我想注册用户并在laravel页面上注册时订阅他的主题。我该怎么办?

<!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();
    }
}



如果我将脚本放在每个页面上,它将每次生成令牌吗? 什么时候会生成令牌?
我只想在用户成功注册后生成令牌。
我可以使用laravel吗?

0 个答案:

没有答案