dongxian1699 2019-08-13 07:42
浏览 98

用户注册时如何从firebase获取令牌

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 虚拟机打包apk出现错误
    • ¥30 最小化遗憾贪心算法上界
    • ¥15 用visual studi code完成html页面
    • ¥15 聚类分析或者python进行数据分析
    • ¥15 逻辑谓词和消解原理的运用
    • ¥15 三菱伺服电机按启动按钮有使能但不动作
    • ¥15 js,页面2返回页面1时定位进入的设备
    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝