Skip to content

微信小程序 SDK

HealthGuard 小程序 SDK 用于在微信小程序环境中采集错误、请求和性能数据。

特点

  • 零外部依赖:不依赖任何第三方 npm 包,体积极小
  • 自动注入:通过 wrapAppwrapPage 自动包装生命周期
  • 隐私合规:默认脱敏,不上传用户敏感信息

引入方式

方式一:直接下载(推荐)

从主项目 packages/sdk-miniprogram/dist/ 目录下载 healthguard.miniprogram.js,放入小程序项目的 utils/ 目录:

project/
├── utils/
│   └── healthguard.miniprogram.js
├── app.js
└── pages/

方式二:npm(如支持)

bash
npm install @healthguard/sdk-miniprogram

初始化

app.js 中引入并初始化:

js
import { createMiniProgramClient, wrapApp } from './utils/healthguard.miniprogram.js';

const client = createMiniProgramClient({
  appKey: 'your-app-key',
  endpoint: 'https://your-collector.com/api/events/batch',
  autoCapture: true
});

// 包装 App 生命周期
App(wrapApp({
  onLaunch() {
    console.log('App Launch');
  }
}, client));

包装页面

在页面 JS 中使用 wrapPage

js
import { wrapPage } from './utils/healthguard.miniprogram.js';

Page(wrapPage({
  data: {
    motto: 'Hello World'
  },
  onLoad() {
    // 正常业务逻辑
  }
}, client));

建议将 client 实例挂载到全局 getApp() 上,避免每个页面重复创建。

配置选项

选项类型必填默认值说明
appKeystring-应用唯一标识
endpointstring-Collector 上报地址
releasestring-小程序版本号
environmentstring-环境标识
autoCaptureboolean | objectfalse是否自动捕获错误和请求

autoCapture 选项

js
autoCapture: {
  errors: true,        // onError 监听
  rejections: true,    // unhandledrejection
  requests: true       // wx.request 拦截
}

手动上报 API

与 H5 SDK API 保持一致:

js
// 手动上报错误
client.captureException(new Error('something went wrong'));

// 手动上报请求
client.captureHttp({
  method: 'GET',
  url: '/api/user',
  status: 200,
  duration: 120,
  success: true
});

// 添加面包屑
client.addBreadcrumb({
  type: 'navigation',
  message: 'navigated to /pages/detail'
});

// 立即上报
client.flush();

wx.request 拦截说明

SDK 会自动包装 wx.request,记录以下信息:

  • 请求方法、URL、状态码
  • 请求耗时(duration)
  • 请求失败原因(timeout / fail)

注意

  • 不上报 request body 和 response body
  • URL 中的敏感 query 参数自动脱敏

包体积

  • 压缩后约 3KB(gzip),对小程序包体积影响极小
  • 无外部依赖,无需在 project.config.json 中额外配置 npm 构建

隐私与脱敏

  • 默认过滤 URL query 中的 authorizationpasswordtokensecret
  • 不采集用户真实身份信息
  • 使用 userId(业务传入)或匿名 ID 标识用户

Released under the MIT License.