@tagadapay/core-js
Version:
Core JavaScript SDK for Tagada Pay with standalone and React implementations
351 lines (273 loc) • 8.26 kB
Markdown
# @tagadapay/core-js
A standalone JavaScript SDK for Tagada Pay with clean architecture separating core functionality from React-specific implementations.
## Architecture
The SDK is designed with two main namespaces:
- **Core** (`@tagadapay/core-js`): Standalone payment functionality without React dependencies
- **React** (`@tagadapay/core-js/react`): React hooks that use the core functionality
## Installation
```bash
npm install @tagadapay/core-js
```
## Usage
### Core (Standalone)
Use the core functionality without React:
```typescript
import { PaymentInstruments, ApiService } from '@tagadapay/core-js';
// Implement your API service
const apiService: ApiService = {
async fetch(endpoint, options) {
// Your API implementation
const response = await fetch(`https://your-api.com${endpoint}`, {
method: options?.method || 'GET',
headers: {
'Content-Type': 'application/json',
...options?.headers,
},
body: options?.body ? JSON.stringify(options.body) : undefined,
});
return response.json();
},
};
// Create payment instruments instance
const paymentInstruments = new PaymentInstruments({
environment: 'development',
apiService,
});
// Initialize and use
await paymentInstruments.initialize();
const cardData = {
cardNumber: '4111111111111111',
expiryDate: '12/25',
cvc: '123',
cardholderName: 'John Doe',
};
// High-level: Create payment instrument
const paymentInstrument = await paymentInstruments.createCardPaymentInstrument(cardData);
// Low-level: Just tokenize the card
const cardToken = await paymentInstruments.tokenizeCard(cardData);
```
### React Hooks
#### Payment Instruments Hook
Use the React hook for creating payment instruments:
```typescript
import { usePaymentInstruments } from '@tagadapay/core-js/react';
function PaymentForm() {
const {
createCardPaymentInstrument,
createApplePayPaymentInstrument,
isLoading,
error,
clearError,
} = usePaymentInstruments({
environment: 'development',
apiService: yourApiService,
autoInitialize: true, // Automatically initialize on mount
});
const handleSubmit = async (cardData) => {
try {
const paymentInstrument = await createCardPaymentInstrument(cardData);
console.log('Payment instrument created:', paymentInstrument);
} catch (error) {
console.error('Failed to create payment instrument:', error);
}
};
return (
<form onSubmit={handleSubmit}>
{error && <div className="error">{error}</div>}
{/* Your form fields */}
<button type="submit" disabled={isLoading}>
{isLoading ? 'Creating...' : 'Create Payment Method'}
</button>
</form>
);
}
```
#### Card Tokenization Hook (Low-level)
Use the tokenization hook for just tokenizing cards without creating payment instruments:
```typescript
import { useCardTokenization } from '@tagadapay/core-js/react';
function TokenizationForm() {
const {
tokenizeCard,
tokenizeApplePay,
isLoading,
error,
clearError,
} = useCardTokenization({
environment: 'development',
apiService: yourApiService,
autoInitialize: true,
});
const handleTokenize = async (cardData) => {
try {
const cardToken = await tokenizeCard(cardData);
console.log('Card tokenized:', cardToken.id);
// Use the token for your own payment processing
} catch (error) {
console.error('Failed to tokenize card:', error);
}
};
return (
<form onSubmit={handleTokenize}>
{error && <div className="error">{error}</div>}
{/* Your form fields */}
<button type="submit" disabled={isLoading}>
{isLoading ? 'Tokenizing...' : 'Tokenize Card'}
</button>
</form>
);
}
```
## API Reference
### Core Classes
#### `PaymentInstruments`
Main class for creating and managing payment instruments.
**Constructor:**
```typescript
new PaymentInstruments(config: PaymentSDKConfig & { apiService: ApiService })
```
**Methods:**
- `initialize(): Promise<void>` - Initialize BasisTheory SDK
- `tokenizeCard(cardData: CardPaymentMethod): Promise<CardTokenResponse>` - **Low-level**: Tokenize card data only
- `tokenizeApplePay(applePayToken: ApplePayToken): Promise<ApplePayTokenResponse>` - **Low-level**: Tokenize Apple Pay data only
- `createCardPaymentInstrument(cardData: CardPaymentMethod): Promise<PaymentInstrumentResponse>` - **High-level**: Create payment instrument
- `createApplePayPaymentInstrument(applePayToken: ApplePayToken): Promise<PaymentInstrumentResponse>` - **High-level**: Create Apple Pay payment instrument
- `isReady(): boolean` - Check if SDK is initialized
- `getBasisTheoryInstance(): BasisTheory | null` - Get BasisTheory instance for advanced usage
### React Hooks
#### `usePaymentInstruments(config: UsePaymentInstrumentsConfig)`
React hook that provides payment instrument functionality.
**Returns:**
```typescript
{
createCardPaymentInstrument: (cardData: CardPaymentMethod) => Promise<PaymentInstrumentResponse>;
createApplePayPaymentInstrument: (applePayToken: ApplePayToken) => Promise<PaymentInstrumentResponse>;
initialize: () => Promise<void>;
isLoading: boolean;
isInitialized: boolean;
error: string | null;
clearError: () => void;
paymentInstruments: PaymentInstruments | null;
}
```
#### `useCardTokenization(config: UseCardTokenizationConfig)`
React hook that provides low-level card tokenization functionality.
**Returns:**
```typescript
{
tokenizeCard: (cardData: CardPaymentMethod) => Promise<CardTokenResponse>;
tokenizeApplePay: (applePayToken: ApplePayToken) => Promise<ApplePayTokenResponse>;
initialize: () => Promise<void>;
isLoading: boolean;
isInitialized: boolean;
error: string | null;
clearError: () => void;
paymentInstruments: PaymentInstruments | null;
}
```
### Types
#### `CardPaymentMethod`
```typescript
interface CardPaymentMethod {
cardNumber: string;
expiryDate: string; // MM/YY format
cvc: string;
cardholderName?: string;
}
```
#### `ApplePayToken`
```typescript
interface ApplePayToken {
id: string;
type: string;
card: {
bin: string;
last4: string;
expiration_month: number;
expiration_year: number;
brand: string;
};
}
```
#### `CardTokenResponse`
```typescript
interface CardTokenResponse {
id: string;
type: string;
data: {
number?: string;
expiration_month?: number;
expiration_year?: number;
cvc?: string;
};
metadata?: Record<string, any>;
}
```
#### `ApplePayTokenResponse`
```typescript
interface ApplePayTokenResponse {
id: string;
type: string;
data: ApplePayToken;
metadata?: Record<string, any>;
}
```
#### `PaymentInstrumentResponse`
```typescript
interface PaymentInstrumentResponse {
id: string;
token: string;
type: string;
card?: {
maskedCardNumber?: string;
expirationMonth?: number;
expirationYear?: number;
brand?: string;
};
}
```
#### `ApiService`
```typescript
interface ApiService {
fetch<T = any>(
endpoint: string,
options?: {
method?: string;
body?: any;
headers?: Record<string, string>;
},
): Promise<T>;
}
```
## Environment Configuration
The SDK supports different environments:
- `production` - Uses production BasisTheory keys
- `development` - Uses sandbox BasisTheory keys
- `local` - Uses sandbox BasisTheory keys (default)
Environment variables are supported for production:
- `NEXT_PUBLIC_BASIS_THEORY_PUBLIC_API_KEY`
- `VITE_BASIS_THEORY_PUBLIC_API_KEY`
## Error Handling
The SDK throws `PaymentSDKError` instances with additional context:
```typescript
try {
await paymentInstruments.createCardPaymentInstrument(cardData);
} catch (error) {
if (error instanceof PaymentSDKError) {
console.log('Error code:', error.code);
console.log('Original error:', error.originalError);
}
}
```
## Validation
The SDK includes built-in validation for:
- Card number format (13-19 digits)
- Expiry date format (MM/YY) and expiration check
- CVC format (3-4 digits)
## Dependencies
### Core Dependencies
- `@basis-theory/basis-theory-js` - BasisTheory SDK for tokenization
### Peer Dependencies
- `react` (optional, only needed for React hooks)
## License
MIT