npm package: @mencraft/longswipe-react-sdk
Description: React SDK for Longswipe Merchant Integration API
Author: mencraft
Latest version: 1.0.0

# Longswipe React SDK

A React SDK for integrating with the Longswipe Merchant Integration API.

## Installation

```bash
npm install longswipe-react-sdk
# or
yarn add longswipe-react-sdk
```

## Components and Hooks

### VoucherRedemption Component

A ready-to-use React component for voucher redemption with a clean UI.

```typescript
import { VoucherRedemption } from 'longswipe-react-sdk';

function App() {
  const handleSuccess = (message: string) => {
    console.log('Success:', message);
  };

  const handleError = (error: string) => {
    console.error('Error:', error);
  };

  return (
    <VoucherRedemption
      apiKey="your_api_key_here"
      onSuccess={handleSuccess}
      onError={handleError}
    />
  );
}
```

#### Props

| Prop       | Type                    | Required | Description                                     |
|------------|-------------------------|----------|-------------------------------------------------|
| apiKey     | string                 | Yes      | Your Longswipe API key                          |
| onSuccess  | (message: string) => void | No    | Callback function when voucher redemption succeeds |
| onError    | (error: string) => void  | No     | Callback function when an error occurs           |

### useVoucherRedemption Hook

A custom hook for implementing your own voucher redemption UI.

```typescript
import { useVoucherRedemption } from 'longswipe-react-sdk';

function CustomVoucherRedemption() {
  const {
    verifyVoucher,
    redeemVoucher,
    voucherDetails,
    loading,
    error,
    resetError,
    resetVoucherDetails
  } = useVoucherRedemption({
    apiKey: 'your_api_key_here'
  });

  const handleVerify = async (code: string) => {
    await verifyVoucher(code);
  };

  const handleRedeem = async (amount: number, pin: string) => {
    await redeemVoucher(amount, pin);
  };

  return (
    <div>
      {error && <div>{error}</div>}
      {loading && <div>Loading...</div>}
      {voucherDetails && (
        <div>
          <p>Amount: {voucherDetails.amount}</p>
          <p>Balance: {voucherDetails.balance}</p>
        </div>
      )}
      {/* Your custom UI implementation */}
    </div>
  );
}
```

#### Hook Return Values

| Value              | Type                                      | Description                                     |
|-------------------|-------------------------------------------|------------------------------------------------|
| verifyVoucher     | (code: string) => Promise<void>           | Function to verify a voucher code               |
| redeemVoucher     | (amount: number, pin: string) => Promise<void> | Function to redeem a verified voucher     |
| voucherDetails    | Voucher \| null                           | Details of the verified voucher                 |
| loading           | boolean                                   | Loading state for async operations              |
| error             | string \| null                            | Error message if any operation fails            |
| resetError        | () => void                                | Function to clear the error state               |
| resetVoucherDetails | () => void                              | Function to clear voucher details and state     |

## API Usage

### Initialize the SDK

```typescript
import { LongswipeAPI } from 'longswipe-react-sdk';

const longswipe = new LongswipeAPI({
  apiKey: 'your_api_key_here',
  baseUrl: 'https://api.longswipe.com' // optional, defaults to this value
});
```

### Available Methods

#### Create Invoice
Create a new invoice for a merchant.

```typescript
const invoice = {
  blockchainNetworkId: "network_id",
  currencyId: "currency_id",
  dueDate: "2025-01-26",
  invoiceDate: "2025-01-26",
  invoiceItems: [
    {
      description: "Item description",
      quantity: 1,
      unitPrice: 100
    }
  ],
  merchantUserId: "merchant_id"
};

const response = await longswipe.createInvoice(invoice);
```

#### Fetch Admin Charges
Retrieve the current admin charges configuration.

```typescript
const charges = await longswipe.fetchAdminCharges();
```

#### Fetch Invoices
Retrieve a paginated list of merchant invoices.

```typescript
const invoices = await longswipe.fetchInvoices(1, 10, 0);
```

#### Fetch Supported Currencies
Get a list of supported currencies.

```typescript
const currencies = await longswipe.fetchSupportedCurrencies();
```

#### Fetch Voucher Redemption Charges
Calculate charges for redeeming a voucher.

```typescript
const charges = await longswipe.fetchVoucherRedemptionCharges({
  amount: 100,
  lockPin: "1234",
  voucherCode: "VOUCHER123"
});
```

#### Redeem Voucher
Redeem a voucher.

```typescript
const result = await longswipe.redeemVoucher({
  amount: 100,
  lockPin: "1234",
  voucherCode: "VOUCHER123"
});
```

#### Update Admin Charges
Update the admin charges configuration.

```typescript
const updated = await longswipe.updateAdminCharges({
  takeChargesFromWallet: true
});
```

#### Verify Voucher
Verify a voucher's validity and details.

```typescript
const voucher = await longswipe.verifyVoucher({
  voucherCode: "VOUCHER123"
});
```

## Development

1. Clone the repository
2. Install dependencies:
   ```bash
   npm install
   ```
3. Start the demo:
   ```bash
   npm run demo
   ```
4. Build the package:
   ```bash
   npm run build
   ```

## Response Types

All API methods return a response with the following structure:

```typescript
interface MerchantIntegrationResponse<T> {
  code: number;
  message: string;
  status: string;
  data?: T;
}
```

## Error Handling

The SDK includes built-in error handling. All methods return a response object that includes error information when applicable:

```typescript
try {
  const result = await longswipe.verifyVoucher({
    voucherCode: "INVALID_CODE"
  });
  
  if (result.status === 'error') {
    console.error('Error:', result.message);
    return;
  }
  
  // Handle successful response
  console.log('Voucher details:', result.data);
} catch (error) {
  console.error('Unexpected error:', error);
}
```

## License

MIT