如何在网络应用中设置Twilio聊天推送通知

时间:2018-07-25 05:36:42

标签: push-notification twilio chat twilio-programmable-chat

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

<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 */
                        });

                    }       
                });

我不确定如何继续进行,并且不知道我是否错过了任何事情。如果有人实施了从Web应用程序到移动应用程序的推送通知,请指导我进一步进行操作。

1 个答案:

答案 0 :(得分:0)

Twilio的与此有关的文档确实希望您了解Firebase,因为在通常情况下,Twilio对于其他所有功能都非常有用时,他们的文档却相对缺乏。我自己遇到了问题,因为我使用的是空白服务工作者,但是文档清楚地告诉我们该怎么做。为了使前台通知和后台通知都能正常工作,在服务工作者中,这与https://firebase.google.com/docs/cloud-messaging/js/receive上的示例完全一样。在Service Worker中配置Firebase之后,至少需要做的就是'const messages = firebase.messaging()'来使前台通知正常工作。对于后台通知,您可以按照Google的示例来使用messages.setBackgroundMessageHandler(),因为这对于大多数用例而言可能是最好的。另外,如果您想进一步控制通知的处理方式,则可以轻松地将事件侦听器用于push事件。即

 

   // 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');
        }
    });
} 

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