小程序接入腾讯IM一登录

登录 即时通信 IM 控制台获取到登录时需要的sdkAppID。
在小程序utils里创建webim_handler.js

var webim = require('./webim_wx.js')		//下载im的js,并引入
  var selToID, currentMsgsArray, that;
function login(callback) {
  getSig().then(res => {
    var loginInfo = {
      'sdkAppID': 1400220126,  //申请的sdkAppleID
      'appIDAt3rd': 1400220126, //申请的sdkAppleID
      'identifierNick': app.globalData.userInfo.username,  //聊天时自己的昵称
      'identifier': app.globalData.userInfo.id,  //后台生成的个人信息的id
      'accountType': 1,
      'userSig': res,  //签名
      'headurl': app.globalData.userInfo.avatar  //聊天时的头像
    }
    // 指定监听事件
    var listeners = {
      "onConnNotify": onConnNotify, // 监听连接状态回调变化事件,必填
      "onMsgNotify": onMsgNotify // 监听新消息回调变化事件,必填
    }
    //其他对象,选填
    var options = {
      'isAccessFormalEnv': true, // 是否访问正式环境,默认访问正式,选填
      'isLogOn': true // 是否开启控制台打印日志,默认开启,选填
    }
    // sdk 登录(独立模式)
    webim.login(loginInfo, listeners, options, function(resp) {
      webim.Log.warn('登录 im 成功')
      callback(resp)
      wx.request({
        url: app.globalData.url + '/api/member/set/chat/info',   //app.globalData.url是自己服务器的地址,因为当时我们写的时候获取不到自己的头像,昵称,所以后台自己写了个接口,在登录的时候把当前用户的信息传入腾讯IM。
        method: 'post',
        header: {
          Accept: 'application/json',
          Authorization: 'Bearer ' + app.globalData.token
        },
        data: {
          m_identifier: app.globalData.userInfo.id,
          nick_name: app.globalData.userInfo.username,
          avatar: app.globalData.userInfo.avatar.indexOf('http') == -1 ? config1 + app.globalData.userInfo.avatar : app.globalData.userInfo.avatar
        },
        success: function(res) {
        }
      })
    }, function(err) {
      webim.Log.error("登录 im 失败", err.ErrorInfo)
    })
  })
}
function onConnNotify(resp) {
  var info;
  switch (resp.ErrorCode) { //链接状态码
    case webim.CONNECTION_STATUS.ON:
      webim.Log.warn('建立连接成功: ' + resp.ErrorInfo);
      break;
    case webim.CONNECTION_STATUS.OFF:
      info = '连接已断开,无法收到新消息,请检查下您的网络是否正常: ' + resp.ErrorInfo;
      webim.Log.warn(info);
      break;
    case webim.CONNECTION_STATUS.RECONNECT:
      info = '连接状态恢复正常: ' + resp.ErrorInfo;
      webim.Log.warn(info);
      break;
    default:
      webim.Log.error('未知连接状态: =' + resp.ErrorInfo); //错误信息
      break;
  }
}

function onMsgNotify(newMsgList) {  
  var sess, newMsg, selSess;
  //获取所有聊天会话
  var sessMap = webim.MsgStore.sessMap();  
  for (var j in newMsgList) { //遍历新消息
    newMsg = newMsgList[j];
    selSess = newMsg.getSession();
    if (newMsg.getSession().id() == selToID) { //为当前聊天对象的消息
      addMsg(newMsg);
      webim.setAutoRead(selSess, true, true);
    }
  }

  //消息已读上报,以及设置会话自动已读标记
  webim.setAutoRead(selSess, true, true);
  if (that.data.contactList) {   //当有新消息来时,更新会话列表
    that.initRecentContactList();
  }
}
function getSig() {  //这个是获取签名的接口,就是上面loginInfo的userSig
  return new Promise(function (resolve, reject) {
    wx.request({
      url: app.globalData.url + '/api/member/sig',
      method: 'get',
      header: {
        Accept: 'application/json',
        Authorization: 'Bearer ' + app.globalData.token
      },
      success: function (res) {
        if (res.data.code == '200') {
          resolve(res.data.data.user_sig)
        }
      }
    })
  })
}

function init(opts) {   //初始化参数的方法
  selToID = opts.selToID,
  that = opts.that
}
module.exports = {
  login: login,
  init: init
}

在会话列表的界面引入webim_handler.js

var webim = require('../../utils/webim_wx.js');
var webim_handler = require('../../utils/webim_handler.js');

//在onload或者onshow的生命周期函数里判断是否处于登录状态,没有登录则调用登录的方法
 onShow: function () {
    webim_handler.init({   //初始化在webim_handler里的要用到的参数,selToID是好友的id
      selToID: null,
      that:this
    })
    var that = this;
    if (app.globalData.token) {
      if (webim.checkLogin()) {
        that.initRecentContactList()
      } else {
        webim_handler.login(function (resp) {
          that.initRecentContactList()
        })
      }
    } else {
      app.userInfoReadyCallback = res => {
        app.globalData.token = res.data.data.token;
        app.globalData.userInfo = res.data.data.user_info;

        if (webim.checkLogin()) {
          that.initRecentContactList()
        } else {
          webim_handler.login(function (resp) {
            that.initRecentContactList()
          })
        }
      }
    }
  },
  // 拉取最近联系人列表
  initRecentContactList: function () {
    webim.Log.warn("开始拉取最近联系人列表");
    var that = this;
    webim.getRecentContactList({
      'Count': 10   //设置拉取的个数
    }, function (resp) {
      if (resp.SessionItem && resp.SessionItem.length > 0) {
        var contactList = resp.SessionItem.map((item, index) => {
          return {
            "friendId": item.To_Account,  //好友的id
            "friendName": item.C2cNick, //好友的昵称
            "friendAvatarUrl": item.C2cImage.indexOf('http') == -1 ? config1 + item.C2cImage : item.C2cImage,  //好友的头像
            "msgTime": utils.getDateDiff(item.MsgTimeStamp * 1000), 
            "msg": item.MsgShow,
            "unreadMsgCount": item.UnreadMsgCount
          }
        })
        // 设置联系人列表
        that.setData({
          contactList: contactList,
          isNoData: true
        })
      } else {
        that.setData({
          isNoData: false,
        })
      }
    })
    webim.Log.warn("成功拉取最近联系人列表");
  },

会话列表页面的html

<view class='message-box' >
  <view class='message-list'>

    <block wx:for='{{contactList}}'>
      <view class='message-item' bindtap='toMyChat' data-id='{{item.friendId}}' data-friendname='{{item.friendName}}' data-friendavatar='{{item.friendAvatarUrl}}'>
        <view class='origin'>
          <image src='{{item.friendAvatarUrl}}'></image>
          <view>
            <text>{{item.friendName}}</text>
            <text>{{item.msg}}</text>
          </view>
        </view>
        <view class='minute'>
          <text>{{item.msgTime}}</text>
          <text wx:if='{{item.unreadMsgCount>0}}' class='unReadCount'>{{item.unreadMsgCount}}</text>
        </view>
      </view>
    </block>

    <view wx:if='{{!isNoData}}' class="isNoData">暂无会话</view>
  </view>
</view>

会话列表的css

page{
  background: #f4f4f4;
}

.message-box{
  background: #fff;
}

.message-item{
  border-bottom: 1px solid #dcdcdc;
  padding:20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.origin{
  display: flex;
  align-items: center;
}
.origin image{
  width:96rpx;
  height:96rpx;
  border-radius: 50%;
  margin-right:30rpx;
  display: block;
}

.origin view{
  display: flex;
  flex-direction: column;
}
.origin view text:first-child{
  font-size:28rpx;
  color:#333;
  margin-bottom: 30rpx;
}
.origin view text:last-child{
  font-size:28rpx;
  color:#999999;
}

.minute{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.minute text:first-child{
  font-size:24rpx;
  color:#69707f;
  margin-bottom: 25rpx;
}
.minute text.unReadCount{
  width:49rpx;
  height:49rpx;
  background:#3bb850;
  color:#fff;
  font-size:28rpx;
  text-align: center;
  line-height: 49rpx;
  border-radius: 50%;
}

.isNoData{
  text-align: center;
  padding:20rpx 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值