3.7 KiB
3.7 KiB
安装 SDK 与初始化
详细指南:安装 @websopy/sdk,配置 WebsopyClient,发送第一个 API 请求。
📦 SDK 概述
Websopy 提供多种语言的 SDK:
| 语言 | SDK | 源码 |
|---|---|---|
| JavaScript/TypeScript | @websopy/sdk |
GitHub |
| Python | websopy-sdk |
GitHub |
| Go | github.com/websopy/sdk-go |
GitHub |
| Java | com.websopy:sdk |
GitHub |
本教程以 JavaScript/TypeScript 为例。
🚀 安装
npm
npm install @websopy/sdk
yarn
yarn add @websopy/sdk
pnpm
pnpm add @websopy/sdk
CDN(浏览器端)
<script src="https://unpkg.com/@websopy/sdk/dist/websopy.min.js"></script>
⚙️ 初始化配置
基本配置
import { WebsopyClient } from '@websopy/sdk'
const client = new WebsopyClient({
apiKey: 'ws_live_xxxxxxxxxxxx',
// API 版本(可选,默认 v1)
version: 'v1',
// 超时时间(毫秒)
timeout: 30000,
// 重试次数
retries: 3
})
多环境配置
const config = {
// 开发环境
dev: {
apiKey: 'ws_test_xxxxx',
baseUrl: 'https://api-dev.websopy.com/v1'
},
// 生产环境
prod: {
apiKey: process.env.WEBSOPY_API_KEY,
baseUrl: 'https://api.websopy.com/v1'
}
}
const client = new WebsopyClient(
process.env.NODE_ENV === 'production' ? config.prod : config.dev
)
环境变量
创建 .env 文件:
WEBSOPY_API_KEY=ws_live_xxxxxxxxxxxx
WEBSOPY_BASE_URL=https://api.websopy.com/v1
WEBSOPY_TIMEOUT=30000
import 'dotenv/config'
import { WebsopyClient } from '@websopy/sdk'
const client = new WebsopyClient({
apiKey: process.env.WEBSOPY_API_KEY,
baseUrl: process.env.WEBSOPY_BASE_URL
})
📚 API 模块
SDK 按功能模块组织:
// 用户管理
client.user
// 项目管理
client.project
// 文件存储
client.storage
// AI 功能
client.ai
// 支付功能
client.payment
// Webhook
client.webhook
🧪 完整示例
import { WebsopyClient } from '@websopy/sdk'
async function demo() {
const client = new WebsopyClient({
apiKey: process.env.WEBSOPY_API_KEY
})
// 1. 获取用户信息
const user = await client.user.getProfile()
console.log('用户:', user.name)
// 2. 列出项目
const { items: projects } = await client.project.list({
limit: 10,
status: 'active'
})
// 3. 创建项目
const project = await client.project.create({
name: '新项目',
description: '通过 SDK 创建'
})
// 4. 上传文件
const file = await client.storage.upload({
file: './demo.pdf',
folder: 'documents'
})
console.log('文件上传成功:', file.url)
}
demo().catch(console.error)
🔧 TypeScript 类型
SDK 提供完整的 TypeScript 类型定义:
import type {
Project,
User,
CreateProjectOptions
} from '@websopy/sdk/types'
function createProject(options: CreateProjectOptions): Promise<Project> {
return client.project.create(options)
}
❓ 常见问题
Q: ESM 和 CommonJS 兼容?
是的,SDK 同时支持两种模块格式:
// ESM
import { WebsopyClient } from '@websopy/sdk'
// CommonJS
const { WebsopyClient } = require('@websopy/sdk')
Q: 如何调试?
const client = new WebsopyClient({
apiKey: process.env.WEBSOPY_API_KEY,
debug: true // 打印详细日志
})
上一步: 5 分钟快速上手
下一步: API Key 创建与管理