快速入门
本文档将引导您在 5 分钟内完成智能采购平台 API 的接入,从申请凭证到完成第一次 API 调用。
准备工作
1. 注册账号
访问 智能采购平台控制台 注册企业账号。
2. 创建应用
在控制台创建应用,获取 API 凭证:
- App ID - 应用标识符
- App Secret - 应用密钥(请妥善保管)
本地开发凭证(仅用于开发测试):
- App ID:
dev_app_local- App Secret:
dev_secret_local_do_not_use_in_production
3. 配置白名单
在控制台配置 IP 白名单,确保您的服务器可以访问 API。
第一个 API 调用
Step 1: 安装依赖
使用 Node.js 作为示例(也支持 Python、Java 等语言):
npm install cryptoStep 2: 生成签名
创建签名工具函数:
signature.ts
import crypto from 'crypto';
interface SignatureParams {
method: string; // HTTP 方法:GET, POST, PUT, DELETE
path: string; // 请求路径:/api/v1/intents
timestamp: string; // 时间戳(毫秒)
body: string; // 请求体 JSON 字符串(GET 请求为空字符串)
appSecret: string; // 应用密钥
}
export function generateSignature(params: SignatureParams): string {
const { method, path, timestamp, body, appSecret } = params;
// 拼接签名字符串:METHOD + PATH + TIMESTAMP + BODY
const signString = `${method}${path}${timestamp}${body}`;
// 使用 HMAC-SHA256 计算签名
const signature = crypto
.createHmac('sha256', appSecret)
.update(signString)
.digest('hex');
return signature;
}Step 3: 发送请求
创建 API 调用函数:
api-client.ts
import { generateSignature } from './signature';
const API_BASE_URL = 'http://localhost:3000';
const APP_ID = 'dev_app_local';
const APP_SECRET = 'dev_secret_local_do_not_use_in_production';
async function callAPI(
method: string,
path: string,
body?: object
): Promise<any> {
const timestamp = Date.now().toString();
const bodyString = body ? JSON.stringify(body) : '';
// 生成签名
const signature = generateSignature({
method,
path,
timestamp,
body: bodyString,
appSecret: APP_SECRET
});
// 构造请求头
const headers: Record<string, string> = {
'X-App-Id': APP_ID,
'X-Timestamp': timestamp,
'X-Signature': signature,
};
if (body) {
headers['Content-Type'] = 'application/json';
}
// 发送请求
const response = await fetch(`${API_BASE_URL}${path}`, {
method,
headers,
body: bodyString || undefined,
});
return response.json();
}Step 4: 创建采购意图
调用 API 创建一个采购意图:
example.ts
import { callAPI } from './api-client';
async function createIntent() {
const intentData = {
userId: 'user_001',
platform: 'TAOBAO',
productUrl: 'https://item.taobao.com/item.htm?id=123456',
title: 'Apple iPhone 15 Pro 256GB 深空黑色',
price: 8999,
quantity: 1,
recipientName: '张三',
address: '北京市朝阳区望京SOHO T1 1001',
phone: '13800138000',
remarks: '测试订单'
};
try {
const result = await callAPI('POST', '/api/v1/intents', intentData);
console.log('创建成功:', result);
return result;
} catch (error) {
console.error('创建失败:', error);
throw error;
}
}
// 执行调用
createIntent();Step 5: 查看结果
成功响应示例:
{
"code": 0,
"message": "操作成功",
"data": {
"id": "intent_67890",
"userId": "user_001",
"platform": "TAOBAO",
"status": "SUBMITTED",
"createdAt": "2026-02-25T10:30:00.000Z",
"updatedAt": "2026-02-25T10:30:00.000Z"
}
}使用 cURL 调用
如果你习惯使用命令行工具,可以使用我们提供的签名生成脚本:
1. 下载签名脚本
# 使用项目中的签名生成工具
cd apps/api
node generate-signature.ts2. 手动构造请求
# 设置变量
APP_ID="dev_app_local"
APP_SECRET="dev_secret_local_do_not_use_in_production"
TIMESTAMP=$(date +%s%3N)
METHOD="POST"
PATH="/api/v1/intents"
BODY='{"userId":"user_001","platform":"TAOBAO","productUrl":"https://item.taobao.com/item.htm?id=123456","title":"测试商品","price":99.99,"quantity":1,"recipientName":"张三","address":"北京市朝阳区","phone":"13800138000"}'
# 生成签名(需要 OpenSSL)
SIGNATURE=$(echo -n "${METHOD}${PATH}${TIMESTAMP}${BODY}" | openssl dgst -sha256 -hmac "${APP_SECRET}" | awk '{print $2}')
# 发送请求
curl -X POST "http://localhost:3000${PATH}" \
-H "Content-Type: application/json" \
-H "X-App-Id: ${APP_ID}" \
-H "X-Timestamp: ${TIMESTAMP}" \
-H "X-Signature: ${SIGNATURE}" \
-d "${BODY}"常见问题
Q1: 签名验证失败(401 错误)
原因:
- App ID 或 App Secret 错误
- 时间戳格式不正确(应该是毫秒级时间戳)
- 签名字符串拼接顺序错误
- 请求体格式化问题(JSON 字符串中不应有多余空格)
解决方法:
// ❌ 错误 - 时间戳为秒级
const timestamp = Math.floor(Date.now() / 1000);
// ✅ 正确 - 时间戳为毫秒级
const timestamp = Date.now().toString();
// ❌ 错误 - JSON 格式化后有多余空格
const body = JSON.stringify(data, null, 2);
// ✅ 正确 - 紧凑的 JSON 字符串
const body = JSON.stringify(data);Q2: 时间戳过期(401 错误)
请求的时间戳与服务器时间相差不能超过 5 分钟。
解决方法:
- 确保本地时间与标准时间同步
- 使用 NTP 服务同步系统时间
# Linux/macOS 同步时间
sudo ntpdate -u ntp.aliyun.comQ3: 请求参数错误(400 错误)
检查必填参数是否完整:
// 创建意图的必填参数
const requiredFields = [
'userId',
'platform',
'productUrl',
'title',
'price',
'quantity',
'recipientName',
'address',
'phone'
];
// 验证参数
function validateIntent(data: any): boolean {
return requiredFields.every(field => data[field] !== undefined);
}Q4: 网络超时
解决方法:
- 检查网络连接
- 确认 API 端点地址正确
- 增加请求超时时间
const response = await fetch(url, {
method,
headers,
body,
signal: AbortSignal.timeout(30000) // 30秒超时
});下一步
恭喜!您已经成功完成了第一次 API 调用。接下来可以:
获取帮助
如果您在接入过程中遇到问题:
- 📧 技术支持:support@procure-core.com
- 💬 开发者社区:GitHub Discussions
- 📚 完整文档:技术文档