uniapp的uni-im 即时通信使用教程【用户与商家对话、聊天 / 最新 / 最全 / 带源码 / 教程】

本文详细介绍了如何在uniCloud项目中集成和使用即时通信功能,包括登录、注册接口调用、首页和详情页的实现以及微信小程序配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场景

用户图片

请添加图片描述
请添加图片描述

商家图片

请添加图片描述

下载完插件,自动配置插件的路由,也就是想要的商家列表页面,和用户列表页面
请添加图片描述

官方文档

官方文档地址

文档要看仔细,一会要用!!!

uniapp官方:https://doc.dcloud.net.cn/uniCloud/uni-im.html

插件地址

插件地址:https://ext.dcloud.net.cn/plugin?name=uni-im

项目创建uniCloud开发环境

申请开发环境

注意:我这个项目是申请的阿里云的开发环境,要用HBuilder X的账号申请,阿里云开发环境,这个申请过程不是我弄的,后端账号给的我。

申请完后

1.登录HBuilder X刚才申请的账号

2.点击项目根目录,最外层的文件,在HBuilder X里面,左击,创建开发环境uniCloud,找到申请的阿里云,这就关联到自己HBuilder X账号申请的阿里云环境

图片:
请添加图片描述

概括

1.首先,这个过程,即时通信也有登录,注册过程,这个两个过程
必须软件的账号登录和注册同时的,也就是说,登录和注册,都要调用即时通信注册接口!

2.在首页挂在登录方法

3.使用页面跳转即可

开始使用

步骤1

App.vue

引入文件

<script>
	//1. 导入统一身份信息管理模块
	import uniIdPagesInit from '@/uni_modules/uni-id-pages/init.js';
	//2. 导入uniIm的Utils工具类
	import uniImUtils from '@/uni_modules/uni-im/common/utils.js';
	export default {
		onLaunch: function() {
			//3. 初始化uni身份信息管理模块
			uniIdPagesInit();
			//4. 初始化uniIm
			uniImUtils.init();
		},
		onShow: function() {
			//3. 初始化uni身份信息管理模块
			uniIdPagesInit();
			//4. 初始化uniIm
			uniImUtils.init();
		},
	};
</script>

步骤2

找到软件登录图片

请添加图片描述

找到软件登录接口

软件登录接口,调用即时通信登录接口

登录源码如下

<template>
	<view class="">
		<view class="" @click="formSubmit">
			登录
		</view>
	</view>
</template>

<script>
	export default{
		methods:{
			/*登录方法*/
			formSubmit() {
				this.disLogin = true
				let self = this;
				let formdata = {
					mobile: self.formData.mobile,
				}
				let url = '';
			
				uni.showLoading({
					title: '正在提交'
				});
				self._post(
					url,
					formdata,
					result => {
						uni.setStorageSync('token', result.data.token);
						uni.setStorageSync('user_id', result.data.user_id);
						// 调用即时通信注册接口
						self.registerUniIm(result.data.token);
					},
					false,
					() => {
						uni.hideLoading();
						self.disLogin = false
					}
				);
			},
			// 调用即时通信注册接口,后端要,参数传好,和后端协调
			registerUniIm(token) {
				let self = this;
				let userInfo = uni.getSystemInfoSync();
				self._post('user.useruniim/uniImLogin', {
					token:token,
					uniPlatform:userInfo.uniPlatform,
					appId:userInfo.appId,
					deviceId:userInfo.deviceId
				}, function(res) {
					console.log(res);
				});
			},
		}
	}
</script>

步骤3

找到软件注册图片

同样,也要调用即时通信注册接口!!

我这个是验证码登录,你的要是注册也要调用即时通信接口

请添加图片描述

注册源码如下

<template>
	<view class="">
		<view class="" @click="formSubmit">
			注册
		</view>
	</view>
</template>

<script>
	export default{
		methods:{
			/*注册方法*/
			formSubmit() {
				this.disLogin = true
				let self = this;
				let formdata = {
					mobile: self.formData.mobile,
				}
				let url = '';
			
				uni.showLoading({
					title: '正在提交'
				});
				self._post(
					url,
					formdata,
					result => {
						uni.setStorageSync('token', result.data.token);
						uni.setStorageSync('user_id', result.data.user_id);
						// 调用即时通信注册接口
						self.registerUniIm(result.data.token);
					},
					false,
					() => {
						uni.hideLoading();
						self.disLogin = false
					}
				);
			},
			// 调用即时通信注册接口,后端要,参数传好,和后端协调
			registerUniIm(token) {
				let self = this;
				let userInfo = uni.getSystemInfoSync();
				self._post('user.useruniim/uniImLogin', {
					token:token,
					uniPlatform:userInfo.uniPlatform,
					appId:userInfo.appId,
					deviceId:userInfo.deviceId
				}, function(res) {
					console.log(res);
				});
			},
		}
	}
</script>

步骤4

找到index.vue首页

图片

请添加图片描述
请添加图片描述

index.vue源码如下

<template>

</template>

<script>
	// 要记得引入哦~
	// 引入2下面
	import uniImUtils from '@/uni_modules/uni-im/common/utils.js';
	//引入2	uniImMethods
	import uniIm from '@/uni_modules/uni-im/lib/main.js';
	
	export default {
		
		onShow() {
			// this.getTabBarLinks(); // 底部导航注定义的函数释掉
			// 当前时间,毫秒时间戳
			var timestamp = (new Date()).valueOf(); // 1604297892942

			// console.log(timestamp,'毫秒时间戳');
			
			// 获取过期时间	毫秒时间戳
			let tokenExpiredUnIm = uni.getStorageSync("tokenExpiredUnIm")

			let newTime = tokenExpiredUnIm - timestamp;

			if (!tokenExpiredUnIm && newTime < 3600000) {
				// 在首页	调用即时通信	登录接口
				this.loginUniIm();
			}
			// console.log(newTime, '新时间');
			
			
			
			// 下面看自己需求加不加。都可以
			let unreadCount = uniIm.conversation.unreadCount();
			console.log(unreadCount,'获取未读总数量')
			// 下面是给底部tabar加角标消息数量
			uni.setStorageSync("unreadCount",unreadCount)
			if (unreadCount > 0) {
				uni.setTabBarBadge({
					index: 2, 
					// text: String(unreadCount), 
					text: unreadCount,
				});
			} else { 
				uni.removeTabBarBadge({
					index: 2 
				});
			}

		},
		
		methods: {
			// 在首页	调用即时通信	登录接口
			loginUniIm() {
				let self = this;
				let userInfo = uni.getSystemInfoSync();
				self._post('user.useruniim/uniImRegister', {
					uniPlatform: userInfo.uniPlatform,
					appId: userInfo.appId,
					deviceId: userInfo.deviceId
				}, async function(res) {
					console.log(res.data.newToken);
					let uniIdToken = res.data.newToken;
					await uniImUtils.login(uniIdToken)
					
					// console.log(uniIdToken.tokenExpired, '打印');
					// 获取过期时间		毫秒时间戳
					uni.setStorageSync("tokenExpiredUnIm", uniIdToken.tokenExpired)
				});
			},
		}
	};
</script>

角标图片请添加图片描述

步骤5

找到me.vue首页

图片

请添加图片描述

源码如下

<template>

</template>

<script>
	// 要记得引入哦~
	// 引入2下面
	import uniImUtils from '@/uni_modules/uni-im/common/utils.js';
	//引入2	uniImMethods
	import uniIm from '@/uni_modules/uni-im/lib/main.js';
	
	export default {
		
		onShow() {
			// this.getTabBarLinks(); // 底部导航注定义的函数释掉
			// 当前时间,毫秒时间戳
			var timestamp = (new Date()).valueOf(); // 1604297892942

			// console.log(timestamp,'毫秒时间戳');
			
			// 获取过期时间	毫秒时间戳
			let tokenExpiredUnIm = uni.getStorageSync("tokenExpiredUnIm")

			let newTime = tokenExpiredUnIm - timestamp;

			if (!tokenExpiredUnIm && newTime < 3600000) {
				// 在个人中心,我的页面		调用即时通信	登录接口
				this.loginUniIm();
			}
			// console.log(newTime, '新时间');
			
			
			
			// 下面看自己需求加不加。都可以
			let unreadCount = uniIm.conversation.unreadCount();
			console.log(unreadCount,'获取未读总数量')
			// 下面是给底部tabar加角标消息数量
			uni.setStorageSync("unreadCount",unreadCount)
			if (unreadCount > 0) {
				uni.setTabBarBadge({
					index: 2, 
					// text: String(unreadCount), 
					text: unreadCount,
				});
			} else { 
				uni.removeTabBarBadge({
					index: 2 
				});
			}

		},
		
		methods: {
			// 个人中心,我的页面	调用即时通信	登录接口
			loginUniIm() {
				let self = this;
				let userInfo = uni.getSystemInfoSync();
				self._post('user.useruniim/uniImRegister', {
					uniPlatform: userInfo.uniPlatform,
					appId: userInfo.appId,
					deviceId: userInfo.deviceId
				}, async function(res) {
					console.log(res.data.newToken);
					let uniIdToken = res.data.newToken;
					await uniImUtils.login(uniIdToken)
					
					// console.log(uniIdToken.tokenExpired, '打印');
					// 获取过期时间		毫秒时间戳
					uni.setStorageSync("tokenExpiredUnIm", uniIdToken.tokenExpired)
				});
			},
		}
	};
</script>

步骤6

使用页面detail.vue

图片

用户联系商家按钮
请添加图片描述

源码如下

<template>
	<view class="content">
		<view class="btns-wrap-lft-btn btns-wrap-lft-btn1" @click="goSiXin">
			<text>私信联系</text>
		</view>
	</view>
</template>
<script>
	//引入uniImMethods
	import uniIm from '@/uni_modules/uni-im/lib/main.js';
	export default {
		methods: {
			data() {
				return {
					store_im_id: ''
				}
			},
			onLoad() {
				this.getData();
			},
			methods: {
				/*获取数据*/
				getData() {
					let self = this;
					let product_id = self.product_id;
					uni.showLoading({
						title: '加载中'
					});
					self._get(
						'product.product/detail', {
							product_id: product_id,
							url: self.url,
							visitcode: self.getVisitcode()
						},
						function(res) {
							// console.log(res.data.store_im_id);
							// 后端返回	对应的用户id
							self.store_im_id = res.data.store_im_id;
						}
					);
				},
				goSiXin() {
					// 文档有下面这个方法,路由下载插件就自动配置好了!!!
					// uni.navigateTo({
					// 	url:'/uni_modules/uni-im/pages/chat/chat?user_id=' + 对应的用户id
					// })

					let store_im_id = this.store_im_id;
					uni.navigateTo({
						url: '/uni_modules/uni-im/pages/chat/chat?user_id=' + store_im_id
					})
				},
			}
		}
	};
</script>

步骤7

退出页面

在这里插入图片描述

源码如下

<template>
	<view class="">
		<button @click="logout">退出登录</button>
	</view>
</template>

<script>
	// 必须加引入	必须加1import {mutations as uniIdMutations} from '@/uni_modules/uni-id-pages/common/store.js'
	import {
		mutations as uniIdMutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		methods: {
			logout() {
				let self = this;
				self.isloadding = true;
				self._get('user.index/detail', {
					id: self.id
				}, function(res) {
					// 必须加2		uniIdMutations.logout()
					uniIdMutations.logout()
				});
			}
		}
	}
</script>

<style>
</style>

步骤8

pages.json图片

请添加图片描述

步骤9

注意:
1.即时通讯,也就是实时聊天对话。
2.首先申请,然后打开设置,微信小程序配置,Web配置,App模块配置

项目根目录下,找到manifest.json文件,选择打开所需要的配置

微信小程序配置

在这里插入图片描述

Web配置/H5配置

在这里插入图片描述

App模块配置

在这里插入图片描述

步骤10

大功告成啦,哪里如果有遗漏,大家可以在评论区进行补充,感谢大家,这么久的陪伴!!!

最后

感觉文章好的话记得点个心心和关注和收藏,有错的地方麻烦指正一下,如果需要转载,请标明出处,多谢!!!

<think>好的,用户想了解如何在UniApp中集成和使用UNI-IM即时通讯功能。我需要先回忆UniApp的相关文档和IM组件的使用方式。首先,UNI-IM可能需要通过插件市场引入,或者需要安装特定的SDK。然后,用户需要配置项目,比如在manifest.json中添加模块,或者引入相关的JS文件。接着,可能需要初始化IM实例,连接服务器,处理消息的发送和接收。还要考虑示例代码的展示,比如如何调用API,如何监听事件。此外,需要注意UniApp的项目结构,可能需要使用Vue的语法,或者特定的生命周期钩子。用户还可能关心云端打包的问题,比如是否需要配置安心打包,或者证书相关的问题。同时,要确保引用正确的文档部分,比如引用提供的三个引用内容,可能涉及模块引入、项目创建方式、云端打包注意事项。需要检查步骤是否清晰,代码示例是否正确,以及是否覆盖了常见问题,比如连接失败、消息发送失败的处理。最后,生成相关问题,帮助用户进一步了解UNI-IM的其他功能或高级配置。</think>### UniApp中集成UNI-IM即时通讯功能指南 #### 1. 环境准备 - **创建项目**:使用HBuilderX创建或打开现有UniApp项目。若使用CLI方式创建,需确保已安装uni-app编译插件[^2]。 - **插件引入**:在[uni-app插件市场](https://ext.dcloud.net.cn/)搜索`uni-im`,下载并导入插件至项目。 #### 2. 模块配置 在`manifest.json`中添加IM模块声明: ```json "app-plus": { "modules": { "UniIM": {} } } ``` #### 3. 初始化IM实例 ```javascript // 在App.vue或入口文件中初始化 import uniIm from '@/uni_modules/uni-im/js_sdk/index.js'; const im = new uniIm({ appid: 'your-app-id', // 从DCloud控制台获取 autoConnect: true // 自动连接服务器 }); ``` #### 4. 监听事件消息处理 ```javascript // 监听连接状态 im.on('connect', () => { console.log('IM服务器连接成功'); }); // 接收消息 im.on('message', (msg) => { console.log('收到消息:', msg); }); // 发送文本消息 im.sendTextMessage({ toUserId: 'target-user-id', content: 'Hello UNI-IM' }); ``` #### 5. 用户登录集成 需结合uni-id实现用户鉴权: ```javascript uniCloud.callFunction({ name: 'uni-id-login', success: (res) => { im.login({ token: res.result.token }); } }); ``` #### 6. 云端打包注意事项 - 使用**安心打包**模式时,需在HBuilderX中勾选`差量包制作`选项,确保隐私合规[^3]。 - 检查`nativeplugins`目录是否包含IM插件原生代码。 #### 7. 示例代码结构 ```html <template> <view> <input v-model="message" placeholder="输入消息"/> <button @click="send">发送</button> </view> </template> <script> export default { data() { return { message: '' } }, methods: { send() { this.$im.sendTextMessage({ toUserId: 'target-id', content: this.message }); } } } </script> ``` #### 常见问题处理 - **连接失败**:检查网络状态和appid配置 - **消息发送失败**:确认目标用户在线状态 - **包体积过大**:使用安心打包的差量更新功能[^3]
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值