wechat-chat-tool

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

微信小程序聊天工具开发指南

WeChat Mini Program Chat Tool Development Guide

基础库 3.7.8+ 支持,Android/iOS 微信 8.0.56+
Supported on Base Library 3.7.8+, WeChat 8.0.56+ for Android/iOS

快速配置

Quick Configuration

app.json 配置示例

app.json Configuration Example

json
{
  "subPackages": [
    {
      "root": "packageChatTool",
      "pages": ["pages/entry/index"],
      "entry": "entry.js", // 独立分包入口文件(必须)
      "independent": true,
      "componentFramework": "glass-easel",
      "renderer": "skyline"
    }
  ],
  "chatTools": [{
    "root": "packageChatTool",
    "entryPagePath": "pages/entry/index",
    "desc": "功能描述",
    "scopes": []
  }],
  "rendererOptions": {
    "skyline": {
      "disableABTest": true,
      "defaultDisplayBlock": true,
      "defaultContentBox": true
    }
  }
}
其中
entry.js
的代码通常:
// 独立分包入口文件
// 用于聊天工具模式的初始化

const enterOptions = wx.getEnterOptionsSync()
console.log('[ChatTool Entry] Enter options:', enterOptions)
注意事项:
  • 分包体积不超过 500KB
  • 必须使用 skyline 渲染
  • 每个小程序目前仅支持配置一个聊天工具
json
{
  "subPackages": [
    {
      "root": "packageChatTool",
      "pages": ["pages/entry/index"],
      "entry": "entry.js", // Independent subpackage entry file (required)
      "independent": true,
      "componentFramework": "glass-easel",
      "renderer": "skyline"
    }
  ],
  "chatTools": [{
    "root": "packageChatTool",
    "entryPagePath": "pages/entry/index",
    "desc": "Function Description",
    "scopes": []
  }],
  "rendererOptions": {
    "skyline": {
      "disableABTest": true,
      "defaultDisplayBlock": true,
      "defaultContentBox": true
    }
  }
}
The typical code for
entry.js
:
// Independent subpackage entry file
// Used for initialization in chat tool mode

const enterOptions = wx.getEnterOptionsSync()
console.log('[ChatTool Entry] Enter options:', enterOptions)
Notes:
  • Subpackage size should not exceed 500KB
  • Must use skyline renderer
  • Each Mini Program currently supports only one chat tool configuration

核心 API

Core APIs

进入/退出聊天模式

Enter/Exit Chat Mode

API用途
wx.openChatTool
打开聊天工具模式(可传入 opengid 或 open_single_roomid)
wx.getApiCategory
判断是否在聊天工具模式(apiCategory === 'chatTool')
wx.navigateBack
退出聊天工具模式
APIPurpose
wx.openChatTool
Open chat tool mode (can pass opengid or open_single_roomid)
wx.getApiCategory
Determine if in chat tool mode (apiCategory === 'chatTool')
wx.navigateBack
Exit chat tool mode

获取聊天信息

Obtain Chat Information

API用途
wx.getChatToolInfo
在聊天工具分包内获取绑定群聊信息
wx.getGroupEnterInfo
进入前获取群聊 id 信息
wx.selectGroupMembers
选择聊天室成员,返回 group_openid
APIPurpose
wx.getChatToolInfo
Obtain bound group chat information within chat tool subpackage
wx.getGroupEnterInfo
Obtain group chat id information before entering
wx.selectGroupMembers
Select chat room members, return group_openid

ID 类型

ID Types

  • opengid
    : 群聊唯一标识
  • open_single_roomid
    : 单聊唯一标识
  • group_openid
    : 用户在此聊天室下的唯一标识
  • opengid
    : Unique identifier for group chats
  • open_single_roomid
    : Unique identifier for one-on-one chats
  • group_openid
    : Unique identifier for a user in a specific chat room

发送到聊天

Send to Chat

API用途
wx.shareAppMessageToGroup
发送小程序卡片
wx.notifyGroupMembers
发送提醒消息(@成员 + 任务)
wx.shareImageToGroup
发送图片
wx.shareVideoToGroup
发送视频
wx.shareFileToGroup
发送文件
wx.shareEmojiToGroup
发送表情
APIPurpose
wx.shareAppMessageToGroup
Send Mini Program card
wx.notifyGroupMembers
Send reminder messages (@members + tasks)
wx.shareImageToGroup
Send images
wx.shareVideoToGroup
Send videos
wx.shareFileToGroup
Send files
wx.shareEmojiToGroup
Send emojis

动态消息

Dynamic Messages

  1. 服务端创建
    activity_id
  2. 前端
    wx.updateShareMenu
    声明动态消息
  3. 服务端
    setChatToolMsg
    更新状态
javascript
wx.updateShareMenu({
  withShareTicket: true,
  isUpdatableMessage: true,
  activityId: "xxx",
  useForChatTool: true,
  chooseType: 1, // 1=指定成员, 2=全部成员
  participant: members,
  templateInfo: {
    templateId: "4A68CBB88A92B0A9311848DBA1E94A199B166463", // 完成类
    // 或 '2A84254B945674A2F88CE4970782C402795EB607' 参与类
  },
});
  1. Server creates
    activity_id
  2. Frontend uses
    wx.updateShareMenu
    to declare dynamic messages
  3. Server uses
    setChatToolMsg
    to update status
javascript
wx.updateShareMenu({
  withShareTicket: true,
  isUpdatableMessage: true,
  activityId: "xxx",
  useForChatTool: true,
  chooseType: 1, // 1=specified members, 2=all members
  participant: members,
  templateInfo: {
    templateId: "4A68CBB88A92B0A9311848DBA1E94A199B166463", // Completion type
    // or '2A84254B945674A2F88CE4970782C402795EB607' Participation type
  },
});

禁用能力

Disabled Capabilities

聊天工具模式下不支持:
  • 普通转发(button open-type=share)
  • 外跳接口(navigateToMiniProgram 等)
  • 广告组件(ad、ad-custom)
The following are not supported in chat tool mode:
  • Ordinary forwarding (button open-type=share)
  • External jump interfaces (navigateToMiniProgram, etc.)
  • Ad components (ad, ad-custom)

7. 聊天工具核心API详解

7. Detailed Explanation of Core Chat Tool APIs

wx.openChatTool

wx.openChatTool

打开聊天工具。
Open chat tool.

参数

Parameters

Object object
Object object
属性类型默认值必填说明
urlstring聊天工具分包内的页面路径
roomidstring聊天室id,不传则拉起群选择框,可以传入多聊群的 opengid 值,或者单聊群的 open_single_roomid 值
chatTypenumber群聊类型
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)
PropertyTypeDefault ValueRequiredDescription
urlstringYesPage path within the chat tool subpackage
roomidstringNoChat room id, if not passed, group selection box will pop up; can pass opengid of multi-person group chat or open_single_roomid of one-on-one chat
chatTypenumberNoGroup chat type
successfunctionNoCallback function for successful interface call
failfunctionNoCallback function for failed interface call
completefunctionNoCallback function for interface call completion (executed on both success and failure)
object.chatType 合法值
Valid Values for object.chatType
说明
1微信联系人单聊
2企业微信联系人单聊
3普通微信群聊
4企业微信互通群聊
ValueDescription
1WeChat contact one-on-one chat
2WeChat Work contact one-on-one chat
3Ordinary WeChat group chat
4WeChat Work interoperable group chat

示例代码

Example Code

javascript
wx.openChatTool({
  url: "pages/chat/index", // 示例路径
  chatType: 1, // 微信联系人单聊
  success(res) {
    console.log("打开聊天工具成功", res);
  },
  fail(err) {
    console.error("打开聊天工具失败", err);
  },
});
javascript
wx.openChatTool({
  url: "pages/chat/index", // Example path
  chatType: 1, // WeChat contact one-on-one chat
  success(res) {
    console.log("Open chat tool successfully", res);
  },
  fail(err) {
    console.error("Failed to open chat tool", err);
  },
});

wx.getApiCategory

wx.getApiCategory

wx.getApiCategory()

wx.getApiCategory()

基础库 2.22.1 开始支持,低版本需做 兼容处理
获取当前小程序的 API 类别。
Supported since Base Library 2.22.1, need to do compatibility handling for lower versions.
Obtain the API category of the current Mini Program.
返回值
Return Value
string
string
当前 API 类别。
合法值
说明
default默认类别
nativeFunctionalized原生功能化,视频号直播商品、商品橱窗等场景打开的小程序
browseOnly仅浏览,朋友圈快照页等场景打开的小程序
embedded内嵌,通过打开半屏小程序能力打开的小程序
chatTool聊天工具打开小程序
Current API category.
Valid Values
ValueDescription
defaultDefault category
nativeFunctionalizedNative functionalization, Mini Programs opened in scenarios like Video号 live goods, product showcase, etc
browseOnlyBrowse only, Mini Programs opened in scenarios like Moments snapshot pages
embeddedEmbedded, Mini Programs opened via half-screen Mini Program capability
chatToolMini Program opened via chat tool
示例代码
Example Code
javascript
const apiCategory = wx.getApiCategory();
console.log(apiCategory);
javascript
const apiCategory = wx.getApiCategory();
console.log(apiCategory);

wx.shareAppMessageToGroup

wx.shareAppMessageToGroup

wx.shareAppMessageToGroup(Object object)

wx.shareAppMessageToGroup(Object object)

基础库 3.7.12 开始支持,低版本需做 兼容处理
转发小程序卡片到聊天。
Supported since Base Library 3.7.12, need to do compatibility handling for lower versions.
Forward Mini Program card to chat.
参数
Parameters
Object object
Object object
属性类型默认值必填说明
titlestring转发标题
pathstring当前页面转发路径,必须是以 / 开头的完整路径,默认为当前页面
imageUrlstring截图自定义图片路径,支持 PNG 及 JPG,显示图片长宽比是 5:4,默认使用截图
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)
PropertyTypeDefault ValueRequiredDescription
titlestringYesForwarding title
pathstringCurrent pageNoForwarding path, must be a complete path starting with /, defaults to current page
imageUrlstringScreenshotNoCustom image path, supports PNG and JPG; aspect ratio of displayed image is 5:4, defaults to screenshot
successfunctionNoCallback function for successful interface call
failfunctionNoCallback function for failed interface call
completefunctionNoCallback function for interface call completion (executed on both success and failure)
示例代码
Example Code
javascript
wx.shareAppMessageToGroup({
  title: "分享标题",
  path: "/path/to/page",
  imageUrl: "",
});
javascript
wx.shareAppMessageToGroup({
  title: "Share Title",
  path: "/path/to/page",
  imageUrl: "",
});

wx.shareVideoToGroup

wx.shareVideoToGroup

wx.shareVideoToGroup(Object object)

wx.shareVideoToGroup(Object object)

分享视频到聊天。
Share video to chat.
参数
Parameters
Object object
Object object
属性类型默认值必填说明
videoPathstring要分享的视频地址,必须为本地路径或临时路径
thumbPathstring缩略图路径,若留空则使用视频首帧
needShowEntrancebooleantrue分享的图片消息是否要带小程序入口
entrancePathstring''从消息小程序入口打开小程序的路径,默认为聊天工具启动路径
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)
PropertyTypeDefault ValueRequiredDescription
videoPathstringYesPath of the video to share, must be local or temporary path
thumbPathstringNoThumbnail path; if left blank, the first frame of the video will be used
needShowEntrancebooleantrueNoWhether to show Mini Program entrance in the shared image message
entrancePathstring''NoPath to open Mini Program from message entrance, defaults to chat tool startup path
successfunctionNoCallback function for successful interface call
failfunctionNoCallback function for failed interface call
completefunctionNoCallback function for interface call completion (executed on both success and failure)
示例代码
Example Code
javascript
wx.shareVideoToGroup({
  videoPath: "path/to/video.mp4",
  thumbPath: "path/to/thumb.png",
  needShowEntrance: true,
  success(res) {
    console.log("分享视频成功", res);
  },
  fail(err) {
    console.error("分享视频失败", err);
  },
});
javascript
wx.shareVideoToGroup({
  videoPath: "path/to/video.mp4",
  thumbPath: "path/to/thumb.png",
  needShowEntrance: true,
  success(res) {
    console.log("Share video successfully", res);
  },
  fail(err) {
    console.error("Failed to share video", err);
  },
});

wx.shareImageToGroup

wx.shareImageToGroup

wx.shareImageToGroup(Object object)

wx.shareImageToGroup(Object object)

分享图片到聊天。
Share image to chat.
参数
Parameters
Object object
Object object
属性类型默认值必填说明
imagePathstring要分享的图片地址,必须为本地路径或临时路径
needShowEntrancebooleantrue分享的图片消息是否要带小程序入口
entrancePathstring''从消息小程序入口打开小程序的路径,默认为聊天工具启动路径
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)
PropertyTypeDefault ValueRequiredDescription
imagePathstringYesPath of the image to share, must be local or temporary path
needShowEntrancebooleantrueNoWhether to show Mini Program entrance in the shared image message
entrancePathstring''NoPath to open Mini Program from message entrance, defaults to chat tool startup path
successfunctionNoCallback function for successful interface call
failfunctionNoCallback function for failed interface call
completefunctionNoCallback function for interface call completion (executed on both success and failure)
示例代码
Example Code
javascript
wx.shareImageToGroup({
  imagePath: "path/to/image.png",
  needShowEntrance: true,
  success(res) {
    console.log("分享图片成功", res);
  },
  fail(err) {
    console.error("分享图片失败", err);
  },
});
javascript
wx.shareImageToGroup({
  imagePath: "path/to/image.png",
  needShowEntrance: true,
  success(res) {
    console.log("Share image successfully", res);
  },
  fail(err) {
    console.error("Failed to share image", err);
  },
});

wx.shareEmojiToGroup

wx.shareEmojiToGroup

wx.shareEmojiToGroup(Object object)

wx.shareEmojiToGroup(Object object)

分享表情到聊天。
Share emoji to chat.
参数
Parameters
Object object
Object object
属性类型默认值必填说明
imagePathstring要分享的表情地址,必须为本地路径或临时路径
needShowEntrancebooleantrue分享的表情消息是否要带小程序入口
entrancePathstring''从消息小程序入口打开小程序的路径,默认为聊天工具启动路径
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)
PropertyTypeDefault ValueRequiredDescription
imagePathstringYesPath of the emoji to share, must be local or temporary path
needShowEntrancebooleantrueNoWhether to show Mini Program entrance in the shared emoji message
entrancePathstring''NoPath to open Mini Program from message entrance, defaults to chat tool startup path
successfunctionNoCallback function for successful interface call
failfunctionNoCallback function for failed interface call
completefunctionNoCallback function for interface call completion (executed on both success and failure)
示例代码
Example Code
javascript
wx.shareEmojiToGroup({
  imagePath: "path/to/image.png",
  needShowEntrance: true,
  success(res) {
    console.log("分享表情成功", res);
  },
  fail(err) {
    console.error("分享表情失败", err);
  },
});
javascript
wx.shareEmojiToGroup({
  imagePath: "path/to/image.png",
  needShowEntrance: true,
  success(res) {
    console.log("Share emoji successfully", res);
  },
  fail(err) {
    console.error("Failed to share emoji", err);
  },
});

wx.selectGroupMembers

wx.selectGroupMembers

wx.selectGroupMembers(Object object)

wx.selectGroupMembers(Object object)

从群组中选择成员。
Select members from group.
参数
Parameters
Object object
Object object
属性类型默认值必填说明
maxSelectCountnumber最多可选人数
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)
PropertyTypeDefault ValueRequiredDescription
maxSelectCountnumberNoMaximum number of selectable members
successfunctionNoCallback function for successful interface call
failfunctionNoCallback function for failed interface call
completefunctionNoCallback function for interface call completion (executed on both success and failure)
object.success 回调函数
Callback Function for object.success
####### 参数
######## Object res
属性类型说明
membersArray.<string>所选用户在此聊天室下的唯一标识,同一个用户在不同的聊天室下id不同
####### Parameters
######## Object res
PropertyTypeDescription
membersArray.<string>Unique identifiers of selected users in this chat room; the same user has different ids in different chat rooms
示例代码
Example Code
javascript
wx.selectGroupMembers({
  maxSelectCount: 10,
  success(res) {
    console.log("选择成员成功", res.members);
  },
  fail(err) {
    console.error("选择成员失败", err);
  },
});
javascript
wx.selectGroupMembers({
  maxSelectCount: 10,
  success(res) {
    console.log("Select members successfully", res.members);
  },
  fail(err) {
    console.error("Failed to select members", err);
  },
});

wx.notifyGroupMembers

wx.notifyGroupMembers

wx.notifyGroupMembers(Object object)

wx.notifyGroupMembers(Object object)

发送消息提醒群成员。
Send message reminders to group members.
参数
Parameters
Object object
Object object
属性类型默认值必填说明
titlestring文字链标题,发送的内容将由微信拼接为:@的成员列表+“请完成:”/"请参与:"+打开小程序的文字链,如「@alex @cindy 请完成:团建报名统计」。
membersArray.<string>需要提醒的用户 group_openid 列表
entrancePathstring文字链跳转路径
typestringcomplete展示的动词
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)
PropertyTypeDefault ValueRequiredDescription
titlestringYesText link title; the sent content will be spliced by WeChat as: @mentioned members + "Please complete:"/"Please participate:" + text link to open Mini Program, e.g.「@alex @cindy Please complete: Team Building Registration Statistics」。
membersArray.<string>YesList of group_openid of users to be reminded
entrancePathstringYesText link jump path
typestringcompleteNoDisplayed verb
successfunctionNoCallback function for successful interface call
failfunctionNoCallback function for failed interface call
completefunctionNoCallback function for interface call completion (executed on both success and failure)
object.type 合法值
Valid Values for object.type
说明
participate请参与
complete请完成
ValueDescription
participatePlease participate
completePlease complete
示例代码
Example Code
javascript
wx.notifyGroupMembers({
  title: "团建报名统计",
  members: ["openid1", "openid2"],
  entrancePath: "/pages/index/index",
  type: "complete",
  success(res) {
    console.log("提醒成功", res);
  },
  fail(err) {
    console.error("提醒失败", err);
  },
});
javascript
wx.notifyGroupMembers({
  title: "Team Building Registration Statistics",
  members: ["openid1", "openid2"],
  entrancePath: "/pages/index/index",
  type: "complete",
  success(res) {
    console.log("Notify successfully", res);
  },
  fail(err) {
    console.error("Failed to notify", err);
  },
});

完整文档

Complete Documentation

详见 reference.md
See reference.md