kotanipay-sdk
Version:
Official Kotani Pay SDK for Node.js and Browser
325 lines (254 loc) • 7.58 kB
Markdown
# KotaniPay TypeScript/JavaScript SDK
Official TypeScript/JavaScript SDK for the KotaniPay API. Simplify crypto-to-mobile money transactions across Africa.
## Features
- 🚀 **TypeScript Support** - Full type definitions included
- 🔐 **Authentication Management** - Magic link login flow
- 📱 **Mobile Money** - Create and manage mobile money customers
- 🏢 **Integrator Management** - Create and manage integrator accounts
- 🛡️ **Error Handling** - Comprehensive error types and validation
- 🌍 **Multi-Environment** - Sandbox and production support
## Installation
```bash
npm install kotanipay-sdk
```
```bash
yarn add kotanipay-sdk
```
## Quick Start
```typescript
import { KotaniPayClient } from 'kotanipay-sdk';
// Initialize client
const client = new KotaniPayClient({
environment: 'sandbox' // or 'production'
});
// Create integrator (no auth required)
const integrator = await client.integrator.create({
organization: 'My Company',
product_name: 'My Product',
first_name: 'John',
last_name: 'Doe',
email: 'john.com',
phone: '+1234567890',
country_code: 'US'
});
// Start authentication flow
await client.auth.login('john.com');
// User receives magic link in email...
// After user clicks magic link, set session
client.initializeWithSession(sessionData);
// Generate API key
const apiKey = await client.auth.generateApiKey();
client.initializeWithApiKey(apiKey.key);
// Create mobile money customer
const customer = await client.mobileMoney.createCustomer({
phone_number: '+254700123456',
country_code: 'KEN',
network: 'MPESA',
account_name: 'John Doe'
});
```
## Authentication Flow
KotaniPay uses a magic link authentication system:
1. **Send Magic Link**: Call `client.auth.login(email)`
2. **User Action**: User clicks verification link in email
3. **Get Session Data**: Copy JSON response from browser
4. **Initialize Session**: Call `client.initializeWithSession(sessionData)`
5. **Generate API Key**: Call `client.auth.generateApiKey()`
6. **Ready**: Use authenticated endpoints
### Example Session Data
When user clicks the magic link, they'll see JSON like this:
```json
{
"success": true,
"message": "ok",
"data": {
"user_id": "66262fda6c7024bcf925636f",
"session_id": "8d1d3429b8075d53993c58a3a1b3bcec",
"token_id": "PrsCEicJ",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
```
Pass the `data` object to `initializeWithSession()`.
## API Reference
### Client Initialization
```typescript
const client = new KotaniPayClient({
environment: 'sandbox' | 'production',
timeout?: number,
apiKey?: string // Optional: for direct API key usage
});
```
### Integrator Management
```typescript
// Create integrator (no auth required)
await client.integrator.create({
organization: string,
product_name: string,
first_name: string,
last_name: string,
email: string,
phone: string,
country_code: string
});
```
### Authentication
```typescript
// Send magic link
await client.auth.login(email);
// Set session after magic link click
client.initializeWithSession(sessionData);
// Generate API key
await client.auth.generateApiKey();
// Set API key directly
client.initializeWithApiKey(apiKey);
// Check authentication status
client.isAuthenticated();
```
### Mobile Money
```typescript
// Create customer (requires auth)
await client.mobileMoney.createCustomer({
phone_number: string,
country_code: 'GHA' | 'KEN' | 'ZAC' | 'CIV' | ...,
network?: 'MPESA' | 'MTN' | 'AIRTEL' | ...,
account_name?: string
});
// Get all customers (requires auth)
await client.mobileMoney.getAllCustomers();
## Supported Countries & Networks
### Countries
- 🇬🇭 Ghana (GHA)
- 🇰🇪 Kenya (KEN)
- 🇿🇦 South Africa (ZAC)
- 🇨🇮 Ivory Coast (CIV)
- 🇿🇲 Zambia (ZMB)
- And more...
### Networks
- M-Pesa
- MTN Mobile Money
- Airtel Money
- Vodafone Cash
- Tigo Pesa
- Orange Money
## Error Handling
```typescript
import { ValidationError, AuthenticationError, KotaniPayError } from '@kotanipay/sdk';
try {
await client.mobileMoney.createCustomer(customerData);
} catch (error) {
if (error instanceof ValidationError) {
console.log('Validation error:', error.message);
} else if (error instanceof AuthenticationError) {
console.log('Auth error:', error.message);
} else if (error instanceof KotaniPayError) {
console.log('API error:', error.message, error.statusCode);
}
}
```
## Environment Variables
For server-side usage, you can set:
```bash
KOTANIPAY_API_KEY=your-api-key
KOTANIPAY_ENVIRONMENT=sandbox
```
## Examples
### React Integration
```typescript
import React, { useState } from 'react';
import { KotaniPayClient } from 'kotanipay-sdk';
function PaymentComponent() {
const [client] = useState(() => new KotaniPayClient({
environment: 'sandbox'
}));
const [authStatus, setAuthStatus] = useState('idle');
const handleLogin = async (email: string) => {
try {
setAuthStatus('sending');
await client.auth.login(email);
setAuthStatus('waiting'); // Wait for user to click magic link
} catch (error) {
setAuthStatus('error');
}
};
const handleSessionData = async (sessionData: any) => {
try {
client.initializeWithSession(sessionData);
const apiKey = await client.auth.generateApiKey();
client.initializeWithApiKey(apiKey.key);
setAuthStatus('authenticated');
} catch (error) {
setAuthStatus('error');
}
};
return (
<div>
{authStatus === 'idle' && (
<button onClick={() => handleLogin('user.com')}>
Login with Email
</button>
)}
{authStatus === 'waiting' && (
<div>
<p>Magic link sent! Check your email.</p>
<textarea
placeholder="Paste session data here..."
onChange={(e) => {
try {
const data = JSON.parse(e.target.value);
handleSessionData(data.data);
} catch {}
}}
/>
</div>
)}
{authStatus === 'authenticated' && (
<p>Ready to make payments!</p>
)}
</div>
);
}
```
### Node.js Integration
```typescript
import { KotaniPayClient } from 'kotanipay-sdk';
const client = new KotaniPayClient({
environment: 'sandbox',
apiKey: process.env.KOTANIPAY_API_KEY // If you already have an API key
});
async function processPayment() {
try {
// Create customer
const customer = await client.mobileMoney.createCustomer({
phone_number: '+254700123456',
country_code: 'KEN',
network: 'MPESA'
});
console.log('Customer created:', customer);
return customer;
} catch (error) {
console.error('Payment failed:', error);
throw error;
}
}
```
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Support
- 📧 **Email**: support.com
- 📖 **Documentation**: https://docs.kotanipay.com
- 🐛 **Issues**: https://github.com/kotanipay/sdk-typescript/issues
## Changelog
### v1.0.0
- Initial release
- Magic link authentication
- Integrator management
- Mobile money customer management
- TypeScript support