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

會話列表功能概述:前端

  • 登陸 :先用本身的帳號登陸騰訊雲;
  • 獲取會話列表 :登陸以後再獲取會話列表;
  • 更新未讀消息數量 :獲取會話列表以後更新未讀消息數量

WXML代碼(本身寫的將就看一下)

  • <view  class='msg-con'>
      <view  class='service-msg flex-wrap' >
        <view class='flex-item'>
          <view class='service-avatar'>
            <view class='iconfont icon-kefu'></view>
          </view>
        </view>
        <view class='flex-item4 service-item'>
            <view class='name s'>在線客服</view>
        </view>
        <button open-type="contact" hover-class="none"></button>
      </view>
      <view class='msg-item flex-wrap' wx:for="{{contactList}}" wx:key="{{index}}" wx:if="{{contactList.length > 0}}" bindtap='linkChat' data-id="{{item.To_Account}}" data-name="{{item.C2cNick}}">
        <view class='flex-item'>
          <view class='msg-avatar'>
            <image style="width:50px;height:50px;border-radius:50%;" mode= "scaleToFill" wx:if="{{item.C2cImage == ''}}" src="{{noData}}"></image>
            <image style="width:50px;height:50px;border-radius:50%;" mode= "scaleToFill" wx:if="{{item.C2cImage != ''}}" src="{{item.C2cImage}}"></image>
          </view>
        </view>
        <view class='flex-item4 msg-text'>
            <view class='name flex-wrap'>
              <view class="flex-item ellipsis1">{{item.C2cNick}}</view>
              <view class="flex-item tr fz24 c9">{{item.MsgTimeStamp}}</view>
            </view>
            <view class='text flex-wrap'>
              <view class='flex-item3 ellipsis1'> <text>{{item.MsgShow}}</text>  </view>
              <view class='flex-item'> <text class='count' wx:if="{{item.UnreadMsgCount > 0}}">{{item.UnreadMsgCount}}</text></view>
            </view>
        </view>
      </view>
      <view >
    </view>
    
    </view>
    <view class='dev' wx:if="{{!isNoData}}">
      <image style="width:306rpx;height:306rpx;display:block;" mode= "scaleToFill" src="{{noData}}"></image>
      <view class="devt">
      消息列表爲空~
      </view>
    </view>

    WXSS代碼

    .msg-con{
      width: 100%;
      height: auto;
      background: #ffffff;
      padding:0px 10px;
      box-sizing: border-box;
    }
    .service-msg{
      width: 100%;
      height: 70px;
    }
    .msg-item{
      border-top: 1px solid #e5e5e5;
    }
    .service-avatar{
      width: 50px;
      height: 50px;
      background: #69BEFF;
      margin: 10px 0;
      border-radius:50%; 
    }
    .msg-avatar{
      width: 50px;
      height: 50px;
      margin: 10px 0;
      border-radius:50%; 
    }
    .msg-text{
      margin-top:12px; 
    }
    .name{
      font-size: 16px;
      color: #333333;
      height: 25px;
    }
    .name.s{
      height: 70px;
      line-height: 70px;
    }
    .text{
      color: #999999;
      font-size: 13px;
      position: relative;
    }
    .icon-kefu::before{
      width: 50px;
      height: 50px;
      line-height: 50px;
      display: block;
      color: #ffffff;
      text-align: center;
      font-size: 60rpx;
    }
    .count{
      width: 20px;
      height: 20px;
      background:#F74C31;
      border-radius:50%;
      line-height: 20px;
      display: block;
      color: #ffffff;
      text-align: center;
      position: absolute;
      right: 0px;
      top: 0;
    }
    button{
      color: #333333;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0);
    }
    button:after{
      border:none;
    
    }
    .service-msg{
      position: relative;
    }

    JS代碼

    ar util = require('../..//utils/util.js'); //轉換時間插件
    var webim = require('../../utils/webim.js');//騰訊雲im包
    var webimhandler = require('../../utils/webim_handler.js');//這個是全部事件的騰訊js,這個頁面須要用到登陸
    
    const app = getApp()
    
    Page({
    
      /**
       * 頁面的初始數據
       */
      data: {
        isNoData:true,
        noData: app.data.imageUrl + '/no-msg.png',//無數據的圖片
        contactList:[],//會話列表
      },
    
      onLoad: function (options) {
    
      },
      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
          , id: selToID  //若是是經紀人,則填agent_member_id ,若是是普通用戶則填經紀人id
          , name: app.data.userInfo.agent_name
          , icon: app.data.userInfo.agent_pic,
          that: that
        });
        if (webim.checkLogin()) {//檢查是否登陸返回true和false,不登陸則從新登陸
          console.log('已登陸')
          that.initRecentContactList();
        } else {
          console.log('登陸成功')
          webimhandler.sdkLogin(that, app, selToID, function () {
            that.initRecentContactList();
          });
        }
    
      },
      //初始化聊天界面最近會話列表
      initRecentContactList: function () {
    
        var that = this;
          webim.getRecentContactList({//獲取會話列表的方法
            'Count': 10 //最近的會話數 ,最大爲 100
          }, function (resp) {
            if (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) {
            //錯誤回調
          });
    
    
      },
      // 初始化最近會話的消息未讀數(這個方法用不到,多餘,這是個坑,登陸以後仍然返回空對象)
      initUnreadMsgCount: function(){
        var sess;
        var sessMap = JSON.stringify(webim.MsgStore.sessMap()) ;
    
        for (var i in sessMap) {
          console.log('循環對象')
          sess = sessMap[i];
          // if (selToID && selToID != sess.id()) { //更新其餘聊天對象的未讀消息數
          console.log('sess.unread()', sess.unread())
          // updateSessDiv(sess.type(), sess.id(), sess.name(), sess.unread());
          // }
        }
      },
      //獲取會話列表全部用戶頭像
      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)
          }
        )
    
      },
    
      /**
       * 頁面相關事件處理函數--監聽用戶下拉動做
       */
      onPullDownRefresh: function () {
    
      },
    
      /**
       * 頁面上拉觸底事件的處理函數
       */
      onReachBottom: function () {
    
      },
      /**
       * 從列表選擇一個會話跳轉聊天(須要傳你要聊天的會話的對方id過去)
       */
      linkChat:function(e){
        wx.navigateTo({
          url: '/pages/chat/chat?id=' + e.currentTarget.dataset.id + '&name=' + e.currentTarget.dataset.name  ,
        })
      }
    })
    
    登陸的方法
    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
            , id: selToID  //若是是經紀人,則填agent_member_id ,若是是普通用戶則填經紀人id
            , 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;
            }
        };
    
    
        //監聽事件
        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)
        });
    }

    登陸主要信息配置

    (我這裏是寫在app.js裏面,這些配置信息是後臺服務器端對接完以後返回給前端的,登陸的時候要用到)
    var cache = require('./utils/cache.js');
    var login = require('./utils/login.js');
    App({
      data: {
        Config :{
          sdkappid: 1400129031,//
          accountType: 35602,
          accountMode: 0 //賬號模式,0-表示獨立模式
        },
    
      },

    https://blog.csdn.net/qq_29789057/article/details/82428326web

<view class='msg-con'> <view class='service-msg flex-wrap' > <view class='flex-item'> <view class='service-avatar'> <view class='iconfont icon-kefu'></view> </view> </view> <view class='flex-item4 service-item'> <view class='name s'>在線客服</view> </view> <button open-type="contact" hover-class="none"></button> </view> <view class='msg-item flex-wrap' wx:for="{{contactList}}" wx:key="{{index}}" wx:if="{{contactList.length > 0}}" bindtap='linkChat' data-id="{{item.To_Account}}" data-name="{{item.C2cNick}}"> <view class='flex-item'> <view class='msg-avatar'> <image style="width:50px;height:50px;border-radius:50%;" mode= "scaleToFill" wx:if="{{item.C2cImage == ''}}" src="{{noData}}"></image> <image style="width:50px;height:50px;border-radius:50%;" mode= "scaleToFill" wx:if="{{item.C2cImage != ''}}" src="{{item.C2cImage}}"></image> </view> </view> <view class='flex-item4 msg-text'> <view class='name flex-wrap'> <view class="flex-item ellipsis1">{{item.C2cNick}}</view> <view class="flex-item tr fz24 c9">{{item.MsgTimeStamp}}</view> </view> <view class='text flex-wrap'> <view class='flex-item3 ellipsis1'> <text>{{item.MsgShow}}</text> </view> <view class='flex-item'> <text class='count' wx:if="{{item.UnreadMsgCount > 0}}">{{item.UnreadMsgCount}}</text></view> </view> </view> </view> <view > </view> </view> <view class='dev' wx:if="{{!isNoData}}"> <image style="width:306rpx;height:306rpx;display:block;" mode= "scaleToFill" src="{{noData}}"></image> <view class="devt"> 消息列表爲空~ </view> </view>express

相關文章
相關標籤/搜索