import { NextRequest, NextResponse } from 'next/server' // 神射手开放API文档 - OpenAPI 3.0 格式 const OPENAPI_SPEC = { openapi: '3.0.3', info: { title: '神射手数据中台 API', description: ` 神射手是一个用户资产数字化平台,提供用户画像、AI标签、RFM评分等数据服务。 ## 认证方式 所有API请求需要在Header中携带API密钥: - **Authorization**: Bearer YOUR_API_KEY(必需) - **X-API-Secret**: YOUR_API_SECRET(可选,增强安全性) ## 基础信息 - 基础URL: https://your-domain.com/api/shensheshou - 请求格式: JSON - 响应格式: JSON - 字符编码: UTF-8 ## 计费说明 - 每次API调用消耗积分(credits) - 不同接口消耗积分不同 - 批量接口享受折扣 ## 字段权限 返回字段根据API密钥配置的字段权限决定,可在开放API管理中配置。 `.trim(), version: '1.0.0', contact: { name: '神射手技术支持', email: 'support@shensheshou.com', }, }, servers: [ { url: '{protocol}://{host}/api/shensheshou', description: '神射手API服务器', variables: { protocol: { default: 'https', enum: ['https', 'http'] }, host: { default: 'your-domain.com' }, }, }, ], tags: [ { name: 'user', description: '用户查询服务 - 查询用户画像和基本信息' }, { name: 'tag', description: '标签服务 - 获取、应用和管理用户标签' }, { name: 'ai', description: 'AI服务 - AI对话、智能分析和自动打标' }, { name: 'data', description: '数据服务 - 数据流入和同步' }, { name: 'package', description: '流量包 - 创建和导出用户流量包' }, ], paths: { '/': { get: { tags: ['user'], operationId: 'queryUser', summary: '用户画像查询', description: '根据手机号或QQ查询完整用户画像。返回字段根据API密钥权限决定。', parameters: [ { name: 'endpoint', in: 'query', required: true, schema: { type: 'string', enum: ['user'] }, description: '固定值: user' }, { name: 'phone', in: 'query', required: false, schema: { type: 'string', pattern: '^1[3-9]\\d{9}$' }, description: '11位手机号' }, { name: 'qq', in: 'query', required: false, schema: { type: 'string', pattern: '^[1-9]\\d{4,10}$' }, description: 'QQ号码(5-11位)' }, { name: 'fields', in: 'query', required: false, schema: { type: 'string' }, description: '指定返回字段(逗号分隔): phone,qq,rfm_score,user_level,tags,behavior,location' }, ], responses: { '200': { description: '查询成功', content: { 'application/json': { schema: { $ref: '#/components/schemas/UserResponse' }, example: { success: true, data: { phone: '138****8000', rfm_score: 85, user_level: 'A', tags: ['高价值', '活跃用户', '电商偏好'], last_active: '2026-01-30', }, credits_used: 5, credits_remaining: 995, }, }, }, }, '401': { $ref: '#/components/responses/Unauthorized' }, '404': { $ref: '#/components/responses/NotFound' }, }, security: [{ bearerAuth: [] }], }, post: { tags: ['user', 'data', 'ai'], operationId: 'postEndpoint', summary: '通用POST端点', description: '根据endpoint参数调用不同服务:users/batch(批量查询)、ingest(数据流入)、ai/chat(AI对话)、ai/tag(AI打标)等', requestBody: { required: true, content: { 'application/json': { schema: { $ref: '#/components/schemas/PostRequest' }, examples: { batch_query: { summary: '批量用户查询', value: { endpoint: 'users/batch', phones: ['13800138001', '13800138002'], fields: ['rfm_score', 'tags', 'user_level'], }, }, data_ingest: { summary: '数据流入', value: { endpoint: 'ingest', source: 'cunkebao', users: [ { phone: '13800138001', name: '张三', tags: ['高意向'] }, { phone: '13800138002', name: '李四' }, ], }, }, ai_chat: { summary: 'AI对话', value: { endpoint: 'ai/chat', message: '帮我查询13800138000的用户画像', }, }, ai_tag: { summary: 'AI智能打标', value: { endpoint: 'ai/tag', phones: ['13800138001', '13800138002'], strategy: 'rfm', }, }, }, }, }, }, responses: { '200': { description: '请求成功', content: { 'application/json': { schema: { $ref: '#/components/schemas/GenericResponse' }, }, }, }, '401': { $ref: '#/components/responses/Unauthorized' }, '400': { $ref: '#/components/responses/BadRequest' }, }, security: [{ bearerAuth: [] }], }, }, '/tags': { get: { tags: ['tag'], operationId: 'listTags', summary: '获取标签列表', description: '获取系统中所有可用标签及其统计信息', parameters: [ { name: 'category', in: 'query', required: false, schema: { type: 'string', enum: ['value', 'behavior', 'preference', 'custom'] }, description: '标签分类' }, ], responses: { '200': { description: '成功', content: { 'application/json': { example: { success: true, data: { tags: [ { id: 'tag_001', name: '高价值用户', category: 'value', count: 125000 }, { id: 'tag_002', name: '活跃用户', category: 'behavior', count: 450000 }, ], total: 45, }, }, }, }, }, }, security: [{ bearerAuth: [] }], }, }, '/packages': { get: { tags: ['package'], operationId: 'listPackages', summary: '获取流量包列表', description: '获取已创建的流量包列表', responses: { '200': { description: '成功', content: { 'application/json': { example: { success: true, data: { packages: [ { id: 'pkg_001', name: '高价值用户包', count: 5000, created_at: '2026-01-30' }, ], total: 10, }, }, }, }, }, }, security: [{ bearerAuth: [] }], }, post: { tags: ['package'], operationId: 'createPackage', summary: '创建流量包', description: '根据筛选条件创建用户流量包', requestBody: { required: true, content: { 'application/json': { example: { endpoint: 'packages/create', name: '高价值用户包', filters: { user_level: ['S', 'A'], tags: ['高价值'], }, }, }, }, }, responses: { '200': { description: '创建成功', content: { 'application/json': { example: { success: true, data: { package_id: 'pkg_002', name: '高价值用户包', count: 3500, }, }, }, }, }, }, security: [{ bearerAuth: [] }], }, }, }, components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', description: 'API密钥,格式: sk-xxx', }, apiSecret: { type: 'apiKey', in: 'header', name: 'X-API-Secret', description: 'API密钥Secret(可选,增强安全性)', }, }, schemas: { UserResponse: { type: 'object', properties: { success: { type: 'boolean' }, data: { type: 'object', properties: { phone: { type: 'string', description: '脱敏手机号' }, qq: { type: 'string', description: 'QQ号' }, rfm_score: { type: 'integer', minimum: 0, maximum: 100, description: 'RFM综合评分' }, user_level: { type: 'string', enum: ['S', 'A', 'B', 'C', 'D'], description: '用户等级' }, tags: { type: 'array', items: { type: 'string' }, description: '用户标签列表' }, behavior: { type: 'object', description: '行为数据' }, location: { type: 'object', description: '位置信息' }, last_active: { type: 'string', format: 'date', description: '最后活跃时间' }, }, }, credits_used: { type: 'integer', description: '本次消耗积分' }, credits_remaining: { type: 'integer', description: '剩余积分' }, }, }, PostRequest: { type: 'object', required: ['endpoint'], properties: { endpoint: { type: 'string', description: '端点名称' }, }, additionalProperties: true, }, GenericResponse: { type: 'object', properties: { success: { type: 'boolean' }, data: { type: 'object' }, message: { type: 'string' }, credits_used: { type: 'integer' }, credits_remaining: { type: 'integer' }, }, }, Error: { type: 'object', properties: { success: { type: 'boolean', example: false }, error: { type: 'string' }, code: { type: 'string' }, }, }, }, responses: { Unauthorized: { description: '认证失败', content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' }, example: { success: false, error: '无效的API密钥', code: 'INVALID_API_KEY' }, }, }, }, NotFound: { description: '资源不存在', content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' }, example: { success: false, error: '用户不存在', code: 'USER_NOT_FOUND' }, }, }, }, BadRequest: { description: '请求参数错误', content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' }, example: { success: false, error: '缺少必要参数', code: 'MISSING_PARAMS' }, }, }, }, }, }, } // Markdown格式的API文档 const MARKDOWN_DOC = `# 神射手数据中台 API 文档 > 版本: 1.0.0 | 更新时间: 2026-01-31 ## 概述 神射手是一个**用户资产数字化平台**,提供用户画像、AI标签、RFM评分等数据服务。通过本API,第三方应用可以: - 查询用户画像和标签 - 批量导入用户数据并自动完善标签 - 使用AI进行智能对话和分析 - 创建和导出用户流量包 --- ## 认证方式 所有API请求需要在Header中携带API密钥: \`\`\` Authorization: Bearer YOUR_API_KEY X-API-Secret: YOUR_API_SECRET # 可选,增强安全性 Content-Type: application/json \`\`\` ### 获取API密钥 1. 登录神射手管理后台 2. 进入「数据市场 → 开放接口」 3. 添加接入方并获取API Key和Secret --- ## 基础URL \`\`\` https://your-domain.com/api/shensheshou \`\`\` --- ## 接口列表 ### 1. 用户画像查询 查询单个用户的完整画像信息。 **请求** \`\`\`http GET /api/shensheshou?endpoint=user&phone=13800138000 \`\`\` **参数** | 参数 | 类型 | 必需 | 说明 | |------|------|:----:|------| | endpoint | string | 是 | 固定值: user | | phone | string | 否 | 11位手机号(与qq二选一) | | qq | string | 否 | QQ号码(与phone二选一) | | fields | string | 否 | 指定返回字段,逗号分隔 | **可用字段**: phone, qq, wechat, rfm_score, user_level, tags, behavior, location **响应示例** \`\`\`json { "success": true, "data": { "phone": "138****8000", "rfm_score": 85, "user_level": "A", "tags": ["高价值", "活跃用户", "电商偏好"], "last_active": "2026-01-30" }, "credits_used": 5, "credits_remaining": 995 } \`\`\` --- ### 2. 批量用户查询 批量查询多个用户画像,最多100个/次。 **请求** \`\`\`http POST /api/shensheshou Content-Type: application/json { "endpoint": "users/batch", "phones": ["13800138001", "13800138002"], "fields": ["rfm_score", "tags", "user_level"] } \`\`\` **响应示例** \`\`\`json { "success": true, "data": { "users": [ {"phone": "138****8001", "rfm_score": 78, "tags": ["活跃"], "user_level": "B"}, {"phone": "138****8002", "rfm_score": 92, "tags": ["高价值"], "user_level": "A"} ], "found": 2, "not_found": [] }, "credits_used": 8 } \`\`\` --- ### 3. 数据流入 将外部系统用户数据导入神射手,自动完善标签。 **请求** \`\`\`http POST /api/shensheshou Content-Type: application/json { "endpoint": "ingest", "source": "cunkebao", "users": [ {"phone": "13800138001", "name": "张三", "tags": ["高意向"]}, {"phone": "13800138002", "name": "李四"} ] } \`\`\` **响应示例** \`\`\`json { "success": true, "data": { "total": 2, "processed": 2, "enriched": 2, "new_tags_added": 8 } } \`\`\` --- ### 4. AI对话 与神射手AI进行自然语言对话,支持用户查询、数据分析等。 **请求** \`\`\`http POST /api/shensheshou Content-Type: application/json { "endpoint": "ai/chat", "message": "帮我查询13800138000的用户画像" } \`\`\` **响应示例** \`\`\`json { "success": true, "data": { "reply": "该用户是A级高价值用户,RFM评分85分,标签包括:高价值、活跃用户、电商偏好。最近30天内有5次互动记录。", "user_data": {...} } } \`\`\` --- ### 5. AI智能打标 使用AI为用户批量打标签。 **请求** \`\`\`http POST /api/shensheshou Content-Type: application/json { "endpoint": "ai/tag", "phones": ["13800138001", "13800138002"], "strategy": "rfm" } \`\`\` **策略选项**: rfm(RFM评分), behavior(行为分析), preference(偏好分析) --- ### 6. 获取标签列表 获取系统中所有可用标签。 **请求** \`\`\`http GET /api/shensheshou?endpoint=tags&category=value \`\`\` --- ### 7. 创建流量包 根据条件筛选用户并创建流量包。 **请求** \`\`\`http POST /api/shensheshou Content-Type: application/json { "endpoint": "packages/create", "name": "高价值用户包", "filters": { "user_level": ["S", "A"], "tags": ["高价值"] } } \`\`\` --- ## 错误码 | 错误码 | 说明 | |--------|------| | INVALID_API_KEY | API密钥无效或已过期 | | PERMISSION_DENIED | 无权限访问该接口 | | FIELD_NOT_ALLOWED | 无权限访问该字段 | | QUOTA_EXCEEDED | 调用配额已用尽 | | RATE_LIMITED | 请求频率超限 | | USER_NOT_FOUND | 用户不存在 | | MISSING_PARAMS | 缺少必要参数 | | INVALID_PARAMS | 参数格式错误 | --- ## 计费说明 | 接口 | 单价(积分/次) | |------|----------------| | 用户画像查询 | 1 | | 批量用户查询 | 0.8/人 | | 数据流入 | 0.5/人 | | AI对话 | 5 | | AI智能打标 | 2/人 | | 流量包创建 | 10 | | 流量包导出 | 0.1/人 | --- ## SDK示例 ### Python \`\`\`python import requests API_KEY = "sk-archer-xxxxx" BASE_URL = "https://your-domain.com/api/shensheshou" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } # 查询用户画像 response = requests.get( f"{BASE_URL}?endpoint=user&phone=13800138000", headers=headers ) print(response.json()) # 批量查询 response = requests.post(BASE_URL, headers=headers, json={ "endpoint": "users/batch", "phones": ["13800138001", "13800138002"] }) print(response.json()) \`\`\` ### JavaScript \`\`\`javascript const API_KEY = "sk-archer-xxxxx"; const BASE_URL = "https://your-domain.com/api/shensheshou"; // 查询用户画像 const response = await fetch(\`\${BASE_URL}?endpoint=user&phone=13800138000\`, { headers: { "Authorization": \`Bearer \${API_KEY}\`, } }); const data = await response.json(); console.log(data); // 批量查询 const batchResponse = await fetch(BASE_URL, { method: "POST", headers: { "Authorization": \`Bearer \${API_KEY}\`, "Content-Type": "application/json" }, body: JSON.stringify({ endpoint: "users/batch", phones: ["13800138001", "13800138002"] }) }); \`\`\` ### cURL \`\`\`bash # 查询用户画像 curl -X GET "https://your-domain.com/api/shensheshou?endpoint=user&phone=13800138000" \\ -H "Authorization: Bearer sk-archer-xxxxx" # 批量查询 curl -X POST "https://your-domain.com/api/shensheshou" \\ -H "Authorization: Bearer sk-archer-xxxxx" \\ -H "Content-Type: application/json" \\ -d '{"endpoint":"users/batch","phones":["13800138001","13800138002"]}' \`\`\` --- ## 联系支持 - 技术支持邮箱: support@shensheshou.com - 在线文档: https://docs.shensheshou.com --- *文档版本 1.0.0 - 最后更新: 2026-01-31* ` export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url) const format = searchParams.get('format') || 'json' // 获取当前域名作为服务器URL const host = request.headers.get('host') || 'localhost:3000' const protocol = request.headers.get('x-forwarded-proto') || 'http' // 更新服务器URL const spec = { ...OPENAPI_SPEC, servers: [ { url: `${protocol}://${host}/api/shensheshou`, description: '神射手API服务器', }, ], } if (format === 'openapi' || format === 'json') { return NextResponse.json(spec, { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=3600', }, }) } if (format === 'markdown' || format === 'md') { return new NextResponse(MARKDOWN_DOC, { headers: { 'Content-Type': 'text/markdown; charset=utf-8', 'Content-Disposition': 'attachment; filename="shensheshou-api-docs.md"', 'Access-Control-Allow-Origin': '*', }, }) } if (format === 'download') { return NextResponse.json(spec, { headers: { 'Content-Type': 'application/json', 'Content-Disposition': 'attachment; filename="shensheshou-openapi.json"', 'Access-Control-Allow-Origin': '*', }, }) } // 返回简化版文档信息 return NextResponse.json({ name: '神射手数据中台 API', version: '1.0.0', description: '用户资产数字化平台API,提供用户画像、AI标签、RFM评分等数据服务', docs: { openapi: `${protocol}://${host}/api/docs?format=openapi`, markdown: `${protocol}://${host}/api/docs?format=markdown`, download: `${protocol}://${host}/api/docs?format=download`, web: `${protocol}://${host}/data-market/api/docs`, }, endpoints: { base: `${protocol}://${host}/api/shensheshou`, auth: 'Header: Authorization: Bearer YOUR_API_KEY', }, quick_start: { step1: '获取API密钥:登录管理后台 → 数据市场 → 开放接口', step2: '阅读文档:访问上方 docs.web 链接', step3: '测试调用:使用curl或SDK调用API', }, }, { headers: { 'Access-Control-Allow-Origin': '*', }, }) } // 支持CORS export async function OPTIONS() { return new NextResponse(null, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }, }) }