uniapp中融云接入方法
重点:
- 不管是打包成app、微信小程序、h5,其实使用的都是同样的sdk,不用纠结该下载什么类型的sdk;
- 官网目前限制了小程序的免费调试,只有认证了成为企业帐户才能正常用于小程序的调试。(demo中所有的appkey为认证企业账户,故可调试);
- 如在浏览器测试,需设置关闭浏览器的跨域检测,关闭方法在demo中的readme中有叙述;
demo中仅实现了token获取,建立连接,消息监听,模拟服务器端消息发送,具体效果见下图红框
核心代码如下:
methods: {
//模拟服务器端获取token
getToken() {
let data = {
userId: 'testId',
name: 'testName',
portraitUri: 'logo.png'
}
let Nonce = parseInt(Math.random() * 10000000000)
let Timestamp = parseInt(new Date().getTime() / 1000)
//生成签名
let Signature = Sha1(appSecret + Nonce + Timestamp)
uni.request({
url: 'http://api-cn.ronghub.com/user/getToken.json',
data,
method: "POST",
header: {
'App-Key': appkey,
Nonce,
Timestamp,
Signature,
"Content-Type": "application/x-www-form-urlencoded"
},
success: function(res) {
console.log(res.data.token)
console.log('模拟服务器端获取token成功')
_self.token = res.data.token
setTimeout(()=>{
console.log('客户端初始化并连接融云服务器')
_self.connectRongIM()
},2000)
},
fail: (e) => {
console.log(e)
}
})
},
//客户端连接服务器
connectRongIM() {
//客户端初始化
let im = RongIMClient.init({
appkey
})
//客户端连接融云
var conversationList = []; // 当前已存在的会话列表
im.connect({
token: _self.token
}).then((user) => {
console.log('链接成功, 链接用户 id 为: ', user.id);
console.log('开始模拟服务器端发送消息')
_self.serverSendMessage()
}).catch(function(error) {
console.log('链接失败: ', error.code, error.msg);
});
im.watch({
conversation: function(event) {
var updatedConversationList = event.updatedConversationList; // 更新的会话列表
// console.log('更新会话汇总:', updatedConversationList);
// console.log('最新会话列表:', im.Conversation.merge({
// conversationList,
// updatedConversationList
// }));
},
message: function(event) {
var message = event.message;
console.log('接收消息成功,消息内容为:', message.content.content);
},
status: function(event) {
var status = event.status;
console.log('连接状态码:', status);
}
});
},
//模拟服务器端向单个客户端发送消息
serverSendMessage() {
let data = {
fromUserId:'system',
toUserId: 'testId',
objectName:'RC:TxtMsg',
content:'{"content":"hello 我是服务器端发来的系统消息","extra":"helloExtra"}'
}
let Nonce = parseInt(Math.random() * 10000000000)
let Timestamp = parseInt(new Date().getTime() / 1000)
let Signature = Sha1(appSecret + Nonce + Timestamp)
uni.request({
url: 'http://api-cn.ronghub.com/message/system/publish.json',
data,
method: "POST",
header: {
'App-Key': appkey,
Nonce,
Timestamp,
Signature,
"Content-Type": "application/x-www-form-urlencoded"
},
success: function(res) {
console.log('服务端消息发送成功')
},
fail: (e) => {
console.log(e)
}
})
},
}
demo下载地址:https://download.youkuaiyun.com/download/weixin_42129248/12827233
或在微信中搜索公众号:金钱交易码,回复融云获取下载链接;