热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

微信小程序接入腾讯云IM即时通讯(会话列表)

会话列表功能概述:登录:先用自己的账号登录腾讯云;获取会话列表:登录之后再获取会话列表;更新未读消息数量:获取会话列表之后更新未读消息数量WXML代码(自己写的将就

会话列表功能概述:

  • 登录 :先用自己的账号登录腾讯云;
  • 获取会话列表 :登录之后再获取会话列表;
  • 更新未读消息数量 :获取会话列表之后更新未读消息数量

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 ) {
              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/82428326

<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>


推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 利用Visual Basic开发SAP接口程序初探的方法与原理
    本文介绍了利用Visual Basic开发SAP接口程序的方法与原理,以及SAP R/3系统的特点和二次开发平台ABAP的使用。通过程序接口自动读取SAP R/3的数据表或视图,在外部进行处理和利用水晶报表等工具生成符合中国人习惯的报表样式。具体介绍了RFC调用的原理和模型,并强调本文主要不讨论SAP R/3函数的开发,而是针对使用SAP的公司的非ABAP开发人员提供了初步的接口程序开发指导。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文介绍了一个React Native新手在尝试将数据发布到服务器时遇到的问题,以及他的React Native代码和服务器端代码。他使用fetch方法将数据发送到服务器,但无法在服务器端读取/获取发布的数据。 ... [详细]
  • Android自定义控件绘图篇之Paint函数大汇总
    本文介绍了Android自定义控件绘图篇中的Paint函数大汇总,包括重置画笔、设置颜色、设置透明度、设置样式、设置宽度、设置抗锯齿等功能。通过学习这些函数,可以更好地掌握Paint的用法。 ... [详细]
  • Gitlab接入公司内部单点登录的安装和配置教程
    本文介绍了如何将公司内部的Gitlab系统接入单点登录服务,并提供了安装和配置的详细教程。通过使用oauth2协议,将原有的各子系统的独立登录统一迁移至单点登录。文章包括Gitlab的安装环境、版本号、编辑配置文件的步骤,并解决了在迁移过程中可能遇到的问题。 ... [详细]
author-avatar
mobiledu2502878565
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有