lightning-auth-and-payment
Version:
Lightning Network authentication and payment processing library for modern web applications
1,170 lines (898 loc) • 28.5 kB
Markdown
# API Reference
This document provides comprehensive documentation for all public methods, properties, classes, and interfaces in the `lightning-auth-and-payment` library.
## Table of Contents
- [CLI Commands](#cli-commands)
- [Core Hooks](#core-hooks)
- [Enhanced UI Components](#enhanced-ui-components)
- [Components](#components)
- [Context Providers](#context-providers)
- [Theme System](#theme-system)
- [Database Adapters](#database-adapters)
- [Payment Utilities](#payment-utilities)
- [Authentication Utilities](#authentication-utilities)
- [CORS Utilities](#cors-utilities)
- [Zero-Config Utilities](#zero-config-utilities)
- [Next.js Plugin](#nextjs-plugin)
- [Development Server](#development-server)
- [Types and Interfaces](#types-and-interfaces)
## CLI Commands
### `npx lightning-setup setup`
Sets up Lightning authentication in your Next.js project.
```bash
# Basic setup
npx lightning-setup setup
# Force reconfigure
npx lightning-setup setup --force
# With PostgreSQL
npx lightning-setup setup --database postgresql
# Verbose output
npx lightning-setup setup --verbose
```
**Options:**
- `--force, -f` - Force overwrite existing files
- `--database <type>` - Database type (sqlite, postgresql)
- `--verbose, -v` - Enable verbose logging
- `--help, -h` - Show help message
**What it does:**
- Installs required dependencies
- Sets up environment variables
- Configures Next.js with Lightning plugin
- Generates Prisma schema and database
- Creates all necessary API routes
- Sets up development scripts
### `npx lightning-setup check`
Checks the current setup status.
```bash
npx lightning-setup check
```
**Output:**
- ✅ Dependencies status
- ✅ Required files status
- ✅ Database status
- ❌ Missing components (if any)
### `npx lightning-dev-server`
Starts HTTPS development server for Lightning authentication.
```bash
# Start development server
npx lightning-dev-server
# With verbose logging
npx lightning-dev-server --verbose
```
**Options:**
- `--verbose, -v` - Enable verbose logging
- `--help, -h` - Show help message
## Enhanced UI Components
### LightningButton
Enhanced button component with Lightning-themed styling and multiple variants.
```tsx
import { LightningButton } from 'lightning-auth-and-payment';
// Basic usage
<LightningButton variant="lightning" size="md">
Pay with Lightning
</LightningButton>
// With payment integration
<LightningButton
variant="payment"
onClick={() => createInvoice(1000, 'Coffee')}
loading={isLoading}
>
Pay 1000 sats
</LightningButton>
```
**Props:**
- `variant`: 'lightning' | 'payment' | 'wallet' | 'send' | 'download' | 'copy' | 'external' | 'outline' | 'ghost'
- `size`: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
- `state`: 'default' | 'loading' | 'success' | 'error' | 'disabled'
- `animation`: 'none' | 'pulse' | 'bounce' | 'shake' | 'glow'
- `ripple`: boolean - Enable ripple effect
- `glow`: boolean - Enable glow effect
- `autoReset`: boolean - Auto-reset state after success/error
### LightningCard
Flexible card component for displaying Lightning Network data.
```tsx
import { LightningCard } from 'lightning-auth-and-payment';
<LightningCard
variant="payment"
title="Payment Details"
status="success"
interactive
>
<p>Payment of 1000 sats completed</p>
</LightningCard>
```
**Props:**
- `variant`: 'default' | 'payment' | 'user' | 'wallet' | 'transaction' | 'invoice' | 'channel' | 'node'
- `size`: 'sm' | 'md' | 'lg' | 'xl'
- `status`: 'default' | 'success' | 'error' | 'warning' | 'info' | 'pending' | 'loading' | 'disabled'
- `interactive`: boolean - Enable hover effects
- `collapsible`: boolean - Enable expand/collapse
- `glow`: boolean - Enable glow effect
### LightningBadge
Status badges with Lightning Network themes.
```tsx
import { LightningBadge } from 'lightning-auth-and-payment';
<LightningBadge variant="success" type="payment" count={1000}>
Paid
</LightningBadge>
```
**Props:**
- `variant`: 'default' | 'success' | 'error' | 'warning' | 'info' | 'pending' | 'loading' | 'disabled'
- `type`: 'default' | 'payment' | 'user' | 'wallet' | 'network' | 'security' | 'connection' | 'transaction' | 'invoice' | 'channel' | 'node' | 'trend' | 'activity'
- `size`: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
- `count`: number - Display count
- `clickable`: boolean - Enable click interaction
- `dismissible`: boolean - Enable dismiss functionality
### LightningInput
Enhanced input fields with Lightning styling.
```tsx
import { LightningInput } from 'lightning-auth-and-payment';
<LightningInput
type="text"
placeholder="Enter Lightning address"
variant="lightning"
copyable
required
/>
```
**Props:**
- `variant`: 'default' | 'lightning' | 'payment' | 'wallet' | 'address' | 'pubkey'
- `size`: 'sm' | 'md' | 'lg'
- `copyable`: boolean - Enable copy button
- `required`: boolean - Mark as required
- `disabled`: boolean - Disable input
- `readOnly`: boolean - Read-only mode
### LightningLogin
Complete login component with QR code integration.
```tsx
import { LightningLogin } from 'lightning-auth-and-payment';
<LightningLogin
variant="card"
size="lg"
showQRCode
showWalletRecommendations
onLogin={handleLogin}
onLogout={handleLogout}
/>
```
**Props:**
- `variant`: 'minimal' | 'card' | 'button'
- `size`: 'sm' | 'md' | 'lg' | 'xl'
- `showQRCode`: boolean - Display QR code
- `showWalletRecommendations`: boolean - Show wallet suggestions
- `onLogin`: () => void - Login handler
- `onLogout`: () => void - Logout handler
### LightningAuthModal
Authentication modal with wallet recommendations.
```tsx
import { LightningAuthModal } from 'lightning-auth-and-payment';
<LightningAuthModal
isOpen={showAuthModal}
onClose={() => setShowAuthModal(false)}
lnurl={lnurl}
k1={k1}
loading={isLoading}
error={error}
/>
```
**Props:**
- `isOpen`: boolean - Modal visibility
- `onClose`: () => void - Close handler
- `lnurl`: string - LNURL for authentication
- `k1`: string - Challenge key
- `loading`: boolean - Loading state
- `error`: string - Error message
### LightningPaymentModal
Payment processing modal with real-time updates.
```tsx
import { LightningPaymentModal } from 'lightning-auth-payment';
<LightningPaymentModal
isOpen={showPaymentModal}
onClose={() => setShowPaymentModal(false)}
invoice={invoice}
paymentState={paymentState}
timeLeft={timeLeft}
onCopyBolt11={copyBolt11}
copied={copied}
/>
```
**Props:**
- `isOpen`: boolean - Modal visibility
- `onClose`: () => void - Close handler
- `invoice`: Invoice object - Payment invoice
- `paymentState`: 'idle' | 'waiting' | 'settled' | 'expired'
- `timeLeft`: number - Time remaining in seconds
- `onCopyBolt11`: () => void - Copy BOLT11 handler
- `copied`: boolean - Copy state
### ThemeToggle
Light/dark theme switcher component.
```tsx
import { ThemeToggle } from 'lightning-auth-and-payment';
<ThemeToggle variant="button" size="md" showLabel />
```
**Props:**
- `variant`: 'button' | 'select' | 'icon'
- `size`: 'sm' | 'md' | 'lg'
- `showLabel`: boolean - Show theme label
- `onThemeChange`: (theme: 'light' | 'dark' | 'system') => void
## Core Hooks
### `useLightningAuth()`
The main authentication hook that combines authentication with session management and payment functionality.
```typescript
import { useLightningAuth } from 'lightning-auth-and-payment';
const {
user,
isAuthenticated,
isLoading,
error,
refetch,
createInvoice,
paymentState,
timeLeft,
copyBolt11,
copied,
handleLogin,
showAuthModal,
setShowAuthModal,
lnurl,
loginError,
k1
} = useLightningAuth();
```
#### Returns
| Property | Type | Description |
|----------|------|-------------|
| `user` | `User \| null` | Current authenticated user |
| `isAuthenticated` | `boolean` | Whether user is authenticated |
| `isLoading` | `boolean` | Whether authentication is loading |
| `error` | `string \| null` | Authentication error message |
| `refetch` | `() => Promise<void>` | Refetch user data |
| `createInvoice` | `(amount: number, description: string) => Promise<void>` | Create Lightning invoice |
| `paymentState` | `string` | Current payment state |
| `timeLeft` | `number` | Time left for payment |
| `copyBolt11` | `() => void` | Copy BOLT11 invoice to clipboard |
| `copied` | `boolean` | Whether invoice was copied |
| `handleLogin` | `() => Promise<void>` | Initiate Lightning login |
| `handleLogout` | `() => Promise<void>` | Logout user and clear session |
| `showAuthModal` | `boolean` | Whether auth modal is shown |
| `setShowAuthModal` | `(show: boolean) => void` | Control auth modal visibility |
| `lnurl` | `string \| null` | Generated LNURL for authentication |
| `loginError` | `string \| null` | Login error message |
| `k1` | `string \| null` | Authentication challenge key |
#### Example
```typescript
function LoginButton() {
const { isAuthenticated, handleLogin, handleLogout, isLoading, user } = useLightningAuth();
if (isAuthenticated) {
return (
<div>
<span>Welcome, {user?.lnPubkey?.slice(0, 8)}...</span>
<button onClick={handleLogout}>Logout</button>
</div>
);
}
return (
<button onClick={handleLogin} disabled={isLoading}>
{isLoading ? 'Connecting...' : 'Login with Lightning'}
</button>
);
}
```
### `useBTCPayPayment()`
Hook for managing BTCPay Server payment flow.
```typescript
import { useBTCPayPayment } from 'lightning-auth-and-payment';
const {
createInvoice,
paymentState,
timeLeft,
copyBolt11,
copied,
error
} = useBTCPayPayment();
```
#### Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `amount` | `number` | Payment amount in satoshis |
| `description` | `string` | Payment description |
| `metadata` | `Record<string, any>` | Additional metadata for the invoice |
#### Returns
| Property | Type | Description |
|----------|------|-------------|
| `createInvoice` | `(params: CreatePaymentParams) => Promise<void>` | Create BTCPay invoice |
| `paymentState` | `string` | Current payment state |
| `timeLeft` | `number` | Time left for payment |
| `copyBolt11` | `() => void` | Copy BOLT11 to clipboard |
| `copied` | `boolean` | Whether invoice was copied |
| `error` | `string \| null` | Payment error |
#### Example
```typescript
function PaymentButton() {
const { createInvoice, paymentState, timeLeft } = useBTCPayPayment();
const handlePayment = async () => {
await createInvoice({
amount: 1000,
description: 'Premium subscription',
metadata: { plan: 'premium' }
});
};
return (
<button onClick={handlePayment}>
Pay 1000 sats {timeLeft > 0 && `(${timeLeft}s left)`}
</button>
);
}
```
### `useLightningPayment()`
Generic Lightning payment hook for any Lightning Network payment.
```typescript
import { useLightningPayment } from 'lightning-auth-and-payment';
const {
createInvoice,
paymentState,
timeLeft,
copyBolt11,
copied,
error
} = useLightningPayment();
```
## Components
### `AuthModal`
Modal component for Lightning authentication.
```typescript
import { AuthModal } from 'lightning-auth-and-payment';
<AuthModal
isOpen={showAuthModal}
lnurl={lnurl}
onClose={() => setShowAuthModal(false)}
onSuccess={() => console.log('Login successful!')}
onError={(error) => console.error('Login failed:', error)}
/>
```
#### Props
| Prop | Type | Description |
|------|------|-------------|
| `isOpen` | `boolean` | Whether modal is open |
| `lnurl` | `string \| null` | LNURL for authentication |
| `onClose` | `() => void` | Close modal callback |
| `onSuccess` | `() => void` | Success callback |
| `onError` | `(error: string) => void` | Error callback |
### `BTCPayPaymentModal`
Modal component for BTCPay Server payments.
```typescript
import { BTCPayPaymentModal } from 'lightning-auth-and-payment';
<BTCPayPaymentModal
isOpen={showPaymentModal}
amount={1000}
description="Premium subscription"
metadata={{ plan: 'premium' }}
onClose={() => setShowPaymentModal(false)}
onPaymentSuccess={() => console.log('Payment successful!')}
onPaymentError={(error) => console.error('Payment failed:', error)}
autoCloseDelay={3000}
successMessage="Payment confirmed! Your subscription is active."
/>
```
#### Props
| Prop | Type | Description |
|------|------|-------------|
| `isOpen` | `boolean` | Whether modal is open |
| `amount` | `number` | Payment amount in satoshis |
| `description` | `string` | Payment description |
| `metadata` | `Record<string, any>` | Additional metadata |
| `onClose` | `() => void` | Close modal callback |
| `onPaymentSuccess` | `() => void` | Payment success callback |
| `onPaymentError` | `(error: string) => void` | Payment error callback |
| `autoCloseDelay` | `number` | Auto-close delay in ms (default: 3000) |
| `successMessage` | `string` | Success message to display |
## Theme System
### ThemeProvider
Provides theme context for the entire application.
```tsx
import { ThemeProvider } from 'lightning-auth-and-payment';
function App() {
return (
<ThemeProvider defaultTheme="system" storageKey="lightning-theme">
<YourApp />
</ThemeProvider>
);
}
```
### useTheme
Hook to access and modify the current theme.
```tsx
import { useTheme } from 'lightning-auth-and-payment';
function ThemeButton() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
Toggle theme
</button>
);
}
```
### useThemeMode
Hook to get the resolved theme mode (light/dark).
```tsx
import { useThemeMode } from 'lightning-auth-and-payment';
function ThemedComponent() {
const themeMode = useThemeMode(); // 'light' | 'dark'
return (
<div className={themeMode === 'dark' ? 'bg-gray-900' : 'bg-white'}>
Content
</div>
);
}
```
### useThemeClass
Hook to get theme-aware CSS classes.
```tsx
import { useThemeClass } from 'lightning-auth-and-payment';
function ThemedButton() {
const buttonClass = useThemeClass({
light: 'bg-orange-500 text-white',
dark: 'bg-orange-600 text-white'
});
return <button className={buttonClass}>Themed Button</button>;
}
```
## Context Providers
### `LightningProvider`
React context provider for Lightning authentication and payments.
```typescript
import { LightningProvider } from 'lightning-auth-and-payment';
function App() {
return (
<LightningProvider
sessionSecret="your-super-secret-session-key"
cookieName="lightning-session"
cookieDomain="localhost"
autoCheck={true}
>
<YourApp />
</LightningProvider>
);
}
```
#### Props
| Prop | Type | Description |
|------|------|-------------|
| `sessionSecret` | `string` | Secret for JWT signing |
| `cookieName` | `string` | Session cookie name |
| `cookieDomain` | `string` | Cookie domain |
| `autoCheck` | `boolean` | Auto-check authentication on mount |
## Database Adapters
### `PrismaDatabaseAdapter`
Prisma implementation of the DatabaseAdapter interface.
```typescript
import { PrismaDatabaseAdapter } from 'lightning-auth-and-payment';
const adapter = new PrismaDatabaseAdapter(prismaClient);
```
#### Constructor
| Parameter | Type | Description |
|-----------|------|-------------|
| `prismaClient` | `PrismaClientLike` | Prisma client instance |
#### Methods
| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `createUser` | `data: CreateUserData` | `Promise<User>` | Create a new user |
| `findUserById` | `id: string` | `Promise<User \| null>` | Find user by ID |
| `findUserByLnPubkey` | `lnPubkey: string` | `Promise<User \| null>` | Find user by Lightning pubkey |
| `updateUser` | `id: string, data: UpdateUserData` | `Promise<User>` | Update user |
| `createInvoice` | `data: CreateInvoiceData` | `Promise<Invoice>` | Create invoice |
| `findInvoiceById` | `id: string` | `Promise<Invoice \| null>` | Find invoice by ID |
| `updateInvoice` | `id: string, data: UpdateInvoiceData` | `Promise<Invoice>` | Update invoice |
| `findFirstUser` | `where: UserWhereInput` | `Promise<User \| null>` | Find first user matching criteria |
| `findFirstInvoice` | `where: InvoiceWhereInput` | `Promise<Invoice \| null>` | Find first invoice matching criteria |
## Payment Utilities
### `handleBTCPayInvoiceCreation`
Creates a BTCPay Server invoice.
```typescript
import { handleBTCPayInvoiceCreation } from 'lightning-auth-and-payment';
const result = await handleBTCPayInvoiceCreation({
request,
databaseAdapter,
btcpayConfig: {
host: 'https://your-btcpay-server.com',
storeId: 'your-store-id',
apiKey: 'your-api-key'
}
});
```
#### Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `request` | `NextRequest` | Next.js request object |
| `databaseAdapter` | `DatabaseAdapter` | Database adapter instance |
| `btcpayConfig` | `BTCPayConfig` | BTCPay Server configuration |
#### Returns
```typescript
{
invoiceId: string;
paymentRequest: string;
amount: number;
status: string;
expiresAt: Date;
}
```
### `handleBTCPayInvoiceStatus`
Checks the status of a BTCPay Server invoice.
```typescript
import { handleBTCPayInvoiceStatus } from 'lightning-auth-and-payment';
const result = await handleBTCPayInvoiceStatus({
invoiceId,
databaseAdapter,
btcpayConfig
});
```
#### Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `invoiceId` | `string` | Invoice ID to check |
| `databaseAdapter` | `DatabaseAdapter` | Database adapter instance |
| `btcpayConfig` | `BTCPayConfig` | BTCPay Server configuration |
#### Returns
```typescript
{
status: string;
settledAt?: Date;
amount: number;
}
```
### `handleBTCPayWebhookRequest`
Handles BTCPay Server webhook requests.
```typescript
import { handleBTCPayWebhookRequest } from 'lightning-auth-and-payment';
const result = await handleBTCPayWebhookRequest({
request,
databaseAdapter,
btcpayConfig,
webhookSecret: 'your-webhook-secret'
});
```
## Authentication Utilities
### `handleLnurlRequest`
Generates LNURL for Lightning authentication.
```typescript
import { handleLnurlRequest } from 'lightning-auth-and-payment';
const result = await handleLnurlRequest({
request,
databaseAdapter
});
```
#### Returns
```typescript
{
lnurl: string;
k1: string;
}
```
### `handleAuthCallbackRequest`
Handles Lightning authentication callback.
```typescript
import { handleAuthCallbackRequest } from 'lightning-auth-and-payment';
const result = await handleAuthCallbackRequest({
request,
databaseAdapter,
sessionSecret: 'your-session-secret'
});
```
### `handleAuthStatusRequest`
Checks authentication status.
```typescript
import { handleAuthStatusRequest } from 'lightning-auth-and-payment';
const result = await handleAuthStatusRequest({
request,
databaseAdapter
});
```
#### Returns
```typescript
{
authorized: boolean;
user?: User;
}
```
### `handleUserRequest`
Gets current user information.
```typescript
import { handleUserRequest } from 'lightning-auth-and-payment';
const result = await handleUserRequest({
request,
databaseAdapter,
sessionSecret: 'your-session-secret'
});
```
### `handleLogoutRequest`
Handles user logout.
```typescript
import { handleLogoutRequest } from 'lightning-auth-and-payment';
const result = await handleLogoutRequest({
request,
sessionSecret: 'your-session-secret',
cookieDomain: 'localhost'
});
```
## CORS Utilities
### `getCorsHeaders()`
Returns basic CORS headers.
```typescript
import { getCorsHeaders } from 'lightning-auth-and-payment';
const headers = getCorsHeaders();
// Returns: { 'Access-Control-Allow-Origin': '*', ... }
```
### `getAuthCorsHeaders()`
Returns CORS headers for authentication endpoints.
```typescript
import { getAuthCorsHeaders } from 'lightning-auth-and-payment';
const headers = getAuthCorsHeaders();
// Includes credentials support
```
### `getBTCPayCorsHeaders()`
Returns CORS headers for BTCPay endpoints.
```typescript
import { getBTCPayCorsHeaders } from 'lightning-auth-and-payment';
const headers = getBTCPayCorsHeaders();
// Includes credentials support
```
## Zero-Config Utilities
### `detectNextJSProject(projectRoot: string)`
Detects Next.js project configuration and capabilities.
```typescript
import { detectNextJSProject } from 'lightning-auth-and-payment';
const projectInfo = detectNextJSProject('/path/to/project');
```
#### Returns
```typescript
{
hasPrisma: boolean;
hasDatabase: boolean;
hasBTCPay: boolean;
isDevelopment: boolean;
hasEnvironmentFile: boolean;
hasPackageJson: boolean;
hasNextConfig: boolean;
projectRoot: string;
databaseType: 'prisma' | 'memory' | 'custom';
storageType: 'database' | 'memory' | 'hybrid';
btcpayEnabled: boolean;
}
```
### `generateSmartDefaults(projectInfo: NextJSProjectInfo)`
Generates smart defaults based on project detection.
```typescript
import { generateSmartDefaults } from 'lightning-auth-and-payment';
const defaults = generateSmartDefaults(projectInfo);
```
### `applyZeroConfig(projectRoot: string, userConfig?: Partial<SmartConfig>)`
Applies zero-config setup to a Next.js project.
```typescript
import { applyZeroConfig } from 'lightning-auth-and-payment';
const { config, projectInfo, needsSetup } = applyZeroConfig('/path/to/project');
```
## Next.js Plugin
### `withLightning(config?: LightningPluginConfig)`
Next.js plugin for complete Lightning Network integration (authentication + payments).
```typescript
import { withLightning } from 'lightning-auth-and-payment/nextjs';
// Zero-config usage
export default withLightning()(nextConfig);
// Custom configuration
export default withLightning({
database: 'prisma',
btcpay: true,
development: true
})(nextConfig);
```
### `withLightningAuth(config?: Partial<LightningPluginConfig>)`
Next.js plugin for Lightning authentication only (no payments).
```typescript
import { withLightningAuth } from 'lightning-auth-and-payment/nextjs';
// Zero-config usage
export default withLightningAuth()(nextConfig);
// Custom configuration
export default withLightningAuth({
database: 'prisma',
authPrefix: '/api/auth',
userPrefix: '/api/user'
})(nextConfig);
```
**Generated Routes:**
- `/api/auth/lnurl` - LNURL generation
- `/api/auth/callback` - Authentication callback
- `/api/auth/status` - Authentication status
- `/api/auth/logout` - User logout
- `/api/user` - User data
### `withLightningPayment(config?: Partial<LightningPluginConfig>)`
Next.js plugin for Lightning payments only (no authentication).
```typescript
import { withLightningPayment } from 'lightning-auth-and-payment/nextjs';
// Zero-config usage
export default withLightningPayment()(nextConfig);
// Custom configuration
export default withLightningPayment({
database: 'prisma',
btcpay: true,
paymentPrefix: '/api/payment',
webhookPrefix: '/api/webhooks'
})(nextConfig);
```
**Generated Routes:**
- `/api/payment/create-invoice` - Invoice creation
- `/api/payment/status` - Payment status
- `/api/webhooks/btcpay` - BTCPay webhooks
#### Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `autoGenerateRoutes` | `boolean` | `true` | Auto-generate API routes |
| `database` | `'prisma' \| 'memory' \| 'custom'` | `'memory'` | Database type |
| `storage` | `'database' \| 'memory' \| 'hybrid'` | `'memory'` | Storage type |
| `btcpay` | `boolean` | `false` | Enable BTCPay Server |
| `development` | `boolean` | `true` | Enable development features |
| `authPrefix` | `string` | `'/api/auth'` | Authentication route prefix |
| `paymentPrefix` | `string` | `'/api/payment'` | Payment route prefix |
| `userPrefix` | `string` | `'/api/user'` | User route prefix |
| `webhookPrefix` | `string` | `'/api/webhooks'` | Webhook route prefix |
## Development Server
### `lightning-dev-server`
CLI tool for running HTTPS development server.
```bash
npx lightning-dev-server
```
#### Options
| Option | Description |
|--------|-------------|
| `--port` | HTTPS port (default: 3443) |
| `--next-port` | Next.js port (default: 3000) |
| `--cert-dir` | Certificate directory (default: ./certificates) |
## Types and Interfaces
### `User`
```typescript
interface User {
id: string;
lnPubkey: string | null;
createdAt: string;
orderCount: number;
}
```
### `Invoice`
```typescript
interface Invoice {
id: string;
amount: number;
status: string;
paymentRequest?: string;
settledAt?: Date;
metadata?: string;
user: User;
}
```
### `CreatePaymentParams`
```typescript
interface CreatePaymentParams {
amount: number;
description?: string;
metadata?: Record<string, any>;
}
```
### `DatabaseAdapter`
```typescript
interface DatabaseAdapter {
createUser(data: CreateUserData): Promise<User>;
findUserById(id: string): Promise<User | null>;
findUserByLnPubkey(lnPubkey: string): Promise<User | null>;
updateUser(id: string, data: UpdateUserData): Promise<User>;
createInvoice(data: CreateInvoiceData): Promise<Invoice>;
findInvoiceById(id: string): Promise<Invoice | null>;
updateInvoice(id: string, data: UpdateInvoiceData): Promise<Invoice>;
findFirstUser(where: UserWhereInput): Promise<User | null>;
findFirstInvoice(where: InvoiceWhereInput): Promise<Invoice | null>;
}
```
### `BTCPayConfig`
```typescript
interface BTCPayConfig {
host: string;
storeId: string;
apiKey: string;
webhookSecret?: string;
}
```
### `LightningPluginConfig`
```typescript
interface LightningPluginConfig {
autoGenerateRoutes?: boolean;
database?: 'prisma' | 'memory' | 'custom';
storage?: 'database' | 'memory' | 'hybrid';
btcpay?: boolean;
development?: boolean;
authPrefix?: string;
paymentPrefix?: string;
userPrefix?: string;
webhookPrefix?: string;
dbConfig?: DatabaseConfig;
btcpayConfig?: BTCPayConfig;
devConfig?: DevelopmentConfig;
}
```
## Error Handling
All functions that can fail will throw errors or return error objects. Common error types:
- `AuthenticationError`: Authentication-related errors
- `PaymentError`: Payment processing errors
- `DatabaseError`: Database operation errors
- `ConfigurationError`: Configuration-related errors
## Examples
### Complete Authentication Flow
```typescript
import { useLightningAuth, AuthModal } from 'lightning-auth-and-payment';
function App() {
const {
isAuthenticated,
handleLogin,
showAuthModal,
setShowAuthModal,
lnurl,
loginError
} = useLightningAuth();
return (
<div>
{isAuthenticated ? (
<div>Welcome!</div>
) : (
<button onClick={handleLogin}>
Login with Lightning
</button>
)}
<AuthModal
isOpen={showAuthModal}
lnurl={lnurl}
onClose={() => setShowAuthModal(false)}
onSuccess={() => console.log('Login successful!')}
onError={(error) => console.error('Login failed:', error)}
/>
</div>
);
}
```
### Complete Payment Flow
```typescript
import { useBTCPayPayment, BTCPayPaymentModal } from 'lightning-auth-and-payment';
function PaymentPage() {
const { createInvoice, paymentState } = useBTCPayPayment();
const [showModal, setShowModal] = useState(false);
const handlePayment = async () => {
await createInvoice({
amount: 1000,
description: 'Premium subscription',
metadata: { plan: 'premium' }
});
setShowModal(true);
};
return (
<div>
<button onClick={handlePayment}>
Pay 1000 sats
</button>
<BTCPayPaymentModal
isOpen={showModal}
amount={1000}
description="Premium subscription"
onClose={() => setShowModal(false)}
onPaymentSuccess={() => console.log('Payment successful!')}
/>
</div>
);
}
```
### Zero-Config Next.js Setup
```javascript
// next.config.js
import { withLightning } from 'lightning-auth-and-payment/nextjs';
/** @type {import('next').NextConfig} */
const nextConfig = {
// your existing config
};
// Zero-config: Auto-detects everything!
export default withLightning()(nextConfig);
```
This API reference provides comprehensive documentation for all public methods, properties, classes, and interfaces in the `lightning-auth-and-payment` library. For more examples and detailed usage guides, see the [README.md](./README.md) and [QUICK_START.md](./QUICK_START.md) files.