安装指南
将 Chaindoc SDK 集成到您的项目中。我们提供两个包:Server SDK 用于后端开发(文档管理、签名、验证),Embed SDK 用于在前端快速嵌入签署界面。
开始之前
如果您还没有账户,请先阅读 快速入门指南 完成账户设置。
Server SDK
Server SDK 负责所有后端操作:创建文档、发送 签名请求、管理团队以及触发区块链验证。它是对 REST API 的轻量级封装,如果您已阅读 API 文档,方法名会非常熟悉。
安装包
npm install @chaindoc_io/server-sdk配置环境变量
在项目根目录创建 `.env` 文件。您需要在此处填入密钥。
# Production keys
CHAINDOC_SECRET_KEY=sk_live_xxxxxxxxxxxxx
# Staging/Testing keys
# CHAINDOC_SECRET_KEY=sk_test_xxxxxxxxxxxxx
# Optional: Custom API endpoint
# CHAINDOC_API_URL=https://api.chaindoc.io初始化 SDK
import { Chaindoc } from '@chaindoc_io/server-sdk';
// Basic initialization
export const chaindoc = new Chaindoc({
secretKey: process.env.CHAINDOC_SECRET_KEY!,
});
// Advanced configuration
export const chaindocAdvanced = new Chaindoc({
secretKey: process.env.CHAINDOC_SECRET_KEY!,
baseUrl: process.env.CHAINDOC_API_URL, // Optional
timeout: 60000, // 60 seconds
retry: {
maxRetries: 5,
baseDelayMs: 1000,
maxDelayMs: 10000,
},
headers: {
'X-Custom-Header': 'value',
},
});基础配置适用于大多数项目。如果您需要批量处理大量文档,建议调整重试设置,因为 API 有速率限制。
验证连接
// Test API connection
const health = await chaindoc.healthCheck();
if (health.status === 'ok' && health.apiKeyValid) {
console.log('Connected to Chaindoc API');
console.log('User ID:', health.userId);
} else {
console.error('Connection failed');
}如果连接失败,请仔细检查密钥是否以 `sk_live_`(生产环境)或 `sk_test_`(沙盒环境)开头。最常见的问题是误用了公钥。
Embed SDK
Embed SDK 让您可以在自己的 Web 应用中展示 Chaindoc 签署界面。您的用户无需离开您的网站即可完成文档签署。它支持 React、Vue、Angular 或原生 JavaScript。
安装包
npm install @chaindoc_io/embed-sdkCDN 方式适用于快速原型或没有构建流程的网站。对于生产环境,建议使用 npm 包以获得 tree-shaking 和版本控制支持。
配置环境变量
Embed SDK 使用公钥(`pk_`),可以安全地包含在客户端代码中。
# .env.local
REACT_APP_CHAINDOC_PUBLIC_KEY=pk_live_xxxxx
# or for Next.js
NEXT_PUBLIC_CHAINDOC_PUBLIC_KEY=pk_live_xxxxx在应用中初始化
// hooks/useChaindoc.ts
import { useRef, useEffect } from 'react';
import { ChaindocEmbed } from '@chaindoc_io/embed-sdk';
export function useChaindoc() {
const sdkRef = useRef<ChaindocEmbed | null>(null);
useEffect(() => {
sdkRef.current = new ChaindocEmbed({
publicKey: process.env.REACT_APP_CHAINDOC_PUBLIC_KEY!,
environment: 'production',
});
return () => {
sdkRef.current?.destroy();
};
}, []);
return sdkRef.current;
}框架特定配置
以下示例展示了如何在各框架中将 Embed SDK 配置为提供者或服务。如果您在后端使用 Server SDK,则不需要提供者模式,只需在需要的地方导入即可。
Next.js (App Router)
'use client';
import { createContext, useContext, useEffect, useRef } from 'react';
import { ChaindocEmbed } from '@chaindoc_io/embed-sdk';
const ChaindocContext = createContext<ChaindocEmbed | null>(null);
export function ChaindocProvider({ children }: { children: React.ReactNode }) {
const sdkRef = useRef<ChaindocEmbed | null>(null);
useEffect(() => {
if (!sdkRef.current) {
sdkRef.current = new ChaindocEmbed({
publicKey: process.env.NEXT_PUBLIC_CHAINDOC_PUBLIC_KEY!,
});
}
return () => {
sdkRef.current?.destroy();
};
}, []);
return (
<ChaindocContext.Provider value={sdkRef.current}>
{children}
</ChaindocContext.Provider>
);
}
export const useChaindoc = () => useContext(ChaindocContext);Next.js (Pages Router)
import type { AppProps } from 'next/app';
import { useEffect, useRef } from 'react';
import { ChaindocEmbed } from '@chaindoc_io/embed-sdk';
export default function App({ Component, pageProps }: AppProps) {
const sdkRef = useRef<ChaindocEmbed | null>(null);
useEffect(() => {
sdkRef.current = new ChaindocEmbed({
publicKey: process.env.NEXT_PUBLIC_CHAINDOC_PUBLIC_KEY!,
});
return () => {
sdkRef.current?.destroy();
};
}, []);
return <Component {...pageProps} />;
}Nuxt 3
import { ChaindocEmbed } from '@chaindoc_io/embed-sdk';
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig();
const chaindoc = new ChaindocEmbed({
publicKey: config.public.chaindocPublicKey,
});
return {
provide: {
chaindoc,
},
};
});Angular
import { Injectable, OnDestroy } from '@angular/core';
import { ChaindocEmbed } from '@chaindoc_io/embed-sdk';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root'
})
export class ChaindocService implements OnDestroy {
private sdk: ChaindocEmbed;
constructor() {
this.sdk = new ChaindocEmbed({
publicKey: environment.chaindocPublicKey,
});
}
getSdk(): ChaindocEmbed {
return this.sdk;
}
ngOnDestroy(): void {
this.sdk.destroy();
}
}TypeScript 配置
两个 SDK 都包含完整的 TypeScript 定义,您不需要额外的 `@types` 包。
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"types": ["node"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}如果您使用的是较旧版本的 TypeScript(< 5.0),请将 `"moduleResolution": "bundler"` 替换为 `"node"`。
开发环境与生产环境
在开发过程中使用测试密钥,以避免意外创建真实文档或向实际收件人发送签名邮件。
开发环境配置
// Use test keys for development
const chaindoc = new Chaindoc({
secretKey: 'sk_test_xxxxx',
baseUrl: 'https://api.chaindoc.io',
});
const embed = new ChaindocEmbed({
publicKey: 'pk_test_xxxxx',
environment: 'staging',
debug: true, // Enable detailed logs
});`debug: true` 标志会在控制台打印请求/响应详情。虽然输出较多,但在排查问题时非常有用。
生产环境配置
// Use live keys for production
const chaindoc = new Chaindoc({
secretKey: process.env.CHAINDOC_SECRET_KEY!, // sk_live_xxxxx
});
const embed = new ChaindocEmbed({
publicKey: process.env.NEXT_PUBLIC_CHAINDOC_PUBLIC_KEY!, // pk_live_xxxxx
environment: 'production',
});验证安装
运行以下检查以确保一切配置正确:
1检查 SDK 版本在应用中运行 `console.log(ChaindocEmbed.version)`。如果能输出版本号,说明包已正确安装。
2测试 API 连接从后端调用 `chaindoc.healthCheck()`。成功响应表示密钥有效且 API 可访问。
3尝试文件上传使用 `chaindoc.media.upload()` 上传一个小型测试 PDF。这可以验证认证、网络和文件处理是否正常工作。
4打开签署界面初始化 Embed SDK 并使用测试会话调用 `openSignatureFlow()`。如果弹窗出现,说明配置成功。
故障排除
"Module not found" 错误
这通常意味着包未正确安装或存在缓存版本冲突。清除缓存后重新安装:
# npm
rm -rf node_modules package-lock.json
npm install
# yarn
rm -rf node_modules yarn.lock
yarn installTypeScript 类型错误
确保已安装 Node.js 类型且 `tsconfig.json` 使用了正确的模块解析方式。大多数问题源于 `moduleResolution` 设置不匹配。
npm install --save-dev @types/nodeAPI 密钥错误
如果您收到 401 或 403 响应,请检查以下内容:
- 401 Unauthorized 表示密钥无效或已过期。请在控制台重新生成。
- 403 Forbidden 表示您的套餐不包含 API 访问权限。您需要 Business 套餐。
- 确保使用正确的密钥类型:`pk_` 密钥用于 Embed SDK(前端),`sk_` 密钥用于 Server SDK(后端)。混淆两者是最常见的错误。
- 测试密钥(`_test_`)仅适用于沙盒环境。正式密钥(`_live_`)用于生产环境。
下一步
SDK 安装完成后,选择您的下一步: