npm package: @jutech-devs/sms-sdk
Description: Official JavaScript/TypeScript SDK for Jutech SMS - A comprehensive SMS messaging platform with usage tracking
Author: Jutech Devs
Latest version: 1.4.0

# Jutech SMS SDK

Official JavaScript/TypeScript SDK for Jutech SMS - A comprehensive SMS messaging platform with usage tracking and analytics.

## Features

- 🚀 Send single and bulk SMS messages
- 📊 Real-time usage tracking and analytics
- 🔐 Secure API key authentication
- 📱 Webhook support for delivery status
- 💳 Credit-based billing system
- 🛡️ Built-in error handling and retry logic
- 📝 Full TypeScript support
- 🌐 Works in Node.js and browsers

## Installation

```bash
npm install @jutech-devs/sms-sdk
```

## Quick Start

```typescript
import { JutechSmsClient } from '@jutech-devs/sms-sdk';

// Initialize the client
const smsClient = new JutechSmsClient({
  apiKey: 'your-api-key-here',
  debug: true // Optional: enable debug logging
});

// Send a single SMS
const response = await smsClient.sendSms({
  text: 'Hello from Jutech SMS!',
  destinations: ['+233123456789', '+233987654321'],
  sender: 'YourBrand', // Optional
  projectId: 'your-project-id' // Optional
});

console.log(response);
```

## Configuration

### JutechSmsConfig

```typescript
interface JutechSmsConfig {
  apiKey: string;        // Your API key (required)
  baseURL?: string;      // Custom base URL (optional)
  timeout?: number;      // Request timeout in ms (default: 30000)
  retries?: number;      // Number of retries (default: 3)
  debug?: boolean;       // Enable debug logging (default: false)
}
```

## API Reference

### Send SMS

Send a single SMS message to multiple recipients:

```typescript
const response = await smsClient.sendSms({
  text: 'Your message here',
  destinations: ['+233123456789'],
  sender: 'YourBrand', // Optional
  projectId: 'project-123' // Optional
});
```

### Send Bulk SMS

Send multiple SMS messages:

```typescript
const messages = [
  {
    text: 'Message 1',
    destinations: ['+233123456789'],
    sender: 'Brand1'
  },
  {
    text: 'Message 2',
    destinations: ['+233987654321'],
    sender: 'Brand2'
  }
];

const responses = await smsClient.sendBulkSms(messages);
```

### Get Usage Statistics

Track your SMS usage and credits:

```typescript
const stats = await smsClient.getUsageStats();
console.log(stats);
// {
//   totalCredits: 1000,
//   usedCredits: 250,
//   availableCredits: 750,
//   messagesSent: 125,
//   messagesThisMonth: 50,
//   lastUsed: "2024-01-15T10:30:00Z"
// }
```

### Get Project Information

Get details about your SMS project:

```typescript
const projectInfo = await smsClient.getProjectInfo();
console.log(projectInfo);
// {
//   id: "project-123",
//   name: "My SMS Project",
//   status: "active",
//   owner: {
//     name: "John Doe",
//     email: "john@example.com"
//   },
//   usage: { ... }
// }
```

### Validate API Key

Check if your API key is valid:

```typescript
const isValid = await smsClient.validateApiKey();
console.log(isValid); // true or false
```

## Webhook Support

Handle delivery status updates:

```typescript
import { JutechSmsClient } from '@jutech-devs/sms-sdk';

// Verify webhook signature
const isValid = JutechSmsClient.verifyWebhook(
  webhookPayload,
  signature,
  'your-webhook-secret'
);

if (isValid) {
  // Process webhook payload
  console.log('Message status:', webhookPayload.status);
}
```

## Error Handling

The SDK provides comprehensive error handling:

```typescript
import { JutechSmsError } from '@jutech-devs/sms-sdk';

try {
  await smsClient.sendSms({
    text: 'Hello World',
    destinations: ['+233123456789']
  });
} catch (error) {
  if (error instanceof JutechSmsError) {
    console.error('SMS Error:', {
      message: error.message,
      statusCode: error.statusCode,
      code: error.code
    });
    
    // Check specific error types
    if (JutechSmsError.isAuthenticationError(error)) {
      console.log('Invalid API key');
    } else if (JutechSmsError.isRateLimitError(error)) {
      console.log('Rate limit exceeded');
    }
  }
}
```

## TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

```typescript
import { 
  JutechSmsClient, 
  SmsMessage, 
  SmsResponse, 
  UsageStats,
  ProjectInfo 
} from '@jutech-devs/sms-sdk';

const client = new JutechSmsClient({ apiKey: 'your-key' });

// All methods are fully typed
const message: SmsMessage = {
  text: 'Hello',
  destinations: ['+233123456789']
};

const response: SmsResponse = await client.sendSms(message);
```

## Examples

### Basic SMS Sending

```typescript
import { JutechSmsClient } from '@jutech-devs/sms-sdk';

const client = new JutechSmsClient({
  apiKey: process.env.JUTECH_SMS_API_KEY!
});

async function sendWelcomeMessage(phoneNumber: string, name: string) {
  try {
    const response = await client.sendSms({
      text: `Welcome ${name}! Thanks for joining our platform.`,
      destinations: [phoneNumber],
      sender: 'MyApp'
    });
    
    console.log(`SMS sent successfully. Message ID: ${response.messageId}`);
    console.log(`Credits used: ${response.creditsUsed}`);
  } catch (error) {
    console.error('Failed to send SMS:', error);
  }
}
```

### Bulk Notifications

```typescript
async function sendBulkNotifications(users: Array<{phone: string, name: string}>) {
  const messages = users.map(user => ({
    text: `Hi ${user.name}, your order has been confirmed!`,
    destinations: [user.phone],
    sender: 'OrderApp'
  }));
  
  const responses = await client.sendBulkSms(messages);
  
  const successful = responses.filter(r => r.success).length;
  const failed = responses.filter(r => !r.success).length;
  
  console.log(`Sent: ${successful}, Failed: ${failed}`);
}
```

### Usage Monitoring

```typescript
async function checkUsageAndAlert() {
  const stats = await client.getUsageStats();
  
  const usagePercentage = (stats.usedCredits / stats.totalCredits) * 100;
  
  if (usagePercentage > 80) {
    console.warn(`Warning: ${usagePercentage.toFixed(1)}% of credits used`);
    // Send alert to admin
  }
  
  console.log(`Available credits: ${stats.availableCredits}`);
}
```

## Environment Variables

For security, store your API key in environment variables:

```bash
# .env
JUTECH_SMS_API_KEY=your-api-key-here
JUTECH_SMS_WEBHOOK_SECRET=your-webhook-secret
```

```typescript
const client = new JutechSmsClient({
  apiKey: process.env.JUTECH_SMS_API_KEY!,
  debug: process.env.NODE_ENV === 'development'
});
```

## Rate Limits

The API has rate limits to ensure fair usage:

- **Free tier**: 100 messages per hour
- **Pro tier**: 1,000 messages per hour
- **Enterprise**: Custom limits

Rate limit information is included in error responses when limits are exceeded.

## Support

- 📧 Email: support@jutechdevs.com
- 📚 Documentation: https://docs.jutechdevs.com
- 🐛 Issues: https://github.com/jutech-devs/sms-sdk/issues

## License

MIT License - see LICENSE file for details.