WeChat Mini Program integration

Updated at:

Interactive Messaging is a service that enhances communication and user interaction in live streaming rooms. It provides a rich, easy-to-integrate SDK to add features like comments, bullet comments, and likes to your live streaming applications. This topic describes how to integrate the Interactive Messaging SDK with a WeChat Mini Program.

Prerequisites

Server-side integration

Before you perform client-side integration, ensure you have completed server-side integration and provided an API for the client to obtain a token. For more information, see Server-side integration.

Configure server domains in the console

  1. Log in to the WeChat Official Accounts Platform.

  2. In the left-side navigation pane, choose Development > Development Management.

  3. On the Development Settings page, add the following domain names to the server domain name list.

    • Request valid domain name: HTTPS domains

      https://slsrole.alicdn.com
      https://videocloud.cn-hangzhou.log.aliyuncs.com
    • Socket valid domain name: WSS domains

      wss://rcoims.rtn.aliyuncs.com

Integrate SDK files

Download SDK files

Download the WeChat Mini Program SDK. Rename the downloaded alivc-im.bin file to alivc-im.zip, then extract the alivc-im.js and alivc-im.wasm.br files.

Integrate into a native project

If you have a native WeChat Mini Program project, follow these two steps to integrate the SDK:

  1. Copy the alivc-im.js and alivc-im.wasm.br files to the /lib directory of your project.

  2. Modify the WASM file path specified during initialization. For more information, see Initialization.

The following example shows the project directory structure:

.
├── lib
│   ├── alivc-im.js
│   ├── alivc-im.wasm.br
├── pages
│   ├── index
│   │   ├── index.js
│   │   ├── index.json
│   │   ├── index.wxml
│   │   └── index.wxss

Integrate into a uni-app project

If you are using the uni-app framework to build a WeChat Mini Program, follow these three steps to integrate the SDK:

  1. Copy the alivc-im.js file to the /lib directory.

  2. Copy the alivc-im.wasm.br file to the /static/mp-weixin directory. This ensures the alivc-im.wasm.br file is copied to the final build directory during compilation.

  3. Change the path returned by the locateFile function in the init API to /static/mp-weixin/alivc-im.wasm.br. For more information, see Initialization.

The following example shows the project directory structure:

.
├── lib
│   ├── alivc-im.js
├── static
│   ├── mp-weixin
│   │   ├── alivc-im.wasm.br
├── pages
│   ├── index
│   │   ├── index.vue

Integrate into a Taro project

If you are using the Taro framework to build a WeChat Mini Program, follow these four steps to integrate the SDK:

  1. Copy the alivc-im.js file to the /src/lib directory.

  2. Copy the alivc-im.wasm.br file to the /static directory.

  3. In the project configuration file /config/index.js, modify the copy option to directly copy the /static folder from the source directory to the final build directory.

    The following example shows how to modify the configuration file:

    const config = {
      projectName: "demo",
      outputRoot: "dist",
      copy: {
        patterns: [
          // Copy the static folder to the production directory after compilation.
          { from: 'static', to: 'dist/static' }
        ],
        options: {},
      },
      // Other configuration items are omitted.
    };
    
    module.exports = function (merge) {
      if (process.env.NODE_ENV === "development") {
        return merge({}, config, require("./dev"));
      }
      return merge({}, config, require("./prod"));
    };
    
  4. Change the path returned by the locateFile function in the init API to /static/alivc-im.wasm.br. For more information, see Initialization.

The following example shows the project directory structure:

.
├── config
│   ├── index.js
│   ├── dev.js
│   ├── prod.js
├── static
│   ├── alivc-im.wasm.br
├── src
│   ├── lib
│   │   ├── alivc-im.js
│   ├── pages
│   │   ├── index
│   │   │   ├── index.tsx

Use the SDK

To use the SDK, perform the following operations in order:

  1. Initialization

  2. Login

  3. Operations

  4. Logout

  5. Uninitialization

  6. Other operations

Operations include group operations and message operations, as described below:

Operations

  • Group operations

    • Create a group (administrator only)

    • Close a group (group owner or administrator only)

    • Join a group

    • Leave a group

    • Query group information

    • Modify group information (group owner or administrator only)

    • Query the list of recent group members

    • Query all group members (group owner or administrator only)

    • Mute a group (group owner or administrator only)

    • Unmute a group (group owner or administrator only)

    • Mute users in a group (group owner or administrator only)

    • Unmute users in a group (group owner or administrator only)

    • Query the list of muted users in a group (group owner or administrator only)

  • Message operations

    • Send a one-to-one message

    • Send a group message

    • Query the list of recent group messages

    • Query all group messages (group owner or administrator only)

    • Delete or retract a group message

    • Query historical messages

Usage notes

Important

All IDs must follow these rules.

appid

Maximum 64 characters. Allowed characters: uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and hyphens (-).

userid

Maximum 64 characters. Allowed characters: uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and hyphens (-).

groupid

Maximum 64 characters. Allowed characters: uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and hyphens (-).

Initialization

Initialize the SDK before use. You can do this at the main entry point of your business module.

Show code

// Import the SDK based on your project's structure.
const { ImEngine, ImLogLevel } = import '../../lib/alivc-im.js';

// Get the engine singleton.
const engine = ImEngine.createEngine();

try {
  await engine.init({
    deviceId: "deviceId", //[Optional]
    appId: "appId", //[Required] If left empty, initialization fails with error code -2. You must replace the sample APP_ID with your application's AppId.
    appSign: "appSign", //[Required] If left empty, initialization fails with error code -2. You must replace the sample APP_SIGN with your application's AppSign.
    logLevel: ImLogLevel.ERROR, //[Optional] Specifies the minimum log level for output. Default value: ImLogLevel.DEBUG. To disable logging, set this parameter to ImLogLevel.NONE.
    // Specify the path to the imported wasm file.
    locateFile: (url: string) => {
      if (url.endsWith('.wasm')) {
        // Modify the returned path based on the location of the alivc-im.wasm.br file in your project.
        // The path is relative to the project root directory, not the current file's directory. Do not use relative paths like .. or .
        // If you follow the uni-app project structure, return /static/mp-weixin/alivc-im.wasm.br.
        // If you follow the Taro project structure, return /static/alivc-im.wasm.br.
        return '/lib/alivc-im.wasm.br';
      }
      return url;
    },
  });
  // Make sure the asynchronous init operation succeeds before you perform other operations such as login.
  
  // After successful initialization, listen for events.
  engine.on("connecting", () => {
    console.log("connecting");
  });
  
  engine.on("connectfailed", (err) => {
    console.log(`connect failed: ${err.message}`;
  });
  
  engine.on("connectsuccess", () => {
    console.log("connect success");
  });
  
  engine.on("disconnect", (code) => {
    // Reason for disconnection. 1: User-initiated logout. 2: Kicked out. 3: Timeout or other reasons. 4: Logged in on another device.
    console.log(`disconnect: ${code}`);
  });

  engine.on('linkstate', (data) => {
    // The connection state changed. state - 0: Disconnected, 1: Connecting, 2: Connected, 3: Connection lost.
    console.log(`previousState: ${data.previousState}, currentState: ${data.currentState}`);
  });

  engine.on('reconnectsuccess', (groupInfos) => {
    // Reconnection is successful. Information of the groups that the user is in is returned.
    console.log(groupInfos);
  });
  
  engine.on("tokenexpired", async (cb) => {
    // Update this part with the code to obtain new login information.
    const auth = await getLoginAuth();
    cb(null, {
      timestamp: 22123123, // The timestamp value returned by the server.
      nonce: 'nonce',      // The nonce value returned by the server.
      role: 'admin',       // The user role. Set to an empty string if not needed.
      token: 'xxx'         // The token value returned by the server.
    });
  });
} catch (error) {
  // init error codes
  // A non-zero value indicates that initialization failed. 1001: Repeated initialization. 1002: Failed to create the underlying engine. -1: Repeated underlying initialization. -2: Incorrect initialization configuration.
  console.log(`Init Fail: code:${error.code}, message: ${error.msg}`);
}

Login

Login requires credentials from your server. Ensure you have completed the prerequisites and obtained the required timestamp, nonce, and token.

Show code

try {  
    // Make sure the asynchronous init operation is successful before you perform this operation.
    await engine.login({
      user: {
        userId: 'abc',       // The ID of the user who logged in to the current app.
        userExtension: '{}', // User extension information, such as an avatar or nickname, encapsulated as a JSON string.
      },
      userAuth: {
        timestamp: 22123123, // The timestamp value returned by the server.
        nonce: 'nonce',      // The nonce value returned by the server.
        role: 'admin',       // The user role. Set to an empty string if not needed.
        token: 'xxx'         // The token value returned by the server.
      },
    });
} catch (error) {
    // 304: Already logged in. 400: Invalid parameter. 403: Authentication failed during login.
    console.log(`login Fail: code:${error.code}, message: ${error.msg}`);
}

Group operations

Ensure the asynchronous login operation is successful before performing the following operations.

Get the group manager

Show code

// Make sure the engine is initialized. Otherwise, null is returned.
const groupManager = engine.getGroupManager();

Add and remove group listeners

Show code

// Add group operation event listeners at an appropriate time, for example, after entering a room and completing login.

groupManager.on('exit', (groupId, reason) => {
  // reason - 1: The group was disbanded. 2: You were kicked out.
  console.log(`group ${groupId} close, reason: ${reason}`);
});

// Deprecated since v1.4.1. Use the memberdatachange event instead.
groupManager.on('memberchange', (groupId, memberCount, joinUsers, leaveUsers) => {
  // A user joins or leaves the group.
  console.log(`group ${groupId} member change, memberCount: ${memberCount}, joinUsers: ${joinUsers.map(u => u.userId).join(',')}, leaveUsers: ${leaveUsers.map(u => u.userId).join('')}`);
});
/**
 * A new event for group member changes was added in v1.4.1. It returns an object.
 * @param data An object that contains data about the group member change.
 * @param data.groupId The group ID.
 * @param data.onlineCount The current online user count in the group.
 * @param data.pv The cumulative number of times users have joined the group.
 * @param data.isBigGroup Indicates whether the group is a large group.
 * @param data.joinUsers The users who joined.
 * @param data.leaveUsers The users who left.
 */
groupManager.on('memberdatachange', (data) => {
  const { groupId, onlineCount, pv, isBigGroup, joinUsers, leaveUsers } = data;
  console.log(`group ${groupId} member change, onlineCount: ${onlineCount}, pv: ${pv}, joinUsers: ${joinUsers.map(u => u.userId).join(',')}, leaveUsers: ${leaveUsers.map(u => u.userId).join('')}`);
});

groupManager.on('mutechange', (groupId, status) => {
  // The mute status of the group changed.
  console.log(`group ${groupId} mute change`);
});

groupManager.on('infochange', (groupId, info) => {
  // The group information changed.
  console.log(`group ${groupId} info change`);
});

// To remove a listener for a specific event, use the off method.
groupManager.off('infochange');

// To remove all event listeners, use the removeAllListeners method.
groupManager.removeAllListeners();

Create a group

Only an administrator can call this method. Calls from other users will fail.

Note

You can create up to 5,000 groups. This quota does not include closed groups. To ensure efficient resource use, close groups that are no longer needed.

Show code

await groupManager.createGroup({
  groupId: '',       // The group ID. If left empty, the system creates a new group and returns a unique ID.
  groupName: 'xxx',  // The group name. This parameter is required, or the call fails.
  groupMeta: 'xxx'   // Group extension information. If there are multiple fields, consider encapsulating them as a JSON string.
});

Close a group

Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

// The parameter is groupId.
await groupManager.closeGroup('xxx');

Join a group

Show code

// The parameter is groupId.
await groupManager.joinGroup('xxx');

Leave a group

Show code

// The parameter is groupId.
await groupManager.leaveGroup('xxx');

Query group information

Show code

// The parameter is groupId.
const groupInfo = await groupManager.queryGroup('xxx');

Modify group information

You can modify group extension information and set administrators. Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

await groupManager.modifyGroup({
  groupId: 'xxx',  // The group ID.
  forceUpdateAdmins: true, // Specifies whether to forcibly modify the group administrators.
  admins: ['xxx'], // A list of administrator IDs. To clear the list, pass an empty array and set forceUpdateAdmins to true.
  forceUpdateGroupMeta: true, // Specifies whether to forcibly modify the group extension information.
  groupMeta: 'xxx' // The group extension information (Meta). To clear the information, pass an empty string and set forceUpdateGroupMeta to true.
});

Query recent group members

Show code

/**
 * The parameter is groupId.
 * This API is not available for large groups. You need to check if the current group is a large group.
 * 1. A group is considered large if the isBigGroup attribute in the ImGroupInfo object returned after a successful join is true.
 * 2. A regular group can become a large group as more members join.
 * 3. Monitor group status changes with groupListener.onMemberChange(). If the isBigGroup attribute in the returned ImMemberChangeData object is true, the group is large.
 */
const recentGroupUserInfo = groupManager.listRecentGroupUser(groupId);

Query all group members

Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

/**
 * This API is not available for large groups. You need to check if the current group is a large group.
 * 1. A group is considered large if the isBigGroup attribute in the ImGroupInfo object returned after a successful join is true.
 * 2. A regular group can become a large group as more members join.
 * 3. Monitor group status changes with groupListener.onMemberChange(). If the isBigGroup attribute in the returned ImMemberChangeData object is true, the group is large.
 */
const groupUserInfo = groupManager.listGroupUser({
  groupId: 'xxx',    // The group ID.
  nextpagetoken: 12, // The pagination token. Leave empty for the first page. Use the token returned by the server to get the next page.
  pageSize: 10,      // The maximum value is 50.
  sortType: ImSortType.ASC // The sort order. ASC: earlier joins first. DESC: later joins first.
});

Mute a group

Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

// The parameter is groupId.
await groupManager.muteAll('xxx');

Unmute a group

Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

// The parameter is groupId.
await groupManager.cancelMuteAll('xxx');

Mute users in a group

Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

await groupManager.muteUser({
  groupId: 'xxx',    // The group ID.
  userList: ['xxx']  // A list of user IDs to mute.
});

Unmute users in a group

Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

await groupManager.cancelMuteUser({
  groupId: 'xxx',    // The group ID.
  userList: ['xxx']  // A list of user IDs to unmute.
});

Query muted users

Only the group owner or an administrator can call this method. Calls from other users will fail.

Show code

// The parameter is groupId.
const muteUsersInfo = await groupManager.listMuteUsers('xxx');

Message operations

Get the message manager

Show code

// Make sure the engine is initialized. Otherwise, null is returned.
const messageManager = await engine.getMessageManager();

Add and remove message listeners

Show code

// A one-to-one message is received from another user.
messageManager.on("recvc2cmessage", (msg) => {
  console.log('recvc2cmessage', msg);
});

// A group message is received.
messageManager.on("recvgroupmessage", (msg, groupId) => {
  console.log('recvgroupmessage', msg, groupId);
});

// A group message is deleted.
messageManager.on('deletegroupmessage', (msgId, groupId) => {
  console.log(`group ${groupId} delete message ${msgId}`)
});

// To remove a listener for a specific event, use the off method.
messageManager.off('recvgroupmessage');

// To remove all event listeners, use the removeAllListeners method.
messageManager.removeAllListeners();

Send a one-to-one message

Show code

try {
  const messageId = await messageManager.sendC2cMessage({
    receiverId: 'xxx',     // The recipient's ID.
    data: 'xxx',           // The message content. For structured data, consider using a JSON string.
    type: 88888,           // A custom message type. The value must be greater than 10000.
    skipAudit: false,      // Optional, defaults to false. If true, the message bypasses the Alibaba Cloud security audit. If false, the message is audited and will not be sent if it fails.
    level: ImMessageLevel.NORMAL // Sets the message level. The default is NORMAL. For details, see Message Throttling.
  });
  console.log('send success, messageId: ', messageId);
} catch (error) {
  // If error.code is 424, the recipient is offline. We recommend resending the message after the recipient comes online.
  console.log('send fail', error);
}

Use level: ImMessageLevel.NORMAL to set the message level. The default value is NORMAL. For details, see more information.

Send a group message

Show code

// Make sure you have joined the group before sending a group message.
try {
  const messageId = await messageManager.sendGroupMessage({
    groupId: 'xxx',       // The group ID.
    data: 'xxx',          // The message content. For structured data, consider using a JSON string.
    type: 88888,          // A custom message type. The value must be greater than 10000.
    skipAudit: false,     // Optional, defaults to false. If true, the message bypasses the Alibaba Cloud security audit. If false, the message is audited and will not be sent if it fails.
    skipMuteCheck: false, // Optional, defaults to false. If true, muted users can still send messages. If false, muted users cannot send messages.
    level: ImMessageLevel.NORMAL, // Sets the message level. The default is NORMAL. For details, see Message Throttling.
    sendMessageOption:{
      isStorageEnable:false,// Specifies whether to store the message. Default: false. If enabled, the message is stored in the database and is returned by `listHistoryMessage` or `listMessage` calls.
      isCacheEnable:false// Specifies whether to cache the message. Default: false. If enabled, the message is cached in memory (only the last 50 messages) and is returned by `listRecentMessage` calls.
    },
    repeatCount: 1        // Optional, defaults to 1. The number of times this message is repeated. You can use this field to aggregate identical messages and send them only once.
  });
  console.log('send success, messageId: ', messageId);
} catch (error) {
  // If error.code is 425, you have not joined the group.
  console.log('send fail', error);
}

Use level: ImMessageLevel.NORMAL to set the message level. The default value is NORMAL. For details, see more information.

Delete or retract a group message

A successful API call triggers a callback for recipients.

Show code

// Make sure you have joined the group before deleting or retracting a group message.
await messageManager.deleteMessage({
  groupId: 'xxx',       // The group ID.
  messageId: 'xxx',     // The ID of the message to delete.
});

Query recent group messages

After joining a group, you can call this API to retrieve the last 50 messages. Any user type can call this API.

Show code

// Make sure you have joined the group before querying the message list.
const messagesInfo = await messageManager.listRecentMessage({
  groupId: 'xxx',     // The group ID.
})

Query all group messages

Only the group owner or an administrator can call this method. Otherwise, the call fails. Regular users should use the listRecentMessage API to get the last 50 messages.

Show code

const { ImSortType } = import '../../lib/alivc-im.js';

// You must first call the engine.getMessageManager method to get the messageManager object.
const messageList = await messageManager.listMessage({
  groupId: 'xxx',    // The group ID.
  type: 88888,       // A custom message type. The value must be greater than 10000.
  nextPageToken: 12, // The pagination token. Leave empty for the first page. Use the token returned by the server to get the next page.
  pageSize: 10,      // Default: 10. Maximum: 30.
  sortType: ImSortType.ASC // The sort order. Default: ascending by time.
});

Query historical messages

This API is primarily for replaying historical messages after a live stream ends. Users can call this API without joining the group. Because this is a time-consuming operation, we do not recommend using it during a live stream. This API will be a paid service in the future.

Show code

// ImSortType.ASC: ascending order. ImSortType.DESC: descending order.
const { ImSortType } = import '../../lib/alivc-im.js';

// You must first call the engine.getMessageManager method to get the messageManager object.
const messageList = messageManager.listHistoryMessage({
  groupId: 'xxx',    // The group ID.
  type: 88888,       // The message type. For custom types, the value must be greater than 10000.
  nextPageToken: 12, // The pagination token. Leave empty for the first page. Use the token returned by the server to get the next page.
  pageSize: 10,      // Default: 10. Maximum: 30.
  sortType: ImSortType.ASC, // The sort order. Default: ascending by time.
  beginTime: 0,      // Optional, defaults to 0. The start time, as a Unix timestamp in seconds.
  endTime: 0         // Optional, defaults to 0. The end time, as a Unix timestamp in seconds.
});

Logout

await engine.logout();

Uninitialization

After you log out, if you do not need to log in again, you can uninitialize the engine to release underlying SDK resources.

engine.unInit()

Other operations

These are helper APIs for checking states and handling specific scenarios.

# Checks whether the SDK is initialized. You can use this API to determine if the SDK instance has been created.
ImEngine.isInitialized();

# Checks if you are logged in (returns false if login is in progress). You can only join a group or log out when logged in.
engine.isLogin();

# Checks whether you are logged out (returns false if login is in progress). You can perform a login operation only when you are in the logged-out state.
engine.isLogout();