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

# Longswipe  React SDK

[![npm version](https://img.shields.io/npm/v/@longswipe/longswipe-react.svg)](https://www.npmjs.com/package/@longswipe/longswipe-react)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-4.0-blue.svg)](https://www.typescriptlang.org/)
[![React](https://img.shields.io/badge/React-18.0+-61DAFB.svg?logo=react&logoColor=white)](https://reactjs.org/)
[![npm download][download-image]][download-url]

[download-image]: https://img.shields.io/npm/dm/@longswipe/longswipe-react.svg
[download-url]: https://npmjs.org/package/@longswipe/longswipe-react

[![@longswipe/longswipe-react](https://nodei.co/npm/@longswipe/longswipe-react.png)](https://npmjs.org/package/@longswipe/longswipe-react)



A React SDK for integrating the Longswipe Widget into your application. Provides both a component-based approach and a hook-based approach for maximum flexibility.

For detailed API documentation, visit the [Longswipe Developer Documentation](https://developer.longswipe.com/docs/).

## Installation


- using npm

```bash
npm install --save @longswipe/longswipe-react
```

- using yarn

```bash
yarn add @longswipe/longswipe-react
```

- CDN

```
https://unpkg.com/@longswipe/longswipe-react
```


## Integration Options

This SDK provides two ways to integrate the Longswipe Widget:

1. **LongswipeWidget Component**: A ready-to-use component with built-in UI
2. **useLongswipe Hook**: A flexible hook for custom UI implementations

## LongswipeWidget Component

A lightweight component that loads the Longswipe Widget script and provides a simple interface with built-in UI for integrating the widget into your application.

```typescript
import { LongswipeWidget, ResType } from '@longswipe/longswipe-react';

function App() {
  const handleResponse = (type: ResType, res?: any) => {
    switch (type) {
      case 'success':
        console.log('Success:', res);
        break;
      case 'error':
        console.error('Error:', res);
        break;
      case 'close':
        console.log('Widget closed');
        break;
      case 'start':
        console.log('Widget started');
        break;
      case 'loading':
        console.log('Widget loading');
        break;
    }
  };

  return (
    <LongswipeWidget
      apiKey="your_api_key_here"
      referenceId="unique-transaction-id"
      response={handleResponse}
      environment="sandbox" // or "production"
      defaultCurrency="USDT"
      defaultAmount={100}
      metaData={{ source: 'my-app' }}
      buttonText="Pay with Longswipe" // Optional custom button text
    />
  );
}
```

You can also provide your own custom button or clickable element:

```typescript
<LongswipeWidget
  apiKey="your_api_key_here"
  referenceId="unique-transaction-id"
  response={handleResponse}
  environment="sandbox"
>
  <button className="my-custom-button">Custom Payment Button</button>
</LongswipeWidget>
```

### Props

| Prop            | Type                    | Required | Description                                     |
|-----------------|-------------------------|----------|-------------------------------------------------|
| apiKey          | string                  | Yes      | Your Longswipe API key                          |
| referenceId     | string                  | Yes      | Unique identifier for the transaction           |
| response        | (type: ResType, res?: any) => void | Yes | Callback function for widget events      |
| environment     | 'production' \| 'sandbox' | No    | Environment to use (defaults to 'sandbox')      |
| defaultCurrency | 'USD' \| 'NGN' \| 'GBP' \| 'USDT' \| 'USDC' | No | Default currency for redemption |
| defaultAmount   | number                  | No       | Default amount for redemption                   |
| config          | Record<string, unknown> | No       | Additional configuration options                |
| metaData        | Record<string, unknown> | No       | Metadata to pass to the widget                  |
| buttonText      | string                  | No       | Custom text for the default button              |
| children        | React.ReactNode         | No       | Custom button or clickable element              |

### Response Types

The `response` callback receives a type parameter that can be one of the following:

| Type     | Description                                     |
|----------|-------------------------------------------------|
| success  | Widget operation completed successfully         |
| error    | An error occurred during widget operation       |
| close    | Widget was closed by the user                   |
| start    | Widget has started and is ready                 |
| loading  | Widget is loading                               |

## useLongswipe Hook

A flexible hook that provides more control over the Longswipe Widget integration, allowing you to create custom UI components.

```typescript
import { useLongswipe, ResType } from '@longswipe/longswipe-react';

function CustomPaymentButton() {
  const handleResponse = (type: ResType, res?: any) => {
    switch (type) {
      case 'success':
        console.log('Success:', res);
        break;
      case 'error':
        console.error('Error:', res);
        break;
      case 'close':
        console.log('Widget closed');
        break;
      case 'start':
        console.log('Widget started');
        break;
      case 'loading':
        console.log('Widget loading');
        break;
    }
  };

  const { openModal, isLoaded, reload } = useLongswipe({
    apiKey: 'your_api_key_here',
    referenceId: 'unique-transaction-id',
    environment: 'sandbox', // or "production"
    defaultCurrency: 'USDT',
    defaultAmount: 100,
    metaData: { source: 'my-app' },
    onResponse: handleResponse
  });

  return (
    <div>
      <button 
        onClick={openModal} 
        disabled={!isLoaded}
        style={{ 
          backgroundColor: '#0066ff',
          color: 'white',
          padding: '10px 16px',
          borderRadius: '4px'
        }}
      >
        Pay with Longswipe
      </button>
      
      {!isLoaded && <p>Loading payment system...</p>}
      
      <button onClick={reload}>
        Reload Payment System
      </button>
    </div>
  );
}
```

### Hook Parameters

The `useLongswipe` hook accepts an options object with the following properties:

| Parameter       | Type                    | Required | Description                                     |
|-----------------|-------------------------|----------|-------------------------------------------------|
| apiKey          | string                  | Yes      | Your Longswipe API key                          |
| referenceId     | string                  | Yes      | Unique identifier for the transaction           |
| onResponse      | (type: ResType, res?: any) => void | Yes | Callback function for widget events      |
| environment     | 'production' \| 'sandbox' | No    | Environment to use (defaults to 'sandbox')      |
| defaultCurrency | 'USD' \| 'NGN' \| 'GBP' \| 'USDT' \| 'USDC' | No | Default currency for redemption |
| defaultAmount   | number                  | No       | Default amount for redemption                   |
| config          | Record<string, unknown> | No       | Additional configuration options                |
| metaData        | Record<string, unknown> | No       | Metadata to pass to the widget                  |

### Hook Return Values

The `useLongswipe` hook returns an object with the following properties:

| Property  | Type       | Description                                           |
|-----------|------------|-------------------------------------------------------|
| openModal | () => void | Function to open the Longswipe payment modal          |
| isLoaded  | boolean    | Whether the Longswipe script has loaded successfully  |
| reload    | () => void | Function to reload the Longswipe script if needed     |



## 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
   ```

## License

MIT