# NakaPay Node.js SDK

[![npm version](https://badge.fury.io/js/nakapay-sdk.svg)](https://badge.fury.io/js/nakapay-sdk) <!-- Placeholder badge -->

The official Node.js SDK for interacting with the [NakaPay API](https://api.nakapay.app). Easily integrate Bitcoin Lightning Network payments into your Node.js applications.

⚠️ **SECURITY WARNING**: This SDK is designed for SERVER-SIDE use only. Never expose your API keys in client-side code, frontend applications, or environment variables with public prefixes like `NEXT_PUBLIC_`.

## Features

*   Create and manage Lightning payment requests.
*   Check the status of payments.
*   Retrieve payment history.
*   Register webhooks for real-time payment notifications.
*   Typed interfaces for robust development with TypeScript.
*   Simple error handling.

## Security Best Practices

🔒 **API Key Security:**
- Store API keys in server environment variables only
- Never use `NEXT_PUBLIC_` prefix in Next.js applications
- Never commit API keys to version control
- Use different API keys for development and production
- Rotate API keys regularly

## Installation

Install the SDK using npm:

```bash
npm install nakapay-sdk
```

Or using yarn:

```bash
yarn add nakapay-sdk
```

## Getting Started

First, you'll need an API key from your NakaPay dashboard.

```typescript
import { NakaPay } from 'nakapay-sdk';

// SECURE: Initialize the client with your API key from environment variable
// NEVER hardcode API keys or use client-side environment variables
const nakaPay = new NakaPay(process.env.NAKAPAY_API_KEY); // NOT NEXT_PUBLIC_NAKAPAY_API_KEY

async function createPayment() {
  try {
    // Input validation is recommended
    const amount = 100; // Amount in satoshis
    
    if (!amount || amount <= 0) {
      throw new Error('Invalid payment amount');
    }

    // First, get your business profile to use the configured destination wallet
    const businessProfile = await nakaPay.getBusinessProfile();
    console.log('Business Name:', businessProfile.name);
    console.log('Lightning Address:', businessProfile.lightningAddress);

    const paymentRequest = await nakaPay.createPaymentRequest({
      amount: amount,
      description: 'Payment for Order #123',
      destinationWallet: businessProfile.lightningAddress, // Use your configured lightning address
      metadata: { orderId: '123', customerId: '456' }
    });

    console.log('Payment Request Created:', paymentRequest);
    console.log(`Invoice: ${paymentRequest.invoice}`);
    console.log(`Pay this invoice or show QR code for: ${paymentRequest.invoice}`);

    // You can then poll for payment status or use webhooks
    // For example, to check status after a delay:
    setTimeout(async () => {
      const status = await nakaPay.getPaymentStatus(paymentRequest.id);
      console.log(`Payment ID ${paymentRequest.id} Status:`, status.status);
    }, 30000); // Check after 30 seconds

  } catch (error) {
    console.error('Error creating payment request:', error.message);
  }
}

createPayment();
```

## API

The SDK provides the following methods:

*   `new NakaPay(apiKey: string, options?: { baseUrl?: string })`: Constructor to initialize the client.
*   `createPaymentRequest(options: PaymentRequestOptions): Promise<PaymentRequest>`
*   `getPaymentRequest(id: string): Promise<PaymentRequest>`
*   `getPaymentStatus(id: string): Promise<PaymentStatus>`
*   `getBusinessProfile(): Promise<Business>`: Get current business profile information
*   `getPayments(businessId: string, options?: { limit?: number; offset?: number }): Promise<PaymentRequest[]>`
*   `registerWebhook(businessId: string, options: WebhookOptions): Promise<{ success: boolean; message: string }>`

Refer to the `index.ts` file or the main NakaPay API documentation for detailed information on request/response types.

## Testing

The SDK includes both unit and integration tests.

### Running Unit Tests

Unit tests test the basic functionality without external dependencies:

```bash
npm test
# or specifically
npm run test:unit
```

### Running Integration Tests

Integration tests require a running NakaPay API server and Supabase setup:

1. Copy the environment file: `cp .env.example .env`
2. Fill in your test environment variables in `.env`
3. Run integration tests: `npm run test:integration`

### CI/CD

The project includes GitHub Actions CI that:
- Tests the SDK across Node.js versions 16.x, 18.x, and 20.x
- Runs unit tests (integration tests are skipped in CI)
- Builds the TypeScript code
- Verifies the build artifacts

## Contributing

Contributions are welcome! Please open an issue or submit a pull request to the [NakaPay SDK repository](https://github.com/hubavka/nakapay-sdk).

## License

[MIT](LICENSE) <!-- Assuming MIT license, a LICENSE file might be needed at the root or SDK level -->
