npm package: @paymentus/auth
Description: Paymentus Auth API Client for Rest APIs
Author: anasingh@paymentus.com
Latest version: 1.0.7

# @paymentus/auth

Authentication client for Paymentus API services. This package handles JWT token management and authentication for Paymentus API endpoints.

## Installation

```bash
npm install @paymentus/auth
```

## Usage

### Basic Usage

```typescript
import { Auth } from '@paymentus/auth';

// Initialize the auth client
const authClient = new Auth({
  baseUrl: 'https://developer.paymentus.io',
  kid: '001',
  preSharedKey: 'your-pre-shared-key',
  scope: ['xotp'],
  tla: 'ABC'
});

// Fetch a token
const token = await authClient.fetchToken();
```

### Configuration Options

The `Auth` constructor accepts the following configuration:

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `baseUrl` | string | Yes | Base URL for the Paymentus API, it varies based on the environment biller is in |
| `preSharedKey` | string | Yes | Pre-shared key for JWT signing |
| `scope` | string[] | Yes | Array of API scopes (e.g., ['xotp', 'xotp:profile']) |
| `tla` | string | Yes | Three-letter acronym for your application |
| `aud` | string | No | Audience claim for the JWT (optional) |
| `timeout` | number | No | Request timeout in milliseconds (default: 5000) |
| `userLogin` | string | No | User login identifier |
| `pmToken` | string[] | No | Payment method tokens |
| `paymentsData` | PaymentData[] | No | Payment data for the transaction |
| `pixels` | PixelType[] | No | Array of pixels to automatically add required scopes |

### Available Scopes

The SDK supports the following scopes:

- `xotp` - Basic XOTP functionality
- `xotp:profile` - Profile management
- `xotp:profile:read` - Read profile data
- `xotp:profile:create` - Create profiles
- `xotp:profile:update` - Update profiles
- `xotp:profile:delete` - Delete profiles
- `xotp:listProfiles` - List profiles
- `xotp:payment` - Payment processing
- `xotp:autopay` - Autopay functionality
- `xotp:autopay:delete` - Delete autopay settings
- `xotp:accounts` - Account management
- `xotp:listAccounts` - List accounts
- `paybotus` - Paybotus functionality

### Pixel Integration

The SDK provides automatic scope mapping for Paymentus pixels. When you specify pixels in the configuration, the SDK automatically adds the required scopes and validates required claims:

```typescript
const authClient = new Auth({
  baseUrl: 'https://secure1.paymentus.com',
  preSharedKey: 'your-pre-shared-key',
  tla: 'ABC',
  pixels: ['user-checkout-pixel'],
  aud: 'WEB_SDK',
  // Required claims for user-checkout-pixel:
  userLogin: 'user@example.com',
  paymentsData: [{
    accountNumber: '123456',
    convFeeState: 'NY',
    convFeeCountry: 'US'
  }]
});
```

Available pixels and their requirements:

- `tokenization-pixel`: 
  - Claims: None required

- `list-wallets-pixel`: 
  - Claims: `userLogin` required

- `user-checkout-pixel`: 
  - Claims: `userLogin` and `paymentsData` required, `pmTokens` optional

- `guest-checkout-pixel`: 
  - Claims: `paymentsData` required

- `user-autopay-pixel`: 
  - Claims: `userLogin` and `paymentsData` required, `pmTokens` optional

- `list-autopay-pixel`: 
  - Claims: `userLogin` required and `paymentsData` optional

### Error Handling

The package throws specific error types for different scenarios:

- `ConfigurationError`: Thrown when configuration is invalid (e.g., missing required claims for pixels)
- `TokenError`: Thrown when token validation fails
- `NetworkError`: Thrown when API requests fail

Example error handling:

```typescript
try {
  const token = await authClient.fetchToken();
} catch (error) {
  if (error instanceof ConfigurationError) {
    console.error('Invalid configuration:', error.message);
  } else if (error instanceof TokenError) {
    console.error('Token error:', error.message);
  } else if (error instanceof NetworkError) {
    console.error('Network error:', error.message);
  }
}
```

### Advanced Usage

#### Using Multiple Scopes

```typescript
const authClient = new Auth({
  baseUrl: 'https://secure1.paymentus.com',
  preSharedKey: 'your-pre-shared-key',
  scope: ['xotp', 'xotp:profile', 'xotp:payment'],
  tla: 'TST',
  aud: 'WEB_SDK'
});
```

#### Using Optional Fields

```typescript
const authClient = new Auth({
  baseUrl: 'https://developer.paymentus.io',
  preSharedKey: 'your-pre-shared-key',
  scope: ['xotp'],
  tla: 'TST',
  aud: 'WEB_SDK',
  userLogin: 'user@example.com',
  pmToken: ['token1', 'token2'],
  paymentsData: [{
    accountNumber: '123456',
    convFeeState: 'NY',
    convFeeCountry: 'US'
  }]
});
```

## API Reference

### Auth Class

#### Constructor

```typescript
new Auth(config: AuthConfig)
```

Creates a new Auth client instance with the provided configuration.

#### Methods

##### fetchToken()

```typescript
fetchToken(): Promise<string>
```

Fetches a new JWT token from the Paymentus API. Returns a Promise that resolves to the token string.

##### getCurrentToken()

```typescript
getCurrentToken(): string | null
```

Returns the current token if available, or null if no token has been fetched.

##### isTokenExpired()

```typescript
isTokenExpired(): boolean
```

Returns true if the current token is expired or no token is available.

## Development

### Building

```bash
npm run build
```

### Testing

```bash
npm test
```

### Linting

```bash
npm run lint
```

## Disclaimer

These SDKs are intended for use with the URLs and keys that are provided to you for your company by Paymentus. If you do not have this information, please reach out to your implementation or account manager. If you are interested in learning more about the solutions that Paymentus provides, you can visit our website at paymentus.com. You can request access to our complete documentation at developer.paymentus.io. If you are currently not a customer or partner and would like to learn more about the solution and how you can get started with Paymentus, please contact us at https://www.paymentus.com/lets-talk/.

## License

MIT