npm package: @funnelpay/billing
Description: JavaScript SDK for Funnelpay billing with Primer integration
Author: Funnelpay
Latest version: 0.1.0

# @funnelpay/billing

A modern TypeScript SDK for subscription payments with Primer Headless Checkout integration.

## Features

- **Modern API**: Clean, Promise-based interface with event-driven architecture
- **Dynamic Pricing**: Update prices without page reload
- **Type-Safe**: Complete TypeScript definitions and type safety
- **Event-Driven**: Handle success, errors, and status changes with ease
- **Robust**: Built-in error handling, retries, and validation
- **Lightweight**: Minimal dependencies, browser-optimized
- **Headless Checkout**: Full control over checkout UI with Primer Headless Checkout

## Installation

### Via NPM

```bash
npm install @funnelpay/billing @primer-io/checkout-web
```

### Via CDN

```html
<script src="https://sdk.primer.io/web/v2.57.3/Primer.min.js"></script>
<link rel="stylesheet" href="https://sdk.primer.io/web/v2.57.3/Checkout.css" />
<script src="https://unpkg.com/@funnelpay/billing@latest/dist/funnelpay-billing.min.js"></script>
```

## Quick Start

```typescript
import { Billing } from '@funnelpay/billing';

Billing.configure({ orgId: 'your-org-id' });

const checkout = await Billing.createCheckout({
  orgId: 'your-org-id',
  priceId: 'price_123',
  customer: {
    externalId: 'user_456',
    email: 'user@example.com',
  },
  container: '#checkout-container',
});

checkout.on('success', (result) => {
  console.log('Payment succeeded:', result.orderId);
});

checkout.on('error', (error) => {
  console.error('Payment failed:', error.message);
});
```

## API Reference

### `configure(config)`

Configure global SDK settings.

```typescript
import { configure } from '@funnelpay/billing';

configure({
  orgId: 'your-org-id',
  baseUrl: 'https://billing.funnelpay.com', // optional
  region: 'default', // optional
});
```

### `createCheckout(options)`

Creates a new checkout instance.

- `options.orgId` (string) - Organization identifier
- `options.priceId` (string, required) - Price identifier
- `options.customer` (object, required) - Customer info
- `options.container` (string, required) - CSS selector for container
- Returns: `Promise<CheckoutInstance>`

### `createClientSession(params)`

Create a client session manually (for advanced integrations).

- Returns: `Promise<{ clientToken: string, orderId: string, type: string }>`

### CheckoutInstance

#### Properties

- `id` - Unique checkout identifier
- `state` - Current state
- `orderId` - Order identifier
- `isDestroyed` - Whether checkout has been destroyed

#### Methods

- `updatePrice(priceId)` - Update checkout price
- `getStatus()` - Get current status
- `destroy()` - Destroy instance and clean up
- `isReady()` - Check if ready
- `isProcessing()` - Check if processing

#### Events

- `'success'` - Payment completed
- `'error'` - Payment failed
- `'status-change'` - State changed
- `'destroy'` - Checkout destroyed

## Development

```bash
npm install
npm run build
npm run dev       # watch mode
npm run typecheck
npm run lint
npm run test
```

## tree

billing/
├── package.json # @funnelpay/billing 包配置
├── tsconfig.json # TypeScript 配置
├── rollup.config.mjs # Rollup 构建配置（ESM/CJS/UMD/Min 四种格式）
├── eslint.config.mjs # ESLint 配置
├── jest.config.ts # Jest 测试配置
├── .prettierrc # Prettier 格式化配置
├── .gitignore
├── LICENSE # MIT 协议
├── README.md # 使用文档
├── src/
│ ├── index.ts # 主入口，导出 Billing/configure/createCheckout 等
│ ├── enums.ts # PaymentMethod 枚举
│ ├── types.ts # 完整的 TypeScript 类型定义
│ ├── constants.ts # SDK 版本、API 端点、事件名、错误码等常量
│ ├── errors.ts # 错误类层级（FunnelpaySDKError → ValidationError/APIError/...）
│ ├── event-emitter.ts # 轻量级事件发射器
│ ├── utils.ts # 工具函数（merge, retry, withTimeout 等）
│ ├── validation.ts # 输入校验
│ ├── config.ts # 全局配置管理
│ ├── api-client.ts # REST API 客户端（session/payment 接口）
│ ├── primer-wrapper.ts # Primer Headless Checkout 封装
│ ├── checkout-instance.ts # CheckoutInstance 生命周期管理
│ ├── loader.ts # 加载动画 UI 组件
│ └── skin/
│ └── default-skin.ts # 默认皮肤骨架（TODO 待实现）
└── dist/ # 构建产物
├── funnelpay-billing.esm.js
├── funnelpay-billing.cjs.js
├── funnelpay-billing.js (UMD)
├── funnelpay-billing.min.js (UMD 压缩)
└── types/ (TypeScript 类型声明)

## License

MIT © Funnelpay