npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hik-iot-sdk

v1.0.0

Published

Hikvision IoT Node.js SDK

Readme

海康互联 IoT SDK

海康互联开放平台 Node.js TypeScript SDK,提供门禁设备的人员、人脸、卡片管理及远程控门等功能。

特性

  • 强类型 - 完整的 TypeScript 类型定义
  • 自动鉴权 - 自动管理 access_token,无需手动处理
  • 自动重试 - Token 过期自动刷新并重试请求
  • 数据校验 - 使用 zod 对所有 API 返回值进行校验
  • 业务模型 - 面向业务模型设计,而非 HTTP 接口
  • 日志支持 - 使用 pino 进行日志记录

安装

npm install @qiang9996/hik-iot-sdk

快速开始

import { HikSdk } from '@qiang9996/hik-iot-sdk';

const sdk = new HikSdk({
  appKey: 'your-app-key',
  appSecret: 'your-app-secret',
  userName: 'your-phone-number',   // 登录手机号
  password: 'your-password',        // 登录密码
});

// 一键创建人员并绑定人脸和卡片
const result = await sdk.createPersonWithFaceAndCard({
  deviceSerial: 'your-device-serial',
  employeeNo: 'EMP001',
  name: '张三',
  faceURL: 'https://example.com/face.jpg',
  cardNo: '12345678',
  permanentValid: true,
});

// 远程开门
await sdk.device.openDoor('your-device-serial');

API 文档

初始化

const sdk = new HikSdk({
  appKey: string;           // 应用 AppKey
  appSecret: string;        // 应用 AppSecret
  userName: string;         // 登录手机号
  password: string;         // 登录密码
  redirectUrl?: string;     // 重定向回调地址(可选,需在应用安全设置中配置)
  baseUrl?: string;         // API 基础地址(默认:https://open-api.hikiot.com)
  timeout?: number;         // 请求超时时间(默认:30000ms)
});

// 获取当前登录用户信息
const userInfo = sdk.getUserInfo();
// { teamNo: '团队编号', personNo: '成员编号', accountNo: '账号' }

人员管理 (sdk.person)

// 添加/更新人员
await sdk.person.create({
  deviceSerial: 'device-serial',
  employeeNo: 'EMP001',
  name: '张三',
  userType: 'normal',        // normal | visitor | blackList
  permanentValid: true,      // 是否永久有效
  enableBeginTime: '2024-01-01T00:00:00',
  enableEndTime: '2037-12-31T23:59:59',
  doorRight: [1],            // 门权限
  doorRightPlan: [{ doorNo: 1, planTemplateId: [1] }],
  password: '123456',        // 开门密码(可选)
});

// 删除人员
await sdk.person.delete({
  deviceSerial: 'device-serial',
  employeeNo: 'EMP001',
});

// 批量删除人员
await sdk.person.batchDelete({
  deviceSerial: 'device-serial',
  employeeNos: ['EMP001', 'EMP002'],
});

// 查询人员
const result = await sdk.person.search({
  deviceSerial: 'device-serial',
  keyword: 'EMP001',
  page: 1,
  size: 20,
});

// 获取单个人员
const person = await sdk.person.get('device-serial', 'EMP001');

人脸管理 (sdk.face)

// 添加/更新人脸
await sdk.face.add({
  deviceSerial: 'device-serial',
  employeeNo: 'EMP001',
  faceURL: 'https://example.com/face.jpg',  // 图片需小于200KB
});

// 删除人脸
await sdk.face.delete({
  deviceSerial: 'device-serial',
  employeeNo: 'EMP001',
});

卡片管理 (sdk.card)

// 添加/更新卡片
await sdk.card.add({
  deviceSerial: 'device-serial',
  employeeNo: 'EMP001',
  cardNo: '12345678',
  cardType: 'normalCard',  // normalCard | hijackCard | superCard | ...
});

// 删除卡片
await sdk.card.delete({
  deviceSerial: 'device-serial',
  cardNo: '12345678',
});

// 批量删除卡片
await sdk.card.batchDelete({
  deviceSerial: 'device-serial',
  cardNos: ['12345678', '87654321'],
});

设备管理 (sdk.device)

// 远程开门
await sdk.device.openDoor('device-serial', 1);

// 远程关门(受控)
await sdk.device.closeDoor('device-serial', 1);

// 设置常开
await sdk.device.setDoorAlwaysOpen('device-serial', 1);

// 设置常闭
await sdk.device.setDoorAlwaysClose('device-serial', 1);

// 查询门控状态
const status = await sdk.device.getDoorStatus({
  deviceSerial: 'device-serial',
});

// 查询设备容量
const storage = await sdk.device.getStorageCount({
  deviceSerial: 'device-serial',
});

// 清空设备数据
await sdk.device.clearStorage({
  deviceSerial: 'device-serial',
  opts: ['supportUserInfo', 'supportCardInfo'],
});

门禁应用 API (sdk.access)

门禁应用 API 提供基于 SaaS 应用层面的权限管理,与硬件设备 API 互补。

// ============ 权限配置 ============
// 添加权限配置
const authorityConfigId = await sdk.access.addAuthorityConfig({
  personNo: 'ZHAxxxx',
  timePlanIds: ['1'],
  deviceGroupNo: 'SBZ001',
  password: '123456',
  dynamicCode: false,
});

// 查询权限配置列表
const configs = await sdk.access.getAuthorityConfigPage('__UNI__E32B021', 1, 20);

// 查询权限配置详情
const config = await sdk.access.getAuthorityConfigDetail(authorityConfigId);

// 删除权限配置
await sdk.access.deleteAuthorityConfig(authorityConfigId);

// ============ 设备分组 ============
// 查询设备分组
const groups = await sdk.access.getDeviceGroupPage(1, 20);

// 创建设备分组
await sdk.access.saveDeviceGroup({
  deviceGroupName: '一楼门禁',
  deviceGroupType: 1,
  deviceSerials: ['L12345678'],
});

// ============ 通行权限查询 ============
// 查询人员与设备权限关系
const personDevices = await sdk.access.getPersonDevicePage({
  personName: '张三',
  page: 1,
  size: 20,
});

// 查询未下发信息
const waitIssue = await sdk.access.getWaitIssueInfo('L12345678');

// 查询临时密码列表
const passwords = await sdk.access.listPassword();

// ============ 下发操作 ============
// 手动下发
await sdk.access.manualIssue({ deviceSerials: ['L12345678'] });

// 选择下发
await sdk.access.selectIssue({ issueNos: ['issue-no-1'] });

// 覆盖下发
await sdk.access.coverIssue({});

// ============ 开门记录 ============
// 查询开门记录
const events = await sdk.access.getAccessEventPage({
  startDate: '2024-01-01 00:00:00',
  endDate: '2024-12-31 23:59:59',
  deviceSerials: ['L12345678'],
  page: 1,
  size: 20,
});

// 查询开门记录详情
const eventDetail = await sdk.access.getAccessEventDetail('origin-id');

// 获取认证图片 URL
const picUrl = await sdk.access.getAuthPicUrl({ originId: 'origin-id', deviceSerial: 'L12345678' });

// 远程开门(应用层面)
await sdk.access.remoteOpenDoor('L12345678');

// ============ 时间计划 ============
// 查询时间计划列表
const timePlans = await sdk.access.getTimePlanList();

// 查询时间计划详情
const timePlan = await sdk.access.getTimePlanDetail(1);

// 添加时间计划
await sdk.access.addTimePlan({ timePlanName: '工作日', timePlanType: 1 });

// 删除时间计划
await sdk.access.deleteTimePlan(1);

// ============ 节假日组 ============
// 查询节假日组列表
const holidays = await sdk.access.getHolidayGroupList();

// 添加节假日组
await sdk.access.addHolidayGroup({ holidayGroupName: '春节', holidayGroupDetail: [...] });

便捷方法

// 一键创建人员并绑定人脸
const result = await sdk.createPersonWithFace({
  deviceSerial: 'device-serial',
  employeeNo: 'EMP001',
  name: '张三',
  faceURL: 'https://example.com/face.jpg',
});

// 一键创建人员并绑定人脸和卡片
const result = await sdk.createPersonWithFaceAndCard({
  deviceSerial: 'device-serial',
  employeeNo: 'EMP001',
  name: '张三',
  faceURL: 'https://example.com/face.jpg',
  cardNo: '12345678',
});

// 完整删除人员(包括人脸)
await sdk.deletePersonComplete('device-serial', 'EMP001');

远程核验事件服务

SDK 提供了远程核验事件处理示例,用于接收海康互联平台推送的 DoorRemoteCheck 事件,并根据白名单决定是否放行。

# 运行远程核验事件服务
npx tsx examples/mock.ts

服务默认监听 8080 端口,接收加密事件回调并自动解密。需要在海康互联开放平台配置:

  1. 事件订阅 → 添加 门禁远程核验 事件
  2. 加密策略 → 配置 Encrypt KeyVerification Token
  3. 回调地址 → 设置为服务的公网地址(如 https://your-domain/callback

环境变量配置:

export HIK_APP_KEY="your-app-key"
export HIK_APP_SECRET="your-app-secret"
export HIK_USER_NAME="your-phone-number"
export HIK_PASSWORD="your-password"
export HIK_ENCRYPT_KEY="your-encrypt-key"        # 事件解密用
export HIK_VERIFICATION_TOKEN="your-token"       # 事件验证用

错误处理

import { HikError, HikDeviceError, HikAuthError, ERROR_CODES } from '@qiang9996/hik-iot-sdk';

try {
  await sdk.person.create({ ... });
} catch (error) {
  if (error instanceof HikDeviceError) {
    // 设备相关错误 (160xxx)
    console.error('设备错误:', error.code, error.message, error.detail);
  } else if (error instanceof HikAuthError) {
    // 认证错误
    console.error('认证错误:', error.message);
  } else if (error instanceof HikError) {
    // 其他 API 错误
    console.error('API错误:', error.code, error.message);
  }
}

常见错误码

| 错误码 | 说明 | |--------|------| | 0 | 操作成功 | | 400015 | AppAccessToken 无效 | | 400019 | UserAccessToken 无效 | | 160001 | 设备不存在 | | 160101 | 设备离线 | | 160102 | 设备超时 | | 160104 | 设备不支持该功能 | | 160112 | 人员已被删除 | | 160116 | 人员数量已达上限 | | 160117 | 照片未检测到人脸 |

示例说明

examples/ 目录提供了多种使用示例:

| 示例文件 | 说明 | |---------|------| | demo.ts | 综合交互式示例,支持菜单选择运行门禁应用 API、人员管理或设备控制示例 | | quick-start.ts | 最简快速开始示例,展示一键创建人员并绑定人脸和卡片 | | face-access-demo.ts | 人脸与门禁设备管理示例 | | access-demo.ts | 门禁应用 API 示例 | | mock.ts | 远程核验事件 Web 服务示例,接收海康事件回调并处理 |

运行示例:

# 设置环境变量
export HIK_APP_KEY="your-app-key"
export HIK_APP_SECRET="your-app-secret"
export HIK_USER_NAME="your-phone-number"
export HIK_PASSWORD="your-password"
export HIK_DEVICE_SERIAL="your-device-serial"

# 运行综合示例(交互式菜单)
npx tsx examples/demo.ts

# 直接运行指定示例
npx tsx examples/demo.ts 1   # 门禁应用 API
npx tsx examples/demo.ts 2   # 人员/人脸/卡片管理
npx tsx examples/demo.ts 3   # 设备控制

# 运行远程核验服务
npx tsx examples/mock.ts

数据加密

海康互联开放平台默认开启数据加密,SDK 会自动处理请求加密和响应解密:

  • API 请求/响应加密:使用 RSA 私钥(App Secret)加密,SDK 自动处理
  • 事件订阅加密:使用 AES-256-CBC 加密,需配置 Encrypt Key

如需关闭加密(不推荐),可在初始化时设置:

const sdk = new HikSdk({
  appKey: 'your-app-key',
  appSecret: 'your-app-secret',
  userName: 'your-phone-number',
  password: 'your-password',
  enableEncrypt: false, // 关闭加密
});

项目结构

src/
├── core/                  # 核心模块
│   ├── auth.ts           # 认证管理(App/User Token)
│   ├── config.ts         # 配置校验
│   ├── crypto.ts         # RSA 加密/解密
│   ├── http.ts           # HTTP 客户端
│   └── logger.ts         # 日志
├── modules/               # 业务模块
│   ├── access/           # 门禁应用 API
│   ├── card/             # 卡片管理
│   ├── device/           # 设备控制
│   ├── face/             # 人脸管理
│   └── person/           # 人员管理
├── sdk.ts                # SDK 主类
└── index.ts              # 入口导出

examples/                  # 示例代码
├── demo.ts               # 综合示例
├── quick-start.ts        # 快速开始
├── mock.ts               # 远程核验服务
├── access-demo.ts        # 门禁应用示例
└── face-access-demo.ts   # 人脸设备示例

开发

# 安装依赖
npm install

# 构建
npm run build

# 运行测试
npm test

# 接收远程核验事件
npx tsx examples/mock.ts

#运行demo
npx tsx examples/demo.ts 2

License

MIT