SDK · WeChat Mini Program
@imcore/sdk/wechat-miniprogram exposes the complete typed imcore API through
WeChat Mini Program transports. It adapts SocketTask, asynchronous storage,
app/network lifecycle events and file uploads without requiring ambient WeChat
TypeScript declarations.
Install
npm install ./imcore-sdk-js-<version>.tgz
Enable npm support in WeChat DevTools and run Tools > Build npm. Add the IM
host to the Mini Program management console’s socket and uploadFile legal
domain lists. Production deployments must use wss:// and https://.
Create a client
import { createMiniProgramClient } from '@imcore/sdk/wechat-miniprogram';
const im = createMiniProgramClient({
wx,
url: 'wss://im.example.com/acc',
auth: {
getToken: () => wx.getStorageSync('access_token'),
login: { userID: '1001', userName: 'alice' },
},
storageNamespace: '@my-app/im/1001/',
});
App({
async onLaunch() {
await im.start();
},
onUnload() {
im.stop();
},
});
Create one client for the app, not one per page. start() subscribes to
wx.onAppShow, wx.onAppHide and wx.onNetworkStatusChange; it releases the
socket while hidden by default and reconnects and logs in again when the app is
visible and reachable. Call stop() on logout.
Storage and offline sends
The SDK stores its message cache, drafts and offline queue through WeChat’s
asynchronous storage APIs. Use a different storageNamespace for every account
to prevent state from leaking across account switches.
await im.dm.sendQueued({
targetUserID: '1002',
text: 'send when the network returns',
});
im.on('reconnected', async () => {
await im.dm.historyPage({ targetUserID: '1002', afterID: lastMessageID });
await im.operations.deviceSyncState();
});
The persistent queue flushes after authentication. The app remains responsible for pulling history and multi-device state missed while disconnected.
Upload media
Pass a temporary file path from wx.chooseMedia or another WeChat picker. The
adapter uses wx.uploadFile and returns a segment ready to send.
const selected = await wx.chooseMedia({ count: 1, mediaType: ['image'] });
const uploaded = await im.media.upload({
file: selected.tempFiles[0].tempFilePath,
type: 'image',
scene: 'dm',
targetUserID: '1002',
});
await im.dm.send({
targetUserID: '1002',
segments: [uploaded.segment],
});
The HTTP origin is derived from the WebSocket URL by default. Pass
httpBaseUrl when uploads use a different host.