2

我正在使用 Twilio 可编程聊天,并希望将推送通知发送到移动应用程序(iOS、Android)和网络应用程序。我遵循了Twilio中给出的步骤 ,但我也没有在网络和移动应用程序中收到通知。以下是我实现的代码。

<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-messaging.js"></script>
<script src="firebase-messaging-sw.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "******************",
    authDomain: "*****.firebaseapp.com",
    databaseURL: "https://******.firebaseio.com",
    projectId: "******",
    storageBucket: "******.appspot.com",
    messagingSenderId: "***************"
  };
  firebase.initializeApp(config);   
</script>

在用户登录期间,我正在执行以下操作

/* Generating token for Twilio chat */
                $scope.URL = Path + "/twilio/chat/generateToken";
                var data = {"identity":localStorage.userId,"deviceId":guid(),"pushCredentialSid":"**********"}
                RestAPIService.post($http,data,$scope,$scope.URL, function ( responsesData ) {
                    if(responsesData.data.status == "success"){
                        var twilioToken = responsesData.data.token;
                        Twilio.Chat.Client.create(twilioToken).then(function(twilioClient) {
                            twilioChatClient = twilioClient;

                            // Twilio notification 
                            firebase.initializeApp(config);
                            if (firebase && firebase.messaging()) {
                              // requesting permission to use push notifications
                              firebase.messaging().requestPermission().then(function() {
                                console.log ("Notification permission granted.");
                                // getting FCM token
                                firebase.messaging().getToken().then(function(fcmToken) {
                                    console.log ("token is:" + fcmToken);
                                    // continue with Step 7 here 
                                    // passing FCM token to the `chatClientInstance` to register for push notifications
                                    twilioChatClient.setPushRegistrationId('fcm', fcmToken);

                                    // registering event listener on new message from firebase to pass it to the Chat SDK for parsing
                                    /* firebase.messaging().onMessage(function(payload){
                                        twilioChatClient.handlePushNotification(payload);
                                    }); */ 
                                }).catch(function(err) {
                                  // can't get token
                                  console.log(err);
                                });
                              }).catch(function(err){
                                // can't request permission or permission hasn't been granted to the web app by the user
                                console.log(err);
                              });
                            } else {
                                // no Firebase library imported or Firebase library wasn't correctly initialized
                            }
                            /* Twilio notification */
                        });

                    }       
                });

我不确定,如何进一步进行,也不知道我是否错过了什么。如果有人已经实现了从网络应用程序到移动应用程序的推送通知,请指导我进一步进行。

4

1 回答 1

0

Twilio 关于这方面的文档确实希望您了解 Firebase,因为他们的文档在该主题上相当缺乏,而它通常对 Twilio 的其他一切都很好。我自己遇到了问题,因为我使用的是空白服务人员,但文档清楚地告诉我们该怎么做。为了让前台和后台通知都工作,在服务工作者中,它与https://firebase.google.com/docs/cloud-messaging/js/receive上的示例完全相同. 在 service worker 中配置 firebase 后,您至少需要“const messages = firebase.messaging()”来让前台通知正常工作。对于后台通知,您可以按照 Google 的示例使用 messing.setBackgroundMessageHandler(),因为这可能是大多数用例场景的最佳选择。作为替代方案,如果您想更好地控制如何处理通知,您可以轻松地为推送事件使用事件侦听器。IE,

 

   // This event is where you'll handle background message.  You can still do self.registration.showNotification() here.
    self.addEventListener('push', function (event) {
        if (event.data) {
            console.log(`firebase-messaging-sw (background handler):  This push event has data: ${event.data.text()}`);
            //self.registration.showNotification('Title', { body: 'Background Message body.', icon: '/firebase-logo.png' });
        }
        else {
            console.log('firebase-messaging-sw(background handler):  This push event has no data.');
        }
    });

顺便说一句,因为这是一个服务工作者,你不需要在你的页面中引用这个脚本。它是一个服务工作者,navigator.serviceWorker.register() 将确保它在您的应用程序的后台运行。

至于 Twilio 部分,您需要为将接收通知的用户创建带有令牌(带聊天授权)的 Twilio 客户端。使用 Twilio 的代码示例,但为了清楚起见添加了其他部分,此代码示例应该会有所帮助:

firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

const handleNotificationsForUser = function (userId) {
    let getChatClient;
    let accessToken = '';
	
	// I'm getting my token from C# code.  Leaving this here for clarity.
    $.ajax({
        url: `chat/accesstoken/${userId}`,   
        dataType: 'JSON',
        async: false,
        success: function (data) {
            accessToken = data.result;
            console.log(`accestoken: ${accessToken}`);
            getChatClient = new Twilio.Chat.Client.create(accessToken);
        }
    });

    getChatClient.then(function (chatClient) {
        if (firebase && chatClient) {
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('/Scripts/firebase-messaging-sw.js').then(function (registration) {
                    firebase.messaging().useServiceWorker(registration);
                    console.log(`handleNotificationsForUser():  ServiceWorker registration successful with scope:  ${registration.scope}`);
                    if (firebase && firebase.messaging()) {                            
                        firebase.messaging().requestPermission().then(() => {       // requesting permission to use push notifications                            
                            firebase.messaging().getToken().then((fcmToken) => {    // getting FCM token
                                console.log(`fcm: ${fcmToken}`);
                                chatClient.setPushRegistrationId('fcm', fcmToken);

                                // This is where we would handle the foreground.  This registers an event listener 
                                // on new message from firebase for you to do something with it.
                                // The chat window must have focus for messaging().onMessage to work.
                                firebase.messaging().onMessage(function (payload) {
                                    console.log(`init - firebase.handleNotificationsForUser() - (foreground handler):  This push event has data: ${JSON.stringify(payload)}`);
                                    chatClient.handlePushNotification(payload); 
									
									// todo:  your implementatation for UI here
                                });
                            }).catch((err) => {
                                console.log(`handleNotificationsForUser():  Can't get token.  ${err}`);
                            });
                        }).catch((err) => {
                            console.log(`handleNotificationsForUser():  Can't request permission or permission hasn't been granted to the web app by the user.  ${err}`);
                        });
                    } else {
                        console.log("handleNotificationsForUser():  No Firebase library imported or Firebase library wasn't correctly initialized.");
                    }
                }, function (err) {
                    console.log(`handleNotificationsForUser(): ServiceWorker registration failed: ${err}`);
                });
            }
        } else {
            console.log('handleNotificationsForUser():  no firebase.js imported');
        }
    });
} 

我希望这对尝试在网络上执行此操作的任何人有所帮助。

于 2020-04-29T20:43:16.530 回答