๐ฑ Mini Program Integration Guideโ
This document provides a detailed guide on quickly integrating the OpenIM Client SDK into Mini Programs or Web environments for instant messaging capabilities.
โ ๏ธ Prerequisitesโ
- This JSSDK version is only compatible with IM Server v3.8.2+
- The SDK communicates directly with IM Server and does not store messages or conversations locally
- Applicable to:
- โ Web development
- โ WeChat Mini Programs
- โ uni-app
๐งฐ Environment Setupโ
Before integration, ensure the following requirements are met:
- Node.js โฅ 16.x
- An accessible IM Server (ws + api) is deployed
- Mini Program or Web project is initialized
- HTTPS is enabled (required by WeChat Mini Programs)
๐ก Tip: In WeChat Mini Program environments, ensure the
wss://address is correctly configured and added to the domain whitelist in the Mini Program admin panel.
๐ฆ Install Dependenciesโ
npm install @openim/client-sdk --save
# or
yarn add @openim/client-sdk
๐งญ Import & Initialize SDKโ
import { getSDK } from '@openim/client-sdk';
const IMSDK = getSDK({
debug: true, // Enable debug mode (optional)
});
โ Recommendation: Initialize only once during the application startup phase (e.g., in
App.vueorapp.js), sharing the IMSDK instance globally.
๐ Login & Connection Status Monitoringโ
Before calling login, it is recommended to register connection event listeners to track SDK status changes.
import { getSDK, CbEvents, CallbackEvent } from '@openim/client-sdk';
const IMSDK = getSDK();
// Bind connection status listeners
IMSDK.on(CbEvents.OnConnecting, handleConnecting);
IMSDK.on(CbEvents.OnConnectFailed, handleConnectFailed);
IMSDK.on(CbEvents.OnConnectSuccess, handleConnectSuccess);
IMSDK.on(CbEvents.OnUserTokenExpired, handleTokenExpired);
// Login
IMSDK.login({
userID: 'your-user-id',
token: 'your-token',
platformID: 5, // 5 for Web/Mini Program
wsAddr: 'ws://your-server-ip:10001',
apiAddr: 'http://your-server-ip:10002',
});
function handleConnecting() {
console.log('โณ Connecting...');
}
function handleConnectFailed({ errCode, errMsg }: CallbackEvent) {
console.error('โ Connection failed', errCode, errMsg);
}
function handleConnectSuccess() {
console.log('โ
Connected');
}
function handleTokenExpired() {
console.warn('โ ๏ธ Token expired, please log in again');
}
๐ Best Practices:
- Bind event listeners before logging in to avoid missing status changes
- After login, the IM SDK automatically maintains the long-lived connection
- Re-login is required when the token expires
- A successful
logincall does not mean the connection to IMServer is established โ listen for connection events to confirm status.
๐ฌ Send & Receive Messagesโ
๐ฅ Listen for Incoming Messagesโ
import { CbEvents, CallbackEvent, MessageItem } from '@openim/client-sdk';
IMSDK.on(CbEvents.OnRecvNewMessages, handleNewMessages);
function handleNewMessages({ data }: CallbackEvent<MessageItem[]>) {
console.log('๐ฉ New messages received', data);
}
๐ค Send a Text Messageโ
// 1. Create a text message
const { data: message } = await IMSDK.createTextMessage('Hello OpenIM!');
// 2. Send the message
IMSDK.sendMessage({
recvID: 'recipientUserID', // For private chat
groupID: '', // For group chat, fill in group ID
message,
})
.then(() => {
console.log('โ
Message sent successfully');
})
.catch((err) => {
console.error('๐ซ Failed to send message', err);
});
๐ก Tips:
- Use
recvIDfor private chats,groupIDfor group chats- After successful sending, the recipient receives the message via the
OnRecvNewMessagescallback- The SDK also supports various message types
๐งช Troubleshootingโ
| Issue | Possible Cause | Solution |
|---|---|---|
| โ Cannot connect | WebSocket address misconfigured / certificate issue | Verify wsAddr / wssAddr is valid and whitelisted in the Mini Program admin panel |
| ๐ซ Login failed | Wrong token / incorrect IM Server address | Check that the platform passed when obtaining the token matches the platform used for IMSDK login, verify server is accessible |
| ๐ก Cannot receive messages | OnRecvNewMessages event not registered / network disconnected | Ensure event binding is correct, network is available, call getLoginStatus to check status if needed |
| ๐ Mini Program cannot connect to ws:// address | WeChat Mini Programs only allow secure wss:// connections | Use a valid HTTPS certificate and configure the wss whitelist in the Mini Program admin panel |
๐งญ Debugging Tipsโ
- Enable
debug: trueto view detailed logs - Use browser DevTools / WeChat Developer Tools to inspect WebSocket connection status
- Call
IMSDK.getLoginStatus()to get real-time login status
๐งฑ More APIsโ
OpenIM Client SDK provides rich capabilities including but not limited to:
- โ User information management
- ๐ฉ Message history queries
- ๐งโ๐คโ๐ง Group operations
- ๐ก Custom message sending
- ๐ก๏ธ Conversation management, message recall, read receipts, etc.
๐ Full API documentation:
IMSDK API Reference