Skip to main content

๐Ÿ“ฑ 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โ€‹

Note
  • 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.vue or app.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 login call 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 recvID for private chats, groupID for group chats
  • After successful sending, the recipient receives the message via the OnRecvNewMessages callback
  • The SDK also supports various message types

๐Ÿงช Troubleshootingโ€‹

IssuePossible CauseSolution
โŒ Cannot connectWebSocket address misconfigured / certificate issueVerify wsAddr / wssAddr is valid and whitelisted in the Mini Program admin panel
๐Ÿšซ Login failedWrong token / incorrect IM Server addressCheck that the platform passed when obtaining the token matches the platform used for IMSDK login, verify server is accessible
๐Ÿ“ก Cannot receive messagesOnRecvNewMessages event not registered / network disconnectedEnsure event binding is correct, network is available, call getLoginStatus to check status if needed
๐Ÿ•’ Mini Program cannot connect to ws:// addressWeChat Mini Programs only allow secure wss:// connectionsUse a valid HTTPS certificate and configure the wss whitelist in the Mini Program admin panel

๐Ÿงญ Debugging Tipsโ€‹

  • Enable debug: true to 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


๐Ÿ“š Referencesโ€‹