CodeBoxCodeBox 文档

TypeScript SDK

使用 @codebox.club/sdk 在 Node.js 中快速集成 CodeBox 二维码能力

安装

npm install @codebox.club/sdk
pnpm add @codebox.club/sdk
yarn add @codebox.club/sdk

SDK 零运行时依赖,使用原生 fetch,适用于 Node.js 18+ 和现代浏览器。

快速开始

import { CodeBox } from '@codebox.club/sdk';

const client = new CodeBox({
  apiKey: 'cb_sk_xxxxxxxxxxxxxxxx',
});

// 生成带追踪的动态二维码
const qrcode = await client.qrcodes.create({
  content: 'https://example.com',
  mode: 'DYNAMIC',
  name: '我的二维码',
});

console.log(qrcode.shortLink); // https://www.codebox.club/s/AbCdEf

方法参考

client.qrcodes.create(params)

生成并保存二维码,返回带追踪的短链。DYNAMIC 模式消耗 1 次普通额度,STATIC 模式不消耗额度。

参数:

参数类型必填说明
contentstring要编码的 URL 或文本
modestringDYNAMIC(默认)或 STATIC
namestring二维码名称
templateIdstring模板 ID
keywordsstring[]自动匹配模板的关键词
logostringLogo 图片 URL
sizenumber图片尺寸(像素)
errorCorrectionLevelstring纠错等级:L / M / Q / H

返回值:

{
  id: string;              // 二维码 ID
  shortLink?: string;      // 追踪短链
  templateUsed: string;    // 使用的模板 ID
  matchedKeywords: string[]; // 匹配到的关键词
  styles: Record<string, unknown>; // 样式配置
}

示例:

const qrcode = await client.qrcodes.create({
  content: 'https://example.com',
  mode: 'DYNAMIC',
  name: '营销活动码',
  keywords: ['科技', '现代'],
});

client.qrcodes.getStats(id, options?)

获取二维码的扫码统计数据。

参数:

参数类型必填说明
idstring二维码 ID
options.startDatestring起始日期 YYYY-MM-DD(默认 30 天前)
options.endDatestring结束日期 YYYY-MM-DD(默认今天)

返回值:

{
  totalScans: number;
  uniqueUsers: number;
  deviceBreakdown: Record<string, number>; // { mobile: 72, desktop: 22, tablet: 5 }
  dailyScans: Array<{ date: string; count: number }>;
  topBrowsers: Array<{ browser: string; count: number }>;
  topOS: Array<{ os: string; count: number }>;
  geoData: Array<{ country: string; region: string; city: string; count: number }>;
}

示例:

const stats = await client.qrcodes.getStats('clxxx...', {
  startDate: '2026-02-01',
  endDate: '2026-03-01',
});

console.log(`总扫描: ${stats.totalScans}, 独立用户: ${stats.uniqueUsers}`);

client.qrcodes.update(id, params)

更新动态二维码的目标 URL、名称或状态。

参数:

参数类型必填说明
idstring二维码 ID
params.targetUrlstring新的目标 URL
params.namestring新名称
params.statusstringREADYEXPIREDDELETED

返回值:

{
  id: string;
  targetUrl: string;
  name: string | null;
  status: string;
  updatedAt: string;
}

示例:

await client.qrcodes.update('clxxx...', {
  targetUrl: 'https://example.com/new-page',
  name: '更新后的名称',
});

client.templates.list()

获取可用的二维码风格模板列表。

返回值:

{
  totalTemplates: number;
  tags: string[];
  categories: Array<{
    source: string;
    count: number;
    templates: Array<{
      id: string;
      name: string;
      category: string;
      tags?: string[];
      previewImage?: string;
    }>;
  }>;
}

示例:

const catalog = await client.templates.list();

console.log(`共 ${catalog.totalTemplates} 个模板`);
catalog.categories.forEach(cat => {
  console.log(`${cat.source}: ${cat.count} 个`);
});

client.qrcodes.list(params?)

获取用户的二维码列表,支持分页和筛选。

参数:

参数类型必填说明
params.pagenumber页码(默认 1)
params.sizenumber每页数量,最大 50(默认 10)
params.modestring按模式筛选:STATIC / DYNAMIC / AI
params.keywordstring按名称或描述搜索

返回值:

{
  data: Array<{
    id: string;
    name: string | null;
    mode: string;
    status: string;
    targetUrl: string;
    scanCount: number;
    createdAt: string;
    updatedAt: string;
  }>;
  pagination: {
    page: number;
    size: number;
    total: number;
    totalPages: number;
  };
}

示例:

const result = await client.qrcodes.list({
  page: 1,
  size: 20,
  mode: 'DYNAMIC',
});

console.log(`共 ${result.pagination.total} 个二维码`);
result.data.forEach(qr => {
  console.log(`${qr.name}: ${qr.scanCount} 次扫描`);
});

client.qrcodes.delete(id)

软删除二维码。删除后关联的短链接也会被禁用。

参数:

参数类型必填说明
idstring二维码 ID

返回值:

{
  id: string;
  deleted: boolean;
}

示例:

await client.qrcodes.delete('clxxx...');

client.qrcodes.clone(id, params?)

克隆已有的二维码,支持修改名称和内容。克隆动态码消耗 1 次额度,克隆静态码不消耗。

参数:

参数类型必填说明
idstring要克隆的二维码 ID
params.namestring新名称(默认在原名后加"(副本)")
params.contentstring新的内容 URL

返回值:

{
  id: string;        // 新二维码 ID
  clonedFrom: string; // 原二维码 ID
  name: string | null;
  shortLink?: string;
}

示例:

const cloned = await client.qrcodes.clone('clxxx...', {
  name: '克隆的二维码',
  content: 'https://example.com/new-page',
});

client.qrcodes.batchCreate(items)

批量生成二维码(最多 20 个),支持 partial failure。每个非静态 item 消耗 1 次额度,静态码不消耗。

参数:

参数类型必填说明
itemsBatchGenerateItem[]二维码配置数组(最多 20 个)

每个 item 的结构与 create() 参数相同。

返回值:

{
  total: number;      // 总数
  succeeded: number;  // 成功数
  failed: number;     // 失败数
  results: Array<{
    index: number;
    success: boolean;
    data?: { id: string; shortLink?: string; templateUsed: string };
    error?: string;
  }>;
}

示例:

const batch = await client.qrcodes.batchCreate([
  { content: 'https://page1.com', name: '页面1' },
  { content: 'https://page2.com', name: '页面2', templateId: 'tech-modern-01' },
  { content: 'https://page3.com', name: '页面3', mode: 'STATIC' },
]);

console.log(`成功: ${batch.succeeded}, 失败: ${batch.failed}`);
batch.results.forEach(r => {
  if (r.success) {
    console.log(`#${r.index}: ${r.data!.id}`);
  } else {
    console.error(`#${r.index}: ${r.error}`);
  }
});

client.qrcodes.getScans(id, params?)

获取二维码的原始扫描事件列表(分页)。

参数:

参数类型必填说明
idstring二维码 ID
params.pagenumber页码(默认 1)
params.sizenumber每页数量,最大 100(默认 20)
params.startDatestring起始日期 YYYY-MM-DD
params.endDatestring结束日期 YYYY-MM-DD

返回值:

{
  data: Array<{
    id: string;
    eventType: string;   // 'impression' | 'click'
    device: string;
    os: string;
    browser: string;
    country: string;
    region: string;
    city: string;
    timestamp: string;
  }>;
  pagination: {
    page: number;
    size: number;
    total: number;
    totalPages: number;
  };
}

示例:

const scans = await client.qrcodes.getScans('clxxx...', {
  page: 1,
  size: 50,
  startDate: '2026-03-01',
});

scans.data.forEach(scan => {
  console.log(`${scan.timestamp} - ${scan.device} ${scan.browser} from ${scan.city}`);
});

client.webhooks.create(params)

创建 Webhook,监听二维码事件。

参数:

参数类型必填说明
urlstringWebhook 接收 URL
eventsstring[]订阅的事件列表

可订阅的事件:scan.createdqrcode.created

返回值:

{
  id: string;
  url: string;
  events: string[];
  secret: string;    // 用于验证签名
  status: string;
  createdAt: string;
}

示例:

const webhook = await client.webhooks.create({
  url: 'https://your-server.com/webhooks',
  events: ['scan.created', 'qrcode.created'],
});

console.log(`Webhook secret: ${webhook.secret}`);

client.webhooks.list(params?)

获取 Webhook 列表。

参数:

参数类型必填说明
params.pagenumber页码(默认 1)
params.sizenumber每页数量(默认 10)

示例:

const result = await client.webhooks.list({ page: 1 });
result.list.forEach(wh => {
  console.log(`${wh.url} - ${wh.events.join(', ')} (${wh.status})`);
});

client.webhooks.update(id, params)

更新 Webhook 配置。

参数:

参数类型必填说明
idstringWebhook ID
params.urlstring新的 URL
params.eventsstring[]新的事件列表
params.statusstringACTIVEDISABLED

示例:

await client.webhooks.update('webhook_id', {
  events: ['scan.created'],
  status: 'ACTIVE',
});

client.webhooks.delete(id)

删除 Webhook。

示例:

await client.webhooks.delete('webhook_id');

错误处理

SDK 提供类型化的错误类,便于精确处理不同场景:

import { CodeBox, CodeBoxError, AuthenticationError, RateLimitError } from '@codebox.club/sdk';

const client = new CodeBox({ apiKey: 'cb_sk_xxx' });

try {
  await client.qrcodes.create({ content: 'https://example.com' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    // API Key 无效或已过期
    console.error('鉴权失败:', error.message);
  } else if (error instanceof RateLimitError) {
    // 超出频率限制,可获取重试时间
    console.error(`请在 ${error.retryAfter} 秒后重试`);
  } else if (error instanceof CodeBoxError) {
    // 其他 API 错误
    console.error(`错误 ${error.status}: ${error.message}`);
  }
}
错误类触发条件关键属性
AuthenticationErrorAPI Key 无效、已删除或缺少权限(401)status, code
RateLimitError超出频率限制或每日上限(429)retryAfter
CodeBoxError其他 API 错误(400/403/500),基类status, code

额度不足时返回 403 + code: "CREDIT_EXHAUSTED"。可通过 GET /api/v1/credits/balance 提前检查余额,或在 Dashboard → 充值额度 购买额度包。

配置

const client = new CodeBox({
  apiKey: 'cb_sk_xxxxxxxxxxxxxxxx',
  baseUrl: 'https://www.codebox.club',  // 默认值,通常无需修改
});
配置项类型默认值说明
apiKeystringAPI Key(必填)
baseUrlstringhttps://www.codebox.clubAPI 基础 URL

On this page