微信小程序接入騰訊雲IM即時通訊(會話列表開發步驟)

微信小程序接入騰訊雲IM即時通訊(會話列表開發步驟)

1.先看官方文檔(小程序就看客戶端集成-web通用這一塊就好了)

2.登錄SDK(我們是獨立模式,所以託管模式就不需要管)
- 登錄https://cloud.tencent.com/document/product/269/1595
這裏寫圖片描述

  • 登錄的傳入SDK需要的參數就可以了
    這裏寫圖片描述

登錄代碼(這個照文檔寫,然後改改就差不多了)

/**
 * that(傳頁面的this過來,這裏需要接收到新消息的時候操作setData改變視圖顯示出未讀消息)
 * app(傳配置信息)
 * selToID(對方賬號id,列表不設置所以這裏傳空)
 * callback(登錄成功之後的回調) 
*/
function sdkLogin(that,app, selToID,callback) {
    if (!callback){
        callback = () => {

        }
    }
    this.init({
        accountMode: app.data.Config.accountMode
        , accountType: app.data.Config.accountType
        , sdkAppID: app.data.Config.sdkappid
        , selType: webim.SESSION_TYPE.C2C//私聊
        , agent_member_id: app.data.userInfo.id
        , id: selToID  
        , name: app.data.userInfo.agent_name
        , icon: app.data.userInfo.agent_pic,
        that:that
    });

    //當前用戶身份
    var loginInfo = {
        'sdkAppID':app.data.Config.sdkappid, //用戶所屬應用id,必填
        'appIDAt3rd':app.data.Config.sdkappid, //用戶所屬應用id,必填
        'accountType':app.data.Config.accountType, //用戶所屬應用帳號類型,必填
        'identifier': app.data.userInfo.id, //當前用戶ID,必須是否字符串類型,選填
        'identifierNick': app.data.userInfo.nickname, //當前用戶暱稱,選填
        'userSig': app.data.userInfo.usersig, //當前用戶身份憑證,必須是字符串類型,選填
    };

    //1v1單聊的話,一般只需要 'onConnNotify' 和 'onMsgNotify'就行了。
    //監聽連接狀態回調變化事件
    var onConnNotify = function (resp) {
        switch (resp.ErrorCode) {
            case webim.CONNECTION_STATUS.ON:
                //webim.Log.warn('連接狀態正常...');
                break;
            case webim.CONNECTION_STATUS.OFF:
                webim.Log.warn('連接已斷開,無法收到新消息,請檢查下你的網絡是否正常');
                break;
            default:
                webim.Log.error('未知連接狀態,status=' + resp.ErrorCode);
                break;
        }
    };

    //監聽事件(1V1監聽這兩個事件就夠了)
    var listeners = {
        "onConnNotify": onConnNotify//監聽連接狀態回調變化事件,必填
        , "onMsgNotify": onMsgNotify

    };

    //其他對象,選填
    var options = {
        'isAccessFormalEnv': true,//是否訪問正式環境,默認訪問正式,選填
        'isLogOn': true//是否開啓控制檯打印日誌,默認開啓,選填
    };

    //sdk登錄(獨立模式)
    webim.login(loginInfo, listeners, options, function (resp) {
        callback() 
    }, function (err) {
        console.log("登錄失敗", err.ErrorInfo)
    });
}

在會話列表頁面使用初始化跟登錄


onShow:function(){
    wx.showLoading()
    var that = this;
    var selToID = '';//會話列表不設置對方私聊賬號
    //傳初始化信息過去
    webimhandler.init({
      accountMode: app.data.Config.accountMode
      , accountType: app.data.Config.accountType
      , sdkAppID: app.data.Config.sdkappid
      , selType: webim.SESSION_TYPE.C2C//私聊
      , agent_member_id: app.data.userInfo.id
      , id: selToID  
      , name: app.data.userInfo.agent_name
      , icon: app.data.userInfo.agent_pic,
      that: that
    });
    //檢查是否登錄(已經登錄則不需要再次登錄)
    if (webim.checkLogin()) {
      that.initRecentContactList();
    } else {
      webimhandler.sdkLogin(that, app, selToID, function () {
        that.initRecentContactList();
      });
    }

  },

這裏要講一下爲什麼要做檢查是否登錄這件事情
前面講了進入聊天窗口的入口有好幾個,從會話列表進去聊天只是其中一個,如果從房源詳情頁面的諮詢入口進去則直接進入對話,也是需要登錄的,所以不能做重複登錄的

登錄成功之後在回調裏面調用拉取最近聯繫人的方法

這裏寫圖片描述


  initRecentContactList: function () {

    var that = this;
      webim.getRecentContactList({
        'Count': 10 //最近的會話數 ,最大爲 100
      }, function (resp) {
        if (resp.SessionItem){

          console.log('resp.SessionItemresp.SessionItem')
          console.log(resp.SessionItem)
          if (resp.SessionItem.length == 0) {
            that.setData({
              isNoData: false,
            })
            wx.hideLoading()
          }else if (resp.SessionItem.length > 0){
            that.setData({
              contactList: resp.SessionItem,
              isNoData:true
            })
            var userId = that.data.contactList.map((item, index) => {
              return item.To_Account
            })
            //這裏是獲取所有會話用戶的頭像
            that.getAvatar(userId, that.data.contactList, function (data) {
              data = data.map((item,index)=>{
                if (item.MsgShow == '[其他]'){
                  item.MsgShow = '[房源信息]'
                }
                return item;
              })
              that.setData({
                contactList: data
              })
              wx.hideLoading();
              // 初始化最近聯繫人的消息未讀數(監聽新消息事件)
              webim.syncMsgs(webimhandler.onMsgNotify());
            })
            // webim.syncMsgs(that.initUnreadMsgCount())
          }else{
            wx.hideLoading()
            return;
          }
        }else{
          wx.hideLoading()
        }

      }, function (resp) {
        //錯誤回調
      });
  },
  },

獲得最新聯繫人的頭像

這裏寫圖片描述

  //獲取會話列表用戶頭像
  getAvatar: function(userId, item, callback) {
    if(!callback) {
      callback = () => {

      }
    }
    var that = this;
    var tag_list = ['Tag_Profile_IM_Nick', 'Tag_Profile_IM_Image']
    tag_list.push("Tag_Profile_IM_Nick");
    //用戶id
    var account = userId
    var options = {
      From_Account: userId,
      To_Account: account,
      LastStandardSequence: 0,
      TagList: tag_list,
    };
    var contactList = [];
    webim.getProfilePortrait(
      options,
      function (res) {
        var UserProfileItem = res.UserProfileItem;
        var C2cNick, C2cImage;
        for (var i = 0; i < UserProfileItem.length; i++) {
          var data = UserProfileItem[i].ProfileItem;
          // 循環添加暱稱和頭像
          contactList = item.map((item, index) => {
            item.C2cNick = UserProfileItem[index].ProfileItem[0].Value

            item.C2cImage = UserProfileItem[index].ProfileItem[1].Value
            return item;
          })
        }
        contactList = contactList.map((item, index) => {
          var MsgTimeStamp = util.getDateDiff(item.MsgTimeStamp * 1000)
          item.MsgTimeStamp = MsgTimeStamp;
          return item;
        })
        callback(contactList)
      }
    )

  },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章