# wx-share-ts

一个用于微信分享的 TypeScript 工具包，提供了简单易用的 API 来配置微信分享功能。

## 安装

```bash
npm install wx-share-ts
# 或者
yarn add wx-share-ts
# 或者
pnpm add wx-share-ts
```

## 使用方法

### 基础用法

```typescript
import { createWxShare } from "wx-share-ts";

// 创建分享实例
const wxShare = createWxShare();

// 设置分享配置
wxShare.setShareOptions({
  title: "分享标题",
  desc: "分享描述",
  link: "https://example.com",
  imgUrl: "https://example.com/image.jpg",
});

// 从API获取签名配置并初始化分享
await wxShare.fetchSignConfigAndShare({
  url: "/api/wx-share", // 可选，默认为 /api/v2/wx-share
});
```

### 高级用法

```typescript
import { createWxShare } from "wx-share-ts";

const wxShare = createWxShare()
  .setDebug(true) // 开启调试模式
  .setShareOptions({
    title: "分享标题",
    desc: "分享描述",
    link: "https://example.com",
    imgUrl: "https://example.com/image.jpg",
    success: () => console.log("分享成功"),
    fail: (err) => console.error("分享失败:", err),
    cancel: () => console.log("取消分享"),
  });

// 使用自定义的签名配置获取方法
await wxShare
  .setCustomFetch(async (url) => {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ url: window.location.href }),
    });
    return response.json();
  })
  .fetchSignConfigAndShare();
```

## API 文档

### createWxShare()

创建微信分享实例。

### setDebug(debug: boolean)

设置调试模式。

### setShareOptions(options: ShareConfig)

设置分享配置。

### fetchSignConfigAndShare(options?: SignConfigOptions)

从 API 获取签名配置并初始化分享。

### setCustomFetch(customFetch: (url: string) => Promise<SignConfigResponse>)

设置自定义的签名配置获取方法。

## 类型定义

```typescript
interface ShareConfig {
  title?: string;
  desc?: string;
  link?: string;
  imgUrl?: string;
  success?: () => void;
  fail?: (err: any) => void;
  cancel?: () => void;
}

interface SignConfig {
  appId: string;
  timestamp: string;
  nonceStr: string;
  signature: string;
}

interface SignConfigResponse {
  data: SignConfig;
}

interface SignConfigOptions {
  url?: string;
  customFetch?: (url: string) => Promise<SignConfigResponse>;
}
```

## 注意事项

1. 使用前需要确保已经引入了微信 JS-SDK
2. 需要在微信浏览器环境中使用
3. 需要后端提供签名配置接口
4. 建议在生产环境中关闭调试模式

## License

MIT
