npm package: @mininuke01/nenuxpay-sdk
Description: NenuxPay SDK for JavaScript/TypeScript applications
Author: NenuxPay
Latest version: 0.0.4

# NenuxPay SDK

NenuxPay SDK 是一个用于集成 NenuxPay 支付服务的 JavaScript/TypeScript SDK，支持加密货币支付（USDT、BTC、ETH 等）。

## 特性

- 🚀 支持 TypeScript，提供完整的类型定义
- 💰 支持多种加密货币支付
- 🔒 安全的 API 密钥管理
- 🎨 提供原生 JavaScript 支付组件
- 📱 支持移动端和桌面端
- 🌍 支持沙盒和生产环境

## 安装

```bash
npm install @mininuke01/nenuxpay-sdk
# 或
pnpm add @mininuke01/nenuxpay-sdk
# 或
yarn add @mininuke01/nenuxpay-sdk
```

## 快速开始

### 1. 初始化 SDK

```javascript
import { NenuxPay } from '@mininuke01/nenuxpay-sdk';

const nenuxpay = new NenuxPay({
  apiKey: 'sk_test_...', // 你的 API 密钥
  environment: 'sandbox' // 'sandbox' 或 'production'
});
```

### 2. 创建订单

```javascript
const order = await nenuxpay.orders.create({
  amount: 100,
  currency: 'USDT',
  merchantId: 'merchant_123',
  orderId: 'order_456',
  returnUrl: 'https://yoursite.com/success',
  cancelUrl: 'https://yoursite.com/cancel', // 可选
  metadata: { // 可选
    userId: 'user_789',
    productName: '数字产品'
  }
});

console.log('订单创建成功:', order);
```

### 3. 使用支付按钮

```javascript
import { createPaymentButton } from '@mininuke01/nenuxpay-sdk';

const paymentButton = createPaymentButton({
  config: {
    apiKey: 'sk_test_...',
    environment: 'sandbox'
  },
  amount: 100,
  currency: 'USDT',
  orderId: 'order_123',
  merchantId: 'merchant_123',
  returnUrl: 'https://yoursite.com/success',
  onSuccess: (result) => {
    console.log('支付成功:', result);
    // 处理成功逻辑
  },
  onError: (error) => {
    console.error('支付失败:', error);
    // 处理错误逻辑
  },
  onCancel: () => {
    console.log('支付取消');
    // 处理取消逻辑
  }
});

// 挂载到页面
paymentButton.mount('#payment-container');
```

### 4. 使用 React Hooks

```typescript
import React from 'react';
import { useNenuxPay, PaymentModal } from '@mininuke01/nenuxpay-sdk';

function PaymentComponent() {
  const [showModal, setShowModal] = React.useState(false);
  
  const { createOrder, isLoading, error } = useNenuxPay({
    config: {
      apiKey: 'sk_test_...',
      environment: 'sandbox'
    },
    onSuccess: (result) => {
      console.log('支付成功:', result);
      setShowModal(false);
    },
    onError: (error) => {
      console.error('支付失败:', error);
    },
    onCancel: () => {
      console.log('支付取消');
      setShowModal(false);
    }
  });

  const handlePayment = async () => {
    try {
      const order = await createOrder({
        amount: 100,
        currency: 'USDT',
        merchantId: 'merchant_123',
        orderId: `order_${Date.now()}`,
        returnUrl: 'https://yoursite.com/success'
      });
      setShowModal(true);
    } catch (err) {
      console.error('创建订单失败:', err);
    }
  };

  return (
    <div>
      <button onClick={handlePayment} disabled={isLoading}>
        {isLoading ? '处理中...' : '立即支付'}
      </button>
      
      {error && (
        <div style={{ color: 'red' }}>
          错误: {error.message}
        </div>
      )}

      <PaymentModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        config={{
          apiKey: 'sk_test_...',
          environment: 'sandbox'
        }}
        amount={100}
        currency="USDT"
        orderId={`order_${Date.now()}`}
        merchantId="merchant_123"
        returnUrl="https://yoursite.com/success"
        onSuccess={(result) => {
          console.log('支付成功:', result);
          setShowModal(false);
        }}
        onError={(error) => {
          console.error('支付失败:', error);
        }}
        onCancel={() => {
          console.log('支付取消');
          setShowModal(false);
        }}
      />
    </div>
  );
}
```

## API 参考

### NenuxPay 类

#### 构造函数

```typescript
new NenuxPay(config: NenuxPayConfig)
```

**参数:**
- `config.apiKey` (string): API 密钥
- `config.environment` (string): 环境，'sandbox' 或 'production'
- `config.baseUrl` (string, 可选): 自定义 API 基础 URL
- `config.timeout` (number, 可选): 请求超时时间，默认 30000ms

### 订单管理

#### 创建订单

```typescript
nenuxpay.orders.create(orderData: CreateOrderRequest): Promise<Order>
```

**参数:**
- `amount` (number): 支付金额
- `currency` (string): 货币类型，支持 'USDT', 'BTC', 'ETH', 'USDC'
- `merchantId` (string): 商户 ID
- `orderId` (string): 订单 ID（唯一）
- `returnUrl` (string): 支付成功返回 URL
- `cancelUrl` (string, 可选): 支付取消返回 URL
- `notifyUrl` (string, 可选): 支付结果通知 URL
- `metadata` (object, 可选): 自定义元数据

#### 获取订单

```typescript
nenuxpay.orders.get(orderId: string): Promise<Order>
```

#### 取消订单

```typescript
nenuxpay.orders.cancel(orderId: string): Promise<Order>
```

#### 获取支付结果

```typescript
nenuxpay.orders.getPaymentResult(orderId: string): Promise<PaymentResult>
```

### 支付按钮组件

#### 创建支付按钮

```typescript
createPaymentButton(options: PaymentButtonOptions): PaymentButton
```

**选项:**
- `config` (NenuxPayConfig): SDK 配置
- `amount` (number): 支付金额
- `currency` (string): 货币类型
- `orderId` (string): 订单 ID
- `merchantId` (string): 商户 ID
- `returnUrl` (string): 返回 URL
- `onSuccess` (function, 可选): 支付成功回调
- `onError` (function, 可选): 支付失败回调
- `onCancel` (function, 可选): 支付取消回调
- `buttonText` (string, 可选): 按钮文本
- `className` (string, 可选): CSS 类名
- `style` (object, 可选): 内联样式

### React Hooks

#### useNenuxPay Hook

```typescript
useNenuxPay(options: UseNenuxPayOptions): UseNenuxPayReturn
```

**选项:**
- `config` (NenuxPayConfig): SDK 配置
- `onSuccess` (function, 可选): 支付成功回调
- `onError` (function, 可选): 支付失败回调
- `onCancel` (function, 可选): 支付取消回调

**返回值:**
- `createOrder` (function): 创建订单函数
- `getOrder` (function): 获取订单函数
- `cancelOrder` (function): 取消订单函数
- `isLoading` (boolean): 加载状态
- `error` (Error | null): 错误信息

#### PaymentModal 组件

```typescript
<PaymentModal
  isOpen={boolean}
  onClose={() => void}
  config={NenuxPayConfig}
  amount={number}
  currency={string}
  orderId={string}
  merchantId={string}
  returnUrl={string}
  onSuccess={(result) => void}
  onError={(error) => void}
  onCancel={() => void}
/>
```

**属性:**
- `isOpen` (boolean): 模态框是否打开
- `onClose` (function): 关闭模态框回调
- `config` (NenuxPayConfig): SDK 配置
- `amount` (number): 支付金额
- `currency` (string): 货币类型
- `orderId` (string): 订单 ID
- `merchantId` (string): 商户 ID
- `returnUrl` (string): 返回 URL
- `onSuccess` (function, 可选): 支付成功回调
- `onError` (function, 可选): 支付失败回调
- `onCancel` (function, 可选): 支付取消回调

### Vue 组合式 API

#### 安装 Vue 支持

```bash
npm install @mininuke01/nenuxpay-sdk
```

#### 使用 Vue Composable

```vue
<template>
  <div>
    <button @click="handlePayment" :disabled="isLoading">
      {{ isLoading ? '处理中...' : '立即支付' }}
    </button>
    
    <div v-if="error" style="color: red;">
      错误: {{ error.message }}
    </div>

    <PaymentModal
      :is-open="showModal"
      @close="showModal = false"
      :config="config"
      :amount="100"
      currency="USDT"
      :order-id="`order_${Date.now()}`"
      merchant-id="merchant_123"
      return-url="https://yoursite.com/success"
      @success="onPaymentSuccess"
      @error="onPaymentError"
      @cancel="onPaymentCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useNenuxPay, PaymentModal } from '@mininuke01/nenuxpay-sdk/vue'

const showModal = ref(false)

const config = {
  apiKey: 'sk_test_...',
  environment: 'sandbox' as const
}

const { createOrder, isLoading, error } = useNenuxPay({
  config,
  onSuccess: (result) => {
    console.log('支付成功:', result)
    showModal.value = false
  },
  onError: (error) => {
    console.error('支付失败:', error)
  },
  onCancel: () => {
    console.log('支付取消')
    showModal.value = false
  }
})

const handlePayment = async () => {
  try {
    const order = await createOrder({
      amount: 100,
      currency: 'USDT',
      merchantId: 'merchant_123',
      orderId: `order_${Date.now()}`,
      returnUrl: 'https://yoursite.com/success'
    })
    showModal.value = true
  } catch (err) {
    console.error('创建订单失败:', err)
  }
}

const onPaymentSuccess = (result: any) => {
  console.log('支付成功:', result)
  showModal.value = false
}

const onPaymentError = (error: any) => {
  console.error('支付失败:', error)
}

const onPaymentCancel = () => {
  console.log('支付取消')
  showModal.value = false
}
</script>
```

#### useNenuxPay Composable

```typescript
import { useNenuxPay } from '@mininuke01/nenuxpay-sdk/vue'

const { 
  createOrder, 
  getOrder, 
  cancelOrder, 
  getPaymentResult,
  isLoading, 
  error 
} = useNenuxPay(options)
```

**选项:**
- `config` (NenuxPayConfig): SDK 配置
- `onSuccess` (function, 可选): 支付成功回调
- `onError` (function, 可选): 支付失败回调
- `onCancel` (function, 可选): 支付取消回调

**返回值:**
- `createOrder` (function): 创建订单函数
- `getOrder` (function): 获取订单函数
- `cancelOrder` (function): 取消订单函数
- `getPaymentResult` (function): 获取支付结果函数
- `isLoading` (Ref<boolean>): 加载状态
- `error` (Ref<Error | null>): 错误信息

#### Vue 组件

##### PaymentButton 组件

```vue
<template>
  <PaymentButton
    :config="config"
    :amount="100"
    currency="USDT"
    :order-id="`order_${Date.now()}`"
    merchant-id="merchant_123"
    return-url="https://yoursite.com/success"
    button-text="立即支付"
    @success="onPaymentSuccess"
    @error="onPaymentError"
    @cancel="onPaymentCancel"
  />
</template>

<script setup lang="ts">
import { PaymentButton } from '@mininuke01/nenuxpay-sdk/vue'

const config = {
  apiKey: 'sk_test_...',
  environment: 'sandbox' as const
}

const onPaymentSuccess = (result: any) => {
  console.log('支付成功:', result)
}

const onPaymentError = (error: any) => {
  console.error('支付失败:', error)
}

const onPaymentCancel = () => {
  console.log('支付取消')
}
</script>
```

##### PaymentModal 组件

```vue
<template>
  <PaymentModal
    :is-open="isOpen"
    @close="$emit('close')"
    :config="config"
    :amount="amount"
    :currency="currency"
    :order-id="orderId"
    :merchant-id="merchantId"
    :return-url="returnUrl"
    @success="$emit('success', $event)"
    @error="$emit('error', $event)"
    @cancel="$emit('cancel')"
  />
</template>

<script setup lang="ts">
import { PaymentModal } from '@mininuke01/nenuxpay-sdk/vue'

defineProps<{
  isOpen: boolean
  config: any
  amount: number
  currency: string
  orderId: string
  merchantId: string
  returnUrl: string
}>()

defineEmits<{
  close: []
  success: [result: any]
  error: [error: any]
  cancel: []
}>()
</script>
```

## 错误处理

SDK 使用 `NenuxPayError` 类来处理错误：

```javascript
try {
  const order = await nenuxpay.orders.create(orderData);
} catch (error) {
  if (error instanceof NenuxPayError) {
    console.error('错误代码:', error.code);
    console.error('错误信息:', error.message);
    console.error('错误详情:', error.details);
  }
}
```

## 支持的货币

- USDT (Tether)
- BTC (Bitcoin)
- ETH (Ethereum)
- USDC (USD Coin)

## 环境配置

### 沙盒环境
- API 密钥前缀: `sk_test_`
- 基础 URL: `https://api-sandbox.nenuxpay.com/v1`

### 生产环境
- API 密钥前缀: `sk_live_`
- 基础 URL: `https://api.nenuxpay.com/v1`

## 许可证

MIT License

## 支持

如有问题或建议，请联系我们：
- 邮箱: support@nenuxpay.com
- 文档: https://docs.nenuxpay.com
- GitHub: https://github.com/nenuxpay/sdk