@gt6/sdk
Version:
GT6 SDK for articles management - A comprehensive JavaScript/TypeScript library for managing articles, categories, and tags in GT6 platform
2,109 lines (1,726 loc) • 63.8 kB
Markdown
# @gt6/sdk
GT6 SDK 是一个用于管理文章、分类和标签的JavaScript/TypeScript库,专门为GT6平台设计。
## 安装
```bash
npm install @gt6/sdk
```
## 快速开始
### 基础配置
```typescript
import { GT6SDK } from '@gt6/sdk';
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
// 文章相关配置
rootCategoryId: '969287034', // 文章根分类ID
tagAlias: '002', // 文章标签别名
// 产品相关配置
productRootCategoryId: '277233', // 产品根分类ID
productTagAlias: '01', // 产品标签别名
// 缓存配置
cache: {
enabled: true,
ttl: 300000 // 5分钟
}
});
```
### 配置选项
| 字段 | 类型 | 必需 | 默认值 | 描述 |
|------|------|------|--------|------|
| `baseUrl` | string | ✅ | - | API 基础URL |
| `platformId` | string \| number | ✅ | - | 平台ID |
| `rootCategoryId` | string \| number | ❌ | '671920' | 文章根分类ID |
| `tagAlias` | string | ❌ | '001' | 文章标签别名 |
| `productRootCategoryId` | string \| number | ❌ | '277233' | 产品根分类ID |
| `productTagAlias` | string | ❌ | '01' | 产品标签别名 |
| `timeout` | number | ❌ | 10000 | 请求超时时间(毫秒) |
| `cache.enabled` | boolean | ❌ | true | 是否启用缓存 |
| `cache.ttl` | number | ❌ | 300000 | 缓存时间(毫秒) |
### 基本使用
```typescript
import { GT6SDK } from '@gt6/sdk';
// 初始化SDK
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
rootCategoryId: '969287034', // 可选,默认为671920
tagAlias: '002', // 可选,默认为001
productRootCategoryId: '277233',
productTagAlias: '01',
cache: {
enabled: true,
ttl: 300000
}
});
// 获取文章详情
const article = await sdk.getArticle(921546067);
console.log(article.title);
// 获取分类列表
const categories = await sdk.getCategories();
console.log('分类列表:', categories.map(cat => cat.categoryName));
// 获取标签列表
const tags = await sdk.getTags();
console.log('标签列表:', tags.map(tag => tag.tagName));
// 根据分类获取文章
const categoryArticles = await sdk.getArticlesByCategory(782714);
console.log(`分类文章总数: ${categoryArticles.total}`);
// 根据标签获取文章
const tagArticles = await sdk.getArticlesByTag(236656846);
console.log(`标签文章总数: ${tagArticles.total}`);
// 获取分类层级路径
const categoryPath = await sdk.getCategoryPath(782714);
console.log('面包屑路径:', categoryPath.breadcrumbs.map(crumb => crumb.categoryName).join(' > '));
// 获取子分类
const subCategories = await sdk.getSubCategories(671920);
console.log(`子分类数量: ${subCategories.total}`);
```
### 高级功能
```typescript
// 按分类获取文章
const categoryArticles = await sdk.getArticlesByCategory(782714);
// 按标签获取文章
const tagArticles = await sdk.getArticlesByTag(236656846);
// 获取分类层级路径(用于面包屑导航)
const categoryPath = await sdk.getCategoryPath(782714);
// 获取子分类
const subCategories = await sdk.getSubCategories(671920);
// 获取已发布的文章
const publishedArticles = await sdk.articles.getPublishedArticles();
// 搜索文章
const searchResults = await sdk.articles.searchArticles('CRM');
// 获取文章统计信息
const stats = await sdk.articles.getArticleStats();
console.log(`总文章数: ${stats.total}`);
console.log(`已发布: ${stats.published}`);
console.log(`草稿: ${stats.draft}`);
// 获取推荐文章
const recommended = await sdk.articles.getRecommendedArticles(921546067, 5);
```
### 全局参数设置获取
SDK提供了全局参数设置获取功能,可以从指定的URL获取平台配置参数。
#### 获取所有设置
```typescript
// 获取所有全局设置
const allSettings = await sdk.getSettings();
console.log('所有设置:', allSettings);
// 设置包含各种配置参数,如:
// - product_tag01: 产品标签配置
// - article_tag01: 文章标签配置
// - platform_config: 平台配置
// - payment_settings: 支付设置
// - shipping_settings: 运费设置
```
#### 获取单个设置
```typescript
// 获取特定的设置项
const productTagSetting = await sdk.getSetting('product_tag01');
console.log('产品标签设置:', productTagSetting);
const articleTagSetting = await sdk.getSetting('article_tag01');
console.log('文章标签设置:', articleTagSetting);
const platformConfig = await sdk.getSetting('platform_config');
console.log('平台配置:', platformConfig);
```
#### 在Astro项目中使用
```typescript
// Layout.astro
---
import { GT6SDK } from '@gt6/sdk';
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
rootCategoryId: '969287034',
tagAlias: '002',
productRootCategoryId: '277233',
productTagAlias: '01'
});
// 获取全局设置
const settings = await sdk.getSettings();
const productTagSetting = await sdk.getSetting('product_tag01');
---
<html>
<head>
<title>GT6TRADE</title>
<!-- 使用设置中的配置 -->
<meta name="product-tag" content={productTagSetting?.value || '01'}>
</head>
<body>
<slot />
</body>
</html>
```
#### 错误处理
```typescript
try {
const settings = await sdk.getSettings();
console.log('设置获取成功:', settings);
} catch (error) {
console.error('获取设置失败:', error);
// 使用默认配置
const defaultSettings = {
product_tag01: { value: '01' },
article_tag01: { value: '002' }
};
}
```
#### 缓存机制
全局设置也支持缓存机制,默认缓存5分钟:
```typescript
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
cache: {
enabled: true,
ttl: 300000 // 5分钟
}
});
// 设置会被缓存,提高性能
const settings = await sdk.getSettings(); // 第一次请求
const settings2 = await sdk.getSettings(); // 从缓存获取
// 清除缓存
sdk.clearCache();
```
### 在Astro项目中使用
```typescript
// [id].astro
---
import { GT6SDK } from '@gt6/sdk';
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
rootCategoryId: '969287034',
tagAlias: '002',
productRootCategoryId: '277233',
productTagAlias: '01',
cache: {
enabled: true,
ttl: 300000
}
});
const { id } = Astro.params;
const article = await sdk.getArticle(id);
const recommended = await sdk.articles.getRecommendedArticles(Number(id), 3);
---
<html>
<head>
<title>{article.title}</title>
</head>
<body>
<h1>{article.title}</h1>
<div set:html={article.content}></div>
<h2>推荐文章</h2>
<ul>
{recommended.map(rec => (
<li><a href={`/articles/${rec.articleId}`}>{rec.title}</a></li>
))}
</ul>
</body>
</html>
```
## API 参考
### GT6SDK 类
#### 构造函数
```typescript
new GT6SDK(config: GT6Config)
```
**配置参数:**
- `baseUrl` (string): API基础URL
- `platformId` (string | number): 平台ID
- `rootCategoryId` (string | number, 可选): 根分类ID,默认为'671920'
- `tagAlias` (string, 可选): 标签别名,默认为'001'
- `timeout` (number, 可选): 请求超时时间,默认为10000ms
- `cache` (object, 可选): 缓存配置
- `enabled` (boolean): 是否启用缓存,默认为true
- `ttl` (number): 缓存时间,默认为300000ms (5分钟)
#### 便捷方法
- `getArticle(articleId: number | string): Promise<Article>`
- `getCategories(rootCategoryId?: number | string): Promise<Category[]>`
- `getTags(tagAlias?: string): Promise<Tag[]>`
- `getArticlesByCategory(categoryId: number | number[], options?: ArticlesByCategoryOptions): Promise<{ articles: Article[]; total: number; page: number; limit: number }>`
- `getArticlesByTag(tagId: number | number[], options?: ArticlesByTagOptions): Promise<{ articles: Article[]; total: number; page: number; limit: number }>`
- `getCategoryPath(categoryId: number): Promise<{ path: Category[]; currentCategory: Category | null; breadcrumbs: Array<{ categoryId: number; categoryName: string; level: number }> }>`
- `getSubCategories(categoryId: number, options?: { recursive?: boolean; includeCurrent?: boolean; maxDepth?: number }): Promise<{ subCategories: Category[]; currentCategory: Category | null; total: number; depth: number }>`
- `getSettings(): Promise<SettingsResponse>` - 获取所有全局设置
- `getSetting(key: string): Promise<SingleSetting | null>` - 获取单个设置项
#### 缓存管理
- `clearCache(): void` - 清除所有缓存
- `getCacheStats()` - 获取缓存统计信息
### ArticlesAPI 类
#### 文章相关方法
- `getArticle(articleId: number | string): Promise<Article>`
- `getArticles(params?: ArticleQueryParams): Promise<Article[]>`
- `getArticleList(params?: ArticleQueryParams): Promise<ArticleListItem[]>`
- `getArticlesByCategory(categoryId: number | number[], options?: ArticlesByCategoryOptions): Promise<{ articles: Article[]; total: number; page: number; limit: number }>`
- `getArticlesByTag(tagId: number | number[], options?: ArticlesByTagOptions): Promise<{ articles: Article[]; total: number; page: number; limit: number }>`
- `getCategoryPath(categoryId: number): Promise<{ path: Category[]; currentCategory: Category | null; breadcrumbs: Array<{ categoryId: number; categoryName: string; level: number }> }>`
- `getSubCategories(categoryId: number, options?: { recursive?: boolean; includeCurrent?: boolean; maxDepth?: number }): Promise<{ subCategories: Category[]; currentCategory: Category | null; total: number; depth: number }>`
- `getPublishedArticles(params?: Omit<ArticleQueryParams, 'status'>): Promise<Article[]>`
- `searchArticles(query: string, params?: ArticleQueryParams): Promise<Article[]>`
- `getRecommendedArticles(articleId: number, limit?: number): Promise<Article[]>`
#### 分类和标签方法
- `getCategories(rootCategoryId?: number | string): Promise<Category[]>`
- `getTags(tagAlias?: string): Promise<Tag[]>`
#### 统计方法
- `getArticleStats(): Promise<ArticleStats>`
### TransactionsAPI 类
#### 交易相关方法
- `uploadFile(file: File): Promise<UploadResponse>` - 上传文件
- `deductFunds(deductData: DeductFundsRequest): Promise<DeductFundsResponse>` - 资金扣款
- `createRetailOrder(orderData: CreateRetailOrderRequest): Promise<CreateRetailOrderResponse>` - 创建零售订单
#### 资金扣款
```typescript
// 资金扣款
const deductResult = await sdk.transactions.deductFunds({
userId: 12345,
userType: 2,
amount: '100.00',
description: '购买商品扣款',
orderId: 'ORDER123456'
});
if (deductResult.success) {
console.log('扣款成功');
console.log('资金日志ID:', deductResult.fundLogId);
console.log('新余额:', deductResult.newBalance);
} else {
console.log('扣款失败:', deductResult.message);
}
```
#### 创建零售订单
```typescript
// 创建零售订单
const orderData = {
user_id: 12345,
user_type: 2,
total_amount: 150.00,
pay_way: 1, // 钱包支付
product_type: 1,
platform_id: 1747558688,
d1: 0,
d2: 0,
d3: 0,
products: [
{
product_id: 1001,
quantity: 2,
sku: 'PROD001',
price: 50.00,
region_id: 1,
address_id: 101,
shipping_fee: 10.00,
tax_fee: 5.00
}
]
};
const orderResult = await sdk.transactions.createRetailOrder(orderData);
if (orderResult.success) {
console.log('订单创建成功');
console.log('订单ID:', orderResult.orderId);
console.log('订单状态:', orderResult.order?.status);
} else {
console.log('订单创建失败:', orderResult.message);
}
```
#### 完整交易流程
```typescript
// 完整的购买流程示例
async function completePurchase(userId: number, amount: number, products: any[]) {
// 第一步:扣款
const deductResult = await sdk.transactions.deductFunds({
userId,
userType: 2,
amount: amount.toString(),
description: '购买商品扣款'
});
if (!deductResult.success) {
throw new Error(`扣款失败: ${deductResult.message}`);
}
// 第二步:创建订单
const orderData = {
user_id: userId,
user_type: 2,
total_amount: amount,
pay_way: 1,
product_type: 1,
platform_id: 1747558688,
d1: 0,
d2: 0,
d3: 0,
products
};
const orderResult = await sdk.transactions.createRetailOrder(orderData);
if (!orderResult.success) {
// 注意:如果订单创建失败,需要考虑退款处理
throw new Error(`订单创建失败: ${orderResult.message}`);
}
return {
fundLogId: deductResult.fundLogId,
orderId: orderResult.orderId,
newBalance: deductResult.newBalance
};
}
```
## 使用示例
### 根据分类获取文章
```typescript
// 获取单个分类的文章
const result = await sdk.getArticlesByCategory(782714);
console.log(`分类文章总数: ${result.total}`);
console.log(`返回文章数: ${result.articles.length}`);
// 获取多个分类的文章(去重)
const multiResult = await sdk.getArticlesByCategory([782714, 821172]);
console.log(`多分类文章总数: ${multiResult.total}`);
// 使用分页和状态过滤
const paginatedResult = await sdk.getArticlesByCategory(782714, {
page: 1,
limit: 10,
status: 'published'
});
```
### 根据标签获取文章
```typescript
// 获取单个标签的文章
const result = await sdk.getArticlesByTag(236656846);
console.log(`标签文章总数: ${result.total}`);
// 获取多个标签的文章(去重)
const multiResult = await sdk.getArticlesByTag([236656846, 497329737]);
console.log(`多标签文章总数: ${multiResult.total}`);
// 使用分页和状态过滤
const paginatedResult = await sdk.getArticlesByTag(236656846, {
page: 1,
limit: 10,
status: 'published'
});
// 指定标签别名获取文章
const customTagResult = await sdk.getArticlesByTag(236656846, {
tagAlias: '002', // 使用自定义标签别名
limit: 10,
status: 'published'
});
```
### 获取分类层级路径(面包屑导航)
```typescript
// 获取分类的完整层级路径
const pathResult = await sdk.getCategoryPath(821172);
// 输出面包屑导航数据
console.log('当前分类:', pathResult.currentCategory?.categoryName);
console.log('完整路径:', pathResult.path.map(cat => cat.categoryName).join(' > '));
// 前端面包屑导航使用
pathResult.breadcrumbs.forEach((crumb, index) => {
if (index < pathResult.breadcrumbs.length - 1) {
console.log(`<a href="/category/${crumb.categoryId}">${crumb.categoryName}</a> >`);
} else {
console.log(`<span>${crumb.categoryName}</span>`);
}
});
```
### 获取子分类
```typescript
// 获取直接子分类
const result = await sdk.getSubCategories(671920);
console.log(`子分类数量: ${result.total}`);
console.log(`递归深度: ${result.depth}`);
// 递归获取所有层级的子分类
const recursiveResult = await sdk.getSubCategories(671920, {
recursive: true
});
console.log(`所有子分类数量: ${recursiveResult.total}`);
// 包含当前分类
const includeCurrentResult = await sdk.getSubCategories(671920, {
includeCurrent: true
});
console.log(`包含当前分类的总数量: ${includeCurrentResult.total}`);
// 限制递归深度
const limitedResult = await sdk.getSubCategories(671920, {
recursive: true,
maxDepth: 2
});
console.log(`限制深度后的子分类数量: ${limitedResult.total}`);
```
## 在Astro中使用
### 面包屑导航组件
```astro
---
// Breadcrumb.astro
export interface Props {
categoryId: number;
currentPage?: number;
}
const { categoryId, currentPage = 1 } = Astro.props;
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
rootCategoryId: '969287034',
tagAlias: '002',
productRootCategoryId: '277233',
productTagAlias: '01',
cache: {
enabled: true,
ttl: 300000
}
});
const categoryPath = await sdk.getCategoryPath(categoryId);
---
<nav aria-label="面包屑导航" class="mb-3">
<ol class="breadcrumb justify-content-center">
<li class="breadcrumb-item">
<a href="/" class="text-decoration-none">
<i class="bi bi-house"></i> 首页
</a>
</li>
{categoryPath.breadcrumbs.map((crumb, index) => (
<li class={`breadcrumb-item ${index === categoryPath.breadcrumbs.length - 1 ? 'active' : ''}`}>
{index === categoryPath.breadcrumbs.length - 1 ? (
<span>{crumb.categoryName}</span>
) : (
<a href={`/postlist/${crumb.categoryId}-1`} class="text-decoration-none">
{crumb.categoryName}
</a>
)}
</li>
))}
{currentPage > 1 && (
<li class="breadcrumb-item active">
<span>第 {currentPage} 页</span>
</li>
)}
</ol>
</nav>
<style>
.breadcrumb {
background: transparent;
padding: 0.5rem 0;
}
.breadcrumb-item + .breadcrumb-item::before {
content: ">";
color: #6c757d;
}
.breadcrumb-item.active span {
color: #495057;
font-weight: 500;
}
</style>
```
### 标签面包屑导航组件
```astro
---
// TagBreadcrumb.astro
export interface Props {
tagId: number;
currentPage?: number;
baseUrl?: string;
platformId?: string | number;
rootCategoryId?: string | number;
}
const {
tagId,
currentPage = 1,
baseUrl = 'https://data.shopasb.io',
platformId = '1747558688',
rootCategoryId = '969287034',
productRootCategoryId = '277233',
productTagAlias = '01'
} = Astro.props;
const sdk = new GT6SDK({
baseUrl,
platformId,
rootCategoryId,
productRootCategoryId,
productTagAlias,
cache: {
enabled: true,
ttl: 300000
}
});
const tags = await sdk.getTags();
const currentTag = tags.find(tag => tag.tagId === tagId);
---
<nav aria-label="面包屑导航" class="mb-3">
<ol class="breadcrumb justify-content-center">
<li class="breadcrumb-item">
<a href="/" class="text-decoration-none">
<i class="bi bi-house"></i> 首页
</a>
</li>
<li class="breadcrumb-item">
<a href="/tags" class="text-decoration-none">标签</a>
</li>
<li class="breadcrumb-item active">
<span>{currentTag?.tagName || `标签 ${tagId}`}</span>
</li>
{currentPage > 1 && (
<li class="breadcrumb-item active">
<span>第 {currentPage} 页</span>
</li>
)}
</ol>
</nav>
<style>
.breadcrumb {
background: transparent;
padding: 0.5rem 0;
margin-bottom: 0;
}
.breadcrumb-item + .breadcrumb-item::before {
content: ">";
color: #6c757d;
margin: 0 0.5rem;
}
.breadcrumb-item.active span {
color: #495057;
font-weight: 500;
}
.breadcrumb-item a {
color: #6c757d;
text-decoration: none;
}
.breadcrumb-item a:hover {
color: #495057;
text-decoration: underline;
}
.breadcrumb-item i {
margin-right: 0.25rem;
}
</style>
```
### 分类列表页面
```astro
---
// [categoryId]-[pageId].astro
import { GT6SDK } from '@gt6/sdk';
import Breadcrumb from '../components/Breadcrumb.astro';
const { categoryId, pageId } = Astro.params;
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
rootCategoryId: '969287034',
tagAlias: '002',
productRootCategoryId: '277233',
productTagAlias: '01',
cache: {
enabled: true,
ttl: 300000
}
});
const currentPage = parseInt(pageId);
const categoryArticles = await sdk.getArticlesByCategory(parseInt(categoryId), {
page: currentPage,
limit: 9,
status: 'published'
});
const categoryPath = await sdk.getCategoryPath(parseInt(categoryId));
const currentCategory = categoryPath.currentCategory;
---
<html>
<head>
<title>{currentCategory?.categoryName} - GT6TRADE</title>
</head>
<body>
<Breadcrumb
categoryId={parseInt(categoryId)}
currentPage={currentPage}
/>
<section>
<h1>{currentCategory?.categoryName}</h1>
<p>共 {categoryArticles.total} 篇文章</p>
<div class="articles">
{categoryArticles.articles.map(article => (
<article>
<h2><a href={`/post/${article.articleId}`}>{article.title}</a></h2>
<p>{article.content.substring(0, 200)}...</p>
</article>
))}
</div>
</section>
</body>
</html>
```
### 标签列表页面
```astro
---
// [tagId]-[pageId].astro
import { GT6SDK } from '@gt6/sdk';
import TagBreadcrumb from '../components/TagBreadcrumb.astro';
const { tagId, pageId } = Astro.params;
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
rootCategoryId: '969287034',
tagAlias: '002',
productRootCategoryId: '277233',
productTagAlias: '01',
cache: {
enabled: true,
ttl: 300000
}
});
const currentPage = parseInt(pageId);
const tagArticles = await sdk.getArticlesByTag(parseInt(tagId), {
page: currentPage,
limit: 9,
status: 'published',
tagAlias: '002'
});
const tags = await sdk.getTags('002');
const currentTag = tags.find(tag => tag.tagId === parseInt(tagId));
---
<html>
<head>
<title>{currentTag?.tagName} - GT6TRADE</title>
</head>
<body>
<TagBreadcrumb
tagId={parseInt(tagId)}
currentPage={currentPage}
/>
<section>
<h1>{currentTag?.tagName}</h1>
<p>共 {tagArticles.total} 篇文章</p>
<div class="articles">
{tagArticles.articles.map(article => (
<article>
<h2><a href={`/post/${article.articleId}`}>{article.title}</a></h2>
<p>{article.content.substring(0, 200)}...</p>
</article>
))}
</div>
</section>
</body>
</html>
```
## 数据类型
### Article (文章)
```typescript
interface Article {
articleId: number;
title: string;
content: string;
status: 'published' | 'draft' | 'archived';
publishedAt: string;
templateId: number;
aiId: number;
platformId: number;
isVisible: boolean;
displayTemplate: string;
createdAt: any;
updatedAt: any;
categories: Category[];
tags: Tag[];
metaData: ArticleMetaData[];
images: ArticleImage[];
generatedAt: string;
}
```
### Category (分类)
```typescript
interface Category {
categoryId: number;
categoryName: string;
categoryDescription: string;
metaKeywords: string;
status: number;
parentId: number;
sortOrder: number;
createdAt: any;
updatedAt: any;
platformId: number;
articleIds: number[];
children: Category[];
}
```
### Tag (标签)
```typescript
interface Tag {
tagId: number;
tagName: string;
type: number;
platformId: number;
aliases: string;
createdAt: any;
articleIds: number[];
}
```
### 选项类型
```typescript
interface ArticlesByCategoryOptions {
page?: number;
limit?: number;
status?: 'published' | 'draft' | 'archived';
}
interface ArticlesByTagOptions {
page?: number;
limit?: number;
status?: 'published' | 'draft' | 'archived';
tagAlias?: string;
}
interface ProductsByCategoryOptions {
page?: number;
limit?: number;
status?: number;
}
interface ProductsByTagOptions {
page?: number;
limit?: number;
status?: number;
productTagAlias?: string;
}
```
### 产品选项类型
```typescript
interface ProductsByCategoryOptions {
page?: number;
limit?: number;
status?: number;
}
interface ProductsByTagOptions {
page?: number;
limit?: number;
status?: number;
productTagAlias?: string;
}
```
### 全局设置类型
```typescript
// 单个设置项的结构
interface SingleSetting {
key: string;
value: string;
description?: string;
updatedAt: string;
}
// 所有设置的响应结构
interface SettingsResponse {
[key: string]: SingleSetting;
}
```
## 错误处理
SDK使用自定义的 `GT6Error` 类来处理错误:
```typescript
import { GT6Error } from '@gt6/sdk';
try {
const article = await sdk.getArticle(999999);
} catch (error) {
if (error instanceof GT6Error) {
console.error(`错误: ${error.message}`);
console.error(`状态码: ${error.status}`);
}
}
```
## 缓存机制
SDK内置缓存机制,默认缓存5分钟:
```typescript
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688',
cache: {
enabled: true,
ttl: 300000 // 5分钟
}
});
// 清除缓存
sdk.clearCache();
// 获取缓存统计
const stats = sdk.getCacheStats();
console.log(`缓存条目数: ${stats.size}`);
```
## 开发
### 安装依赖
```bash
npm install
```
### 构建
```bash
npm run build
```
### 测试
```bash
npm test
```
### 类型检查
```bash
npm run type-check
```
## 许可证
MIT
## 产品管理
### 获取产品详情
```typescript
const product = await sdk.getProduct(424210);
console.log(product.productName); // "极简不对称设计纯色短袖T恤"
console.log(product.price); // "30.00"
// 检查产品类型
if (product.productType === 2) {
// 订阅产品
console.log(product.subscription?.billingCycleUnit); // "month"
console.log(product.subscription?.trialDays); // 5
} else if (product.productType === 3) {
// 批发产品
console.log(product.wholesale?.minOrderQuantity); // 最小订购量
console.log(product.priceTiers?.length); // 价格层级数量
} else if (product.productType === 4) {
// 众筹产品
console.log(product.crowdfunding?.targetAmount); // 目标金额
console.log(product.crowdfunding?.currentAmount); // 当前金额
console.log(product.rewards?.length); // 奖励数量
} else if (product.productType === 5) {
// 简单理财产品
console.log(product.simpleFinance?.interestRate); // 年化收益率
console.log(product.simpleFinance?.minInvestment); // 最小投资金额
console.log(product.simpleFinance?.investmentPeriod); // 投资期限
} else {
// 普通产品
console.log(product.variants.length); // 变体数量
}
// 税费和运费模板规则自动填充
// SDK会自动为产品的税费模板和运费模板添加适用的规则
if (product.taxTemplates && product.taxTemplates.length > 0) {
product.taxTemplates.forEach(template => {
console.log(`税费模板: ${template.templateName}`);
console.log(`默认税率: ${template.defaultTaxRate}%`);
if (template.rules && template.rules.length > 0) {
console.log(`适用规则数量: ${template.rules.length}`);
template.rules.forEach(rule => {
console.log(` 区域 ${rule.regionId}: ${rule.taxRate}%`);
});
}
});
}
if (product.shippingTemplates && product.shippingTemplates.length > 0) {
product.shippingTemplates.forEach(template => {
console.log(`运费模板: ${template.templateName}`);
console.log(`默认运费: ${template.defaultFee}`);
if (template.rules && template.rules.length > 0) {
console.log(`适用规则数量: ${template.rules.length}`);
template.rules.forEach(rule => {
console.log(` 区域 ${rule.regionId}: 首${rule.firstUnit}件${rule.firstFee}元,续${rule.additionalUnit}件${rule.additionalFee}元`);
});
}
});
}
```
### 获取产品分类列表
```typescript
const categories = await sdk.getProductCategories();
console.log(categories.length); // 分类数量
// 或者指定产品根分类ID
const categories = await sdk.getProductCategories('277233');
```
### 获取产品标签列表
```typescript
const tags = await sdk.getProductTags();
console.log(tags.length); // 标签数量
// 或者指定产品标签别名
const tags = await sdk.getProductTags('01');
```
### 根据分类获取产品列表
```typescript
const result = await sdk.getProductsByCategory(367704, {
page: 1,
limit: 10,
status: 1
});
console.log(result.products.length); // 产品数量
console.log(result.total); // 总产品数
```
### 根据标签获取产品列表
```typescript
const result = await sdk.getProductsByTag(567515, {
page: 1,
limit: 10,
status: 1,
productTagAlias: '01'
});
console.log(result.products.length); // 产品数量
console.log(result.total); // 总产品数
```
### 获取产品分类路径(面包屑导航)
```typescript
const categoryPath = await sdk.getProductCategoryPath(categoryId);
console.log(categoryPath.breadcrumbs);
// [
// { categoryId: 277233, categoryName: "中文商品", level: 0 },
// { categoryId: 367704, categoryName: "女装", level: 1 },
// { categoryId: 907691, categoryName: "T恤", level: 2 }
// ]
```
### 获取产品子分类
```typescript
const subCategories = await sdk.getProductSubCategories(367704, {
recursive: true,
includeCurrent: false,
maxDepth: 2
});
console.log(subCategories.subCategories.length); // 子分类数量
```
### 获取税费信息
```typescript
const taxInfo = await sdk.getTaxInfo();
console.log('税费模板数量:', taxInfo.templates.length);
taxInfo.templates.forEach(template => {
console.log(`模板 ${template.templateId}: ${template.templateName}`);
console.log(` 默认税率: ${template.defaultTaxRate}%`);
console.log(` 规则数量: ${template.rules.length}`);
template.rules.forEach(rule => {
console.log(` 区域 ${rule.regionId}: ${rule.taxRate}%`);
});
});
```
### 获取运费信息
```typescript
const shippingInfo = await sdk.getShippingInfo();
console.log('运费模板数量:', shippingInfo.templates.length);
shippingInfo.templates.forEach(template => {
console.log(`模板 ${template.templateId}: ${template.templateName}`);
console.log(` 默认运费: ${template.defaultFee}`);
console.log(` 免运费门槛: ${template.freeShippingLimit}`);
console.log(` 规则数量: ${template.rules.length}`);
template.rules.forEach(rule => {
console.log(` 区域 ${rule.regionId}: 首${rule.firstUnit}件${rule.firstFee}元,续${rule.additionalUnit}件${rule.additionalFee}元`);
});
});
```
### 获取区域信息
```typescript
const regionInfo = await sdk.getRegions();
console.log('区域数量:', regionInfo.regions.length);
// 递归显示区域层级结构
const displayRegions = (regions: any[], level: number = 0) => {
regions.forEach(region => {
const indent = ' '.repeat(level);
console.log(`${indent}${region.regionName} (${region.regionCode}) - ${region.regionLevel}`);
if (region.children && region.children.length > 0) {
displayRegions(region.children, level + 1);
}
});
};
displayRegions(regionInfo.regions);
```
### 税费和运费模板规则自动填充
SDK在获取产品详情时会自动为税费模板和运费模板填充适用的规则:
**触发条件:**
- 产品有销售区域(`regions` 不为空)
- 产品有税费模板(`taxTemplates` 不为空)或运费模板(`shippingTemplates` 不为空)
**自动填充逻辑:**
1. 获取平台的所有税费/运费模板和规则
2. 根据产品的销售区域过滤出适用的规则
3. 将适用规则添加到对应的模板中
4. 如果获取模板信息失败,不影响产品详情返回
**示例:**
```typescript
const product = await sdk.getProduct(424210);
// 税费模板会自动包含适用区域的规则
if (product.taxTemplates) {
product.taxTemplates.forEach(template => {
console.log(`模板: ${template.templateName}`);
console.log(`默认税率: ${template.defaultTaxRate}%`);
// 自动填充的规则
if (template.rules) {
template.rules.forEach(rule => {
console.log(`区域 ${rule.regionId}: ${rule.taxRate}%`);
});
}
});
}
// 运费模板会自动包含适用区域的规则
if (product.shippingTemplates) {
product.shippingTemplates.forEach(template => {
console.log(`模板: ${template.templateName}`);
console.log(`默认运费: ${template.defaultFee}`);
// 自动填充的规则
if (template.rules) {
template.rules.forEach(rule => {
console.log(`区域 ${rule.regionId}: 首${rule.firstUnit}件${rule.firstFee}元`);
});
}
});
}
```
**注意事项:**
- 如果产品没有销售区域或模板,不会进行自动填充
- 如果获取模板信息失败,产品详情仍会正常返回,只是模板中没有规则
- 自动填充的规则只包含产品可销售区域的规则,确保数据的准确性
### 产品类型说明
- **productType: 1** - 普通产品(包含 variants、options 等)
- **productType: 2** - 订阅产品(包含 subscription 信息)
- **productType: 3** - 批发产品(包含 wholesale、priceTiers、variantPrices 信息)
- **productType: 4** - 众筹产品(包含 crowdfunding、rewards、updates、faqs 信息)
- **productType: 5** - 简单理财产品(包含 simpleFinance 信息)
### 订阅产品示例
```typescript
const subscriptionProduct = await sdk.getProduct(305191);
if (subscriptionProduct.subscription) {
console.log('订阅周期:', subscriptionProduct.subscription.billingCycleUnit);
console.log('试用天数:', subscriptionProduct.subscription.trialDays);
console.log('设置费用:', subscriptionProduct.subscription.setupFee);
console.log('续费折扣:', subscriptionProduct.subscription.renewalDiscount);
console.log('自动续费:', subscriptionProduct.subscription.autoRenew);
}
```
### 批发产品示例
```typescript
const wholesaleProduct = await sdk.getProduct(369374);
if (wholesaleProduct.wholesale) {
console.log('最小订购量:', wholesaleProduct.wholesale.minOrderQuantity);
console.log('最大订购量:', wholesaleProduct.wholesale.maxOrderQuantity);
console.log('允许混合变体:', wholesaleProduct.wholesale.allowMixedVariants);
console.log('显示零售价:', wholesaleProduct.wholesale.showRetailPrice);
console.log('批发描述:', wholesaleProduct.wholesale.wholesaleDescription);
console.log('付款条件:', wholesaleProduct.wholesale.paymentTerms);
console.log('运输条件:', wholesaleProduct.wholesale.shippingTerms);
// 价格层级
console.log('价格层级数量:', wholesaleProduct.priceTiers?.length);
wholesaleProduct.priceTiers?.forEach(tier => {
console.log(`层级 ${tier.tierId}: ${tier.minQuantity}-${tier.maxQuantity}件, 价格调整: ${tier.priceValue}`);
});
// 变体价格
console.log('变体价格数量:', wholesaleProduct.variantPrices?.length);
}
```
### 众筹产品示例
```typescript
const crowdfundingProduct = await sdk.getProduct(803421);
if (crowdfundingProduct.crowdfunding) {
console.log('目标金额:', crowdfundingProduct.crowdfunding.targetAmount);
console.log('当前金额:', crowdfundingProduct.crowdfunding.currentAmount);
console.log('支持者数量:', crowdfundingProduct.crowdfunding.supporterCount);
console.log('最小支持金额:', crowdfundingProduct.crowdfunding.minSupportAmount);
console.log('允许超额众筹:', crowdfundingProduct.crowdfunding.allowOverFunding);
console.log('超额限制:', crowdfundingProduct.crowdfunding.overFundingLimit);
// 众筹进度
const progress = (parseFloat(crowdfundingProduct.crowdfunding.currentAmount) / parseFloat(crowdfundingProduct.crowdfunding.targetAmount)) * 100;
console.log(`众筹进度: ${progress.toFixed(2)}%`);
// 奖励列表
console.log('奖励数量:', crowdfundingProduct.rewards?.length);
crowdfundingProduct.rewards?.forEach(reward => {
console.log(`奖励 ${reward.rewardId}: ${reward.rewardName} - ${reward.rewardAmount}`);
console.log(` 已认领: ${reward.rewardClaimed}/${reward.rewardLimit || '无限制'}`);
});
// 项目更新
console.log('项目更新数量:', crowdfundingProduct.updates?.length);
crowdfundingProduct.updates?.forEach(update => {
console.log(`更新 ${update.updateId}: ${update.updateTitle} (${update.isPublic ? '公开' : '私密'})`);
});
// FAQ
console.log('FAQ数量:', crowdfundingProduct.faqs?.length);
crowdfundingProduct.faqs?.forEach(faq => {
console.log(`FAQ ${faq.faqId}: ${faq.question}`);
});
}
```
### 简单理财产品示例
```typescript
const financeProduct = await sdk.getProduct(249478);
if (financeProduct.simpleFinance) {
console.log('年化收益率:', financeProduct.simpleFinance.interestRate + '%');
console.log('最小投资金额:', financeProduct.simpleFinance.minInvestment + ' ' + financeProduct.simpleFinance.minInvestmentUnit);
console.log('最大投资金额:', financeProduct.simpleFinance.maxInvestment + ' ' + financeProduct.simpleFinance.maxInvestmentUnit);
console.log('投资期限:', financeProduct.simpleFinance.investmentPeriod + ' ' + financeProduct.simpleFinance.investmentPeriodUnit);
console.log('计息周期:', financeProduct.simpleFinance.calculationPeriod + ' ' + financeProduct.simpleFinance.calculationPeriodUnit);
// 计算投资收益示例
const investmentAmount = 5000; // 投资金额
const interestRate = parseFloat(financeProduct.simpleFinance.interestRate);
const investmentPeriod = financeProduct.simpleFinance.investmentPeriod;
// 简单年化收益计算
const annualReturn = (investmentAmount * interestRate / 100);
const totalReturn = annualReturn * investmentPeriod;
console.log(`投资 ${investmentAmount} ${financeProduct.simpleFinance.minInvestmentUnit} 的预期收益:`);
console.log(` 年化收益: ${annualReturn.toFixed(2)} ${financeProduct.simpleFinance.minInvestmentUnit}`);
console.log(` 总收益: ${totalReturn.toFixed(2)} ${financeProduct.simpleFinance.minInvestmentUnit}`);
console.log(` 到期金额: ${(investmentAmount + totalReturn).toFixed(2)} ${financeProduct.simpleFinance.minInvestmentUnit}`);
}
```
## 支付方式模块 (Payment Methods)
SDK提供了支付方式管理功能,支持获取各种类型的支付方式。
### 基础使用
```typescript
// 获取所有支付方式(使用默认别名'01')
const paymentMethods = await sdk.getPaymentMethods();
console.log('支付方式总数:', paymentMethods.methods.length);
// 获取指定别名的支付方式
const paymentMethods02 = await sdk.getPaymentMethods('02');
console.log('别名02的支付方式总数:', paymentMethods02.methods.length);
// 根据类型获取支付方式(使用默认别名)
const apiMethods = await sdk.getPaymentMethodsByType('Api');
const manualMethods = await sdk.getPaymentMethodsByType('Manual');
// 根据类型获取支付方式(使用指定别名)
const apiMethods02 = await sdk.getPaymentMethodsByType('Api', '02');
const manualMethods02 = await sdk.getPaymentMethodsByType('Manual', '02');
```
### 获取特定支付方式
```typescript
// 根据ID获取支付方式详情(使用默认别名)
const method = await sdk.getPaymentMethodById(3);
if (method) {
console.log('支付方式:', method.name);
console.log('类型:', method.type);
// 显示属性
method.attrs.forEach(attr => {
console.log(` ${attr.attrName}: ${attr.attrValue}`);
});
}
// 根据ID获取支付方式详情(使用指定别名)
const method02 = await sdk.getPaymentMethodById(3, '02');
// 获取特定属性值(使用默认别名)
const walletAddress = await sdk.getPaymentMethodAttribute(3, '钱包地址');
// 获取特定属性值(使用指定别名)
const walletAddress02 = await sdk.getPaymentMethodAttribute(3, '钱包地址', '02');
```
### 支付方式类型
- **Api** - API支付方式(如加密货币)
- **Manual** - 手动支付方式(如银行转账)
- **Gateway** - 网关支付方式
- **Crypto** - 加密货币支付方式
### 支付方式别名
支付方式别名用于区分不同的支付配置集合:
- **默认别名**: '01'(如果不指定)
- **其他别名**: '02', '03' 等,用于不同的支付场景或配置
## 表单提交模块 (Forms)
表单提交模块提供了通用的表单提交功能,支持多种类型的表单提交。
### API 方法
#### `submitForm(aliases, email, fieldValue, options?)`
通用表单提交方法
**参数:**
- `aliases` (string): 表单别名(如 'CONTACT', 'FEEDBACK' 等)
- `email` (string): 用户邮箱
- `fieldValue` (Record<string, any>): 表单字段值
- `options` (FormSubmitOptions, 可选): 提交选项
**返回:** `Promise<FormSubmitResponse>`
#### `submitContactForm(formData)`
联系表单提交
**参数:**
- `formData` (object): 联系表单数据
- `firstName` (string): 名字
- `lastName` (string, 可选): 姓氏
- `email` (string): 邮箱
- `phone` (string, 可选): 电话
- `subject` (string): 主题
- `message` (string): 消息内容
#### `submitFeedbackForm(formData)`
反馈表单提交
**参数:**
- `formData` (object): 反馈表单数据
- `name` (string): 姓名
- `email` (string): 邮箱
- `type` (string): 反馈类型
- `message` (string): 消息内容
- `rating` (number, 可选): 评分
#### `submitCustomForm(aliases, formData, emailField?)`
自定义表单提交
**参数:**
- `aliases` (string): 表单别名
- `formData` (Record<string, any>): 表单数据对象
- `emailField` (string, 可选): 邮箱字段名,默认为 'email'
### 使用示例
```javascript
// 联系表单提交
const contactResult = await sdk.submitContactForm({
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@example.com',
phone: '+1234567890',
subject: 'General Inquiry',
message: 'This is a test message.'
});
// 反馈表单提交
const feedbackResult = await sdk.submitFeedbackForm({
name: 'Jane Smith',
email: 'jane.smith@example.com',
type: 'Bug Report',
message: 'Found a bug in the checkout process.',
rating: 4
});
// 通用表单提交
const generalResult = await sdk.submitForm('CUSTOM_FORM', 'user@example.com', {
name: 'Test User',
company: 'Test Company',
inquiry: 'General inquiry about services'
});
// 自定义表单提交
const customResult = await sdk.submitCustomForm('NEWSLETTER_SIGNUP', {
username: 'newuser',
email: 'newuser@example.com',
password: 'securepassword123',
agreeTerms: true
});
```
### 错误处理
表单提交方法返回统一的响应格式:
```typescript
interface FormSubmitResponse {
success: boolean;
message: string;
data?: any;
code?: number;
}
```
### 类型定义
```typescript
interface FormSubmitData {
platformId: number | string;
aliases: string;
email: string;
fieldValue: Record<string, any>;
createSecret?: string;
}
interface FormSubmitOptions {
endpoint?: string;
createSecret?: string;
}
```
## 支付方式模块 (Payment Methods)
## 用户认证模块 (Users)
用户认证模块提供了完整的用户登录、注册和会话管理功能。
### API 方法
#### `login(username, password, platformId)`
用户登录
**参数:**
- `username` (string): 用户名
- `password` (string): 密码
- `platformId` (number): 平台ID
**返回:** `Promise<LoginResponse>`
#### `register(username, password, platformId, ibcode?)`
用户注册
**参数:**
- `username` (string): 用户名
- `password` (string): 密码
- `platformId` (number): 平台ID
- `ibcode` (string, 可选): 邀请码
**返回:** `Promise<RegisterResponse>`
#### `isLoggedIn()`
检查用户是否已登录
**返回:** `boolean`
#### `getCurrentUser()`
获取当前登录用户信息
**返回:** `UserInfo | null`
#### `getToken()`
获取当前登录用户的token
**返回:** `string | null`
#### `logout()`
用户登出
#### `saveUserData(userData)`
保存用户数据到本地存储
**参数:**
- `userData` (UserData): 用户数据对象
#### `getUserData()`
从本地存储获取用户数据
**返回:** `UserData | null`
#### `rememberLogin(username, password)`
记住用户登录信息
**参数:**
- `username` (string): 用户名
- `password` (string): 密码
#### `getRememberedLogin()`
获取记住的登录信息
**返回:** `{ username: string; password: string } | null`
#### `clearRememberedLogin()`
清除记住的登录信息
### 使用示例
```javascript
// 用户登录
const loginResult = await sdk.login('username', 'password', 1);
if (loginResult.success && loginResult.token && loginResult.user) {
// 保存用户数据到本地存储
const userData = {
...loginResult.user,
token: loginResult.token
};
sdk.saveUserData(userData);
console.log('登录成功:', loginResult.user);
} else {
console.error('登录失败:', loginResult.message);
}
// 用户注册
const registerResult = await sdk.register('newuser', 'password123', 1, 'INVITE123');
if (registerResult.success) {
console.log('注册成功,用户ID:', registerResult.userId);
} else {
console.error('注册失败:', registerResult.message);
}
// 检查登录状态
if (sdk.isLoggedIn()) {
const user = sdk.getCurrentUser();
const token = sdk.getToken();
console.log('用户已登录:', user);
console.log('Token:', token);
} else {
console.log('用户未登录');
}
// 记住登录信息
sdk.rememberLogin('username', 'password');
// 获取记住的登录信息
const remembered = sdk.getRememberedLogin();
if (remembered) {
console.log('记住的登录信息:', remembered);
}
// 用户登出
sdk.logout();
```
### 完整的登录流程示例
```javascript
async function completeLoginFlow() {
// 检查是否已登录
if (sdk.isLoggedIn()) {
console.log('用户已登录,无需重新登录');
return true;
}
// 尝试使用记住的登录信息
const remembered = sdk.getRememberedLogin();
if (remembered) {
console.log('使用记住的登录信息');
const result = await sdk.login(remembered.username, remembered.password, 1);
if (result.success) {
console.log('使用记住的信息登录成功');
return true;
}
}
// 手动登录
console.log('需要手动登录');
return false;
}
```
### 表单验证示例
```javascript
// 登录验证
async function loginWithValidation(username, password, platformId) {
// 基本验证
if (!username || !password) {
console.error('用户名和密码不能为空');
return false;
}
if (password.length < 6) {
console.error('密码长度不能少于6位');
return false;
}
// 执行登录
const result = await sdk.login(username, password, platformId);
if (result.success && result.token && result.user) {
// 保存用户数据
const userData = {
...result.user,
token: result.token
};
sdk.saveUserData(userData);
console.log('登录成功');
return true;
} else {
console.error('登录失败:', result.message);
return false;
}
}
// 注册验证
async function registerWithValidation(username, password, confirmPassword, platformId, ibcode) {
// 基本验证
if (!username || !password || !confirmPassword) {
console.error('用户名、密码和确认密码不能为空');
return false;
}
if (password !== confirmPassword) {
console.error('两次输入的密码不一致');
return false;
}
if (password.length < 6) {
console.error('密码长度不能少于6位');
return false;
}
if (username.length < 3) {
console.error('用户名长度不能少于3位');
return false;
}
// 执行注册
const result = await sdk.register(username, password, platformId, ibcode);
if (result.success) {
console.log('注册成功,用户ID:', result.userId);
return true;
} else {
console.error('注册失败:', result.message);
return false;
}
}
```
### 类型定义
```typescript
interface LoginRequest {
username: string;
password: string;
platformId: number;
}
interface LoginResponse {
success: boolean;
message?: string;
token?: string;
user?: {
userId: number;
username: string;
userLevel: number;
status: boolean;
platformId: number;
d1: number;
d2: number;
d3: number;
};
}
interface RegisterRequest {
username: string;
password: string;
platformId: number;
ibcode?: string;
}
interface RegisterResponse {
success: boolean;
message?: string;
userId?: number;
}
interface UserData {
userId: number;
username: string;
userLevel: number;
status: boolean;
platformId: number;
d1: number;
d2: number;
d3: number;
token: string;
}
```
### 在Astro项目中使用
```astro
---
// Layout.astro
import { GT6SDK } from '@gt6/sdk';
const sdk = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: '1747558688'
});
// 检查用户登录状态
const isLoggedIn = sdk.isLoggedIn();
const currentUser = sdk.getCurrentUser();
---
<html>
<head>
<title>GT6TRADE</title>
</head>
<body>
<header>
{isLoggedIn ? (
<div>
<span>欢迎, {currentUser?.username}</span>
<button onclick="logout()">登出</button>
</div>
) : (
<div>
<button onclick="showLoginModal()">登录</button>
<button onclick="showRegisterModal()">注册</button>
</div>
)}
</header>
<slot />
<script>
// 全局SDK实例
window.gt6SDK = new GT6SDK({
baseUrl: 'https://data.shopasb.io',
platformId: 1747558688
});
// 登出函数
function logout() {
window.gt6SDK.logout();
window.location.reload();
}
// 显示登录模态框
function showLoginModal() {
// 实现登录模态框显示逻辑
}
// 显示注册模态框
function showRegisterModal() {
// 实现注册模态框显示逻辑
}
</script>
</body>
</html>
```
### 错误处理
用户认证方法返回统一的响应格式:
```typescript
// 登录成功响应
{
success: true,
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
user: {
userId: 123,
username: "testuser",
userLevel: 1,
status: true,
platformId: 1,
d1: 0,
d2: 0,
d3: 0
}
}
// 登录失败响应
{
success: false,
message: "用户名或密码错误"
}
// 注册成功响应
{
success: true,
userId: 123,
message: "注册成功"
}
// 注册失败响应
{
success: false,
message: "用户名已存在"
}
```
### 用户资金和订单管理
用户模块还提供了资金信息、资金日志、零售订单和地址管理功能。
#### 获取用户资金信息
```javascript
// 获取用户资金信息(完整响应)
const fundsResponse = await sdk.getUserFunds();
if (fundsResponse.success) {
console.log('可用余额:', fundsResponse.fund.fund);
console.log('冻结金额:', fundsResponse.fund.noFund);
console.log('租金:', fundsResponse.fund.rentFund);
console.log('保证金:', fundsResponse.fund.marginFund);
console.log('冻结保证金:', fundsResponse.fund.marginNoFund);
console.log('积分:', fundsResponse.fund.userIntegral);
console.log('信用等级:', fundsResponse.fund.creditLevel);
} else {
console.error('获取资金信息失败:', fundsResponse.message);
}
// 获取用户资金信息(简化版本)
const funds = await sdk.getFunds();
if (funds) {
console.log('可用余额:', funds.fund);
console.log('冻结金额:', funds.noFund);
} else {
console.log('获取资金信息失败');
}
```
#### 获取资金日志列表
```javascript
// 获取资金日志列表(完整响应)
const fundLogsResponse = await sdk.getFundLogs({
page: 1,
pageSize: 10
});
if (fundLogsResponse.success) {
console.log('资金日志总数:', fundLogsResponse.total);
fundLogsResponse.logs.forEach(log => {
console.log(`日志ID: ${log.logId}`);
console.log(`操作类型: ${log.fieldName}`);
console.log(`变动金额: ${log.changeAmount}`);
console.log(`新余额: ${log.newBalance}`);
console.log(`操作时间: ${log.operationTime}`);
console.log(`备注: ${log.remark || '-'}`);
});
} else {
console.error('获取资金日志失败:', fundLogsResponse.message);
}
// 获取资金日志列表(简化版本)
const fundLogs = await sdk.getFundLogsSimple(1, 10);
if (fundLogs) {
console.log('资金日志总数:', fundLogs.total);
fundLogs.logs.forEach(log => {
console.log(`操作类型: ${log.fieldName}, 变动金额: ${log.changeAmount}`);
});
} else {
console.log('获取资金日志失败');
}
```
#### 获取零售订单列表
```javascript
// 获取零售订单列表(完整响应)
const retailOrdersResponse = await sdk.getRetailOrders({
page: 1,
pageSize: 10
});
if (retailOrdersResponse.success) {
console.log('订单总数:', retailOrdersResponse.data.total);
retailOrdersResponse.data.orders.forEach(order => {
console.log(`订单ID: ${order.order_id}`);
console.log(`订单金额: $${order.total_amount}`);
console.log(`支付方式: ${order.pay_way}`);
console.log(`订单状态: ${order.status}`);
console.log(`创建时间: ${order.created_at}`);
// 订单详情
if (order.details && order.details.length > 0) {
order.details.forEach(detail => {
console.log(` 商品ID: ${detail.product_id}`);
console.log(` SKU: ${detail.sku}`);
console.log(` 数量: ${detail.quantity}`);
console.log(` 单价: $${detail.single_price}`);
console.log(` 总价: $${detail.total_price}`);
});
}
});
} else {
console.error('获取零售订单失败:', retailOrdersResponse.message);
}
// 获取零售订单列表(简化版本)
const retailOrders = await sdk.getRetailOrdersSimple(1, 10);
if (retailOrders) {
console.log('订单总数:', retailOrders.total);
retailOrders.orders.forEach(order => {
console.log(`订单ID: ${order.order_id}, 金额: $${order.total_amount}, 状态: ${order.status}`);
});
} else {
console.log('获取零售订单失败');
}
```
#### 获取用户地址列表
```javascript
// 获取用户地址列表(完整响应)
const addressesResponse = await sdk.getAddresses();
if (addressesResponse.success && addressesResponse.addresses) {
addressesResponse.addresses.forEach(address => {
console.log(`地址ID: ${address.addressId}`);
console.log(`收货人: ${address.consignee}`);
console.log(`电话: ${address.phone}`);
console.log(`地址: ${address.address}`);
console.log(`区域ID: ${address.regionId}`);
console.log(`是否默认: ${address.isDefault}`);
});
} else {
console.error('获取地址列表失败:', addressesResponse.message);
}
// 获取用户地址列表(简化版本)
const addresses = await sdk.getAddressesSimple();
if (addresses) {
addresses.forEach(address => {
console.log(`收货人: ${address.consignee}, 地址: ${address.address}`);
});
} else {
console.log('获取地址列表失败');
}
// 根据地址ID获取地址信息
const address = await sdk.getAddressById(123);
if (address) {
console.log('地址信息:', address);
} else {
console.log('地址不存在');
}
```
#### 获取支付记录列表
```javascript
// 获取支付记录列表(完整响应)
const paymentRecordsResponse = await sdk.getPaymentRecords({
page: 1,
pageSize: 10,
status: 'completed', // 可选:筛选状态
recordType: 1, // 可选:筛选记录类型
methodId: 1 // 可选:筛选支付方式
});
if (paymentRecordsResponse.success) {
console.log('支付记录总数:', paymentRecordsResponse.total);
paymentRecordsResponse.records.forEach(record => {
console.log(`记录ID: ${record.id}`);
console.log(`订单ID: ${record.orderId}`);
console.log(`金额: $${record.amount}`);
console.log(`状态: ${record.status}`);
console.log(`创建时间: ${record.createTime}`);
console.log(`描述: ${record.description || '-'}`);
});
} else {
console.error('获取支付记录失败:', paymentRecordsResponse.message);
}
// 获取支付记