# 📱 WhatsApp API Integration Guide (Custom API)

## Overview

Trust Tax Advisor uses a **custom WhatsApp API** for sending OTP and alerts via WhatsApp. This is more cost-effective and reliable than third-party services like Twilio.

**API Provider:** `https://whatsapp.thechintanpatel.co.in`

---

## 🔑 API Credentials

Your API credentials:

```
API Endpoint: https://whatsapp.thechintanpatel.co.in/api/create-message
App Key: 1a68fcd1-3746-4be7-9cc0-334423e4e1d5
Auth Key: yoQ5tAx2MjtnOM2JCu8HU5IuL14DDkKesmGnCVOLRzuyVbu1qv
```

---

## ⚙️ Configuration

### Step 1: Update Environment Variables

Edit `backend/.env`:

```env
# WhatsApp Configuration
WHATSAPP_API_URL=https://whatsapp.thechintanpatel.co.in/api/create-message
WHATSAPP_APP_KEY=1a68fcd1-3746-4be7-9cc0-334423e4e1d5
WHATSAPP_AUTH_KEY=yoQ5tAx2MjtnOM2JCu8HU5IuL14DDkKesmGnCVOLRzuyVbu1qv
```

### Step 2: Verify Configuration

Backend will automatically use these credentials in `/backend/config/whatsapp.js`

**No additional setup required!** ✅

---

## 📤 API Capabilities

### 1. **Send Text Message (OTP)**
```javascript
// Automatically used in login flow
POST https://whatsapp.thechintanpatel.co.in/api/create-message

// Parameters
appkey: "1a68fcd1-3746-4be7-9cc0-334423e4e1d5"
authkey: "yoQ5tAx2MjtnOM2JCu8HU5IuL14DDkKesmGnCVOLRzuyVbu1qv"
to: "919876543210"  // Phone number with country code
message: "Your OTP is: 123456"
```

### 2. **Send Message with File**
```javascript
// Same as above, plus file parameter
file: "https://example.com/document.pdf"

// Supported formats: jpg, jpeg, png, webp, pdf, docx, xlsx, csv, txt
```

### 3. **Send Template Message**
```javascript
// For future template support
template_id: "TEMPLATE_ID"
variables: {
    "{variableKey1}": "value1",
    "{variableKey2}": "value2"
}
```

---

## 💻 Code Implementation

### Backend Integration

**Location:** `backend/config/whatsapp.js`

```javascript
import axios from 'axios';

const API_ENDPOINT = process.env.WHATSAPP_API_URL;
const APP_KEY = process.env.WHATSAPP_APP_KEY;
const AUTH_KEY = process.env.WHATSAPP_AUTH_KEY;

// Send OTP
export const sendWhatsAppOTP = async (phoneNumber, otp) => {
  const response = await axios.post(API_ENDPOINT, {
    appkey: APP_KEY,
    authkey: AUTH_KEY,
    to: `91${phoneNumber}`,  // Adds India country code
    message: `Your OTP for Trust Tax Advisor is: ${otp}. Valid for 10 minutes.`
  });
  
  return { success: true, messageId: response.data?.data?.id };
};

// Send Alert
export const sendWhatsAppAlert = async (phoneNumber, message, fileUrl = null) => {
  const formData = {
    appkey: APP_KEY,
    authkey: AUTH_KEY,
    to: `91${phoneNumber}`,
    message: message
  };

  if (fileUrl) {
    formData.file = fileUrl;
  }

  const response = await axios.post(API_ENDPOINT, formData);
  return { success: true, messageId: response.data?.data?.id };
};
```

### Usage in Authentication Flow

**Location:** `backend/controllers/AuthController.js`

```javascript
import { sendWhatsAppOTP } from '../config/whatsapp.js';

export class AuthController {
  static async sendOtp(req, res) {
    const { mobile } = req.body;
    const otp = generateOTP();

    // Send via WhatsApp
    const result = await sendWhatsAppOTP(mobile, otp);
    
    if (result.success) {
      return res.json({ success: true, message: 'OTP sent via WhatsApp' });
    } else {
      return res.status(500).json({ error: result.error });
    }
  }
}
```

---

## 📊 API Response Format

### Success Response
```json
{
  "message_status": "Success",
  "data": {
    "from": "SENDER_NUMBER",
    "to": "RECEIVER_NUMBER",
    "status_code": 200
  }
}
```

### Error Response
```json
{
  "message_status": "Error",
  "error": "Invalid credentials or invalid phone number",
  "status_code": 400
}
```

---

## 🔄 Use Cases in Trust Tax Advisor

### 1. **OTP Login**
When user sends OTP request:
- ✅ Automatically sends OTP via WhatsApp
- ✅ Falls back to email if WhatsApp fails
- ✅ 10-minute expiry, 6-digit code
- ✅ Rate limited (3 per minute per number)

### 2. **Commission Notifications**
When connector earns commission:
- 📱 Sends WhatsApp alert with amount
- 📄 Can include invoice as PDF attachment
- 💰 Shows payment status updates

### 3. **Order Status Updates**
When order status changes:
- 📬 Client receives WhatsApp notification
- 📌 Can include order details
- ✓ Tracks delivery status

### 4. **Admin Alerts**
For system events:
- 🚨 Critical errors
- 💳 Payment failures
- 📊 Commission disputes
- 👥 New user registrations

---

## ✅ Parameters Explained

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `appkey` | string | Yes | Application key for API authorization |
| `authkey` | string | Yes | Authentication key for valid user |
| `to` | number | Yes | Receiver's WhatsApp number with country code (e.g., 919876543210) |
| `message` | string | No | Text message (max 1000 words) |
| `file` | string | No | File URL (jpg, png, pdf, docx, xlsx, csv, txt) |
| `template_id` | string | No | Template ID for template messages |
| `variables` | object | No | Variables to replace in template (e.g., {1}, {2}) |

---

## 📋 Supported File Formats

- **Images:** jpg, jpeg, png, webp
- **Documents:** pdf, docx, xlsx, csv, txt

**Example:**
```javascript
await sendWhatsAppAlert(
  '9876543210',
  'Your invoice is attached',
  'https://example.com/invoice.pdf'
);
```

---

## 🚀 Testing the Integration

### Test OTP Flow

1. **Start backend:**
   ```bash
   cd backend
   npm start
   ```

2. **Test with curl:**
   ```bash
   curl -X POST http://localhost:5000/api/auth/send-otp \
     -H "Content-Type: application/json" \
     -d '{"mobile": "9876543210"}'
   ```

3. **Check your WhatsApp:**
   - Should receive OTP within seconds
   - Format: "Your OTP for Trust Tax Advisor is: XXXXXX..."

### Test Manual Message

```javascript
// In backend code
import { sendWhatsAppAlert } from './config/whatsapp.js';

await sendWhatsAppAlert(
  '9876543210',
  'Hello! This is a test message from Trust Tax Advisor'
);
```

---

## 🔒 Security Best Practices

1. **Never commit credentials:**
   - Always use `.env` file
   - Add to `.gitignore`
   - Never log API keys

2. **Rate limiting:**
   - OTP requests: 3 per minute per number
   - Alert messages: No limit (internal only)
   - Configure in `middleware/auth.js`

3. **Message encryption:**
   - All messages go via HTTPS
   - API endpoint is secure (HTTPS)
   - No sensitive data in messages (only OTP)

4. **Validation:**
   - Phone numbers validated before sending
   - Message length limited to 1000 characters
   - Country code automatically added

---

## 📞 Message Cost

**Estimated costs** (as per API provider):
- Text message (OTP): ₹0.10 - ₹0.50
- Message with file: ₹0.50 - ₹1.00
- Template message: Variable based on provider

**Advantages over Twilio:**
- ✅ Lower cost (1/10th of Twilio)
- ✅ No setup/subscription required
- ✅ Better local support
- ✅ India-optimized

---

## 🐛 Troubleshooting

### Issue: "Invalid credentials"
**Solution:**
- Verify credentials in `.env`
- Check WHATSAPP_APP_KEY and WHATSAPP_AUTH_KEY
- Contact API provider for new keys

### Issue: "Invalid phone number"
**Solution:**
- Use 10-digit number without country code
- Backend adds India country code (91) automatically
- Example: `9876543210` (not `+919876543210`)

### Issue: "Message delivery timeout"
**Solution:**
- Check internet connection
- Verify API endpoint is reachable
- Add retry logic in controller

### Issue: "Rate limit exceeded"
**Solution:**
- Wait 1 minute before retrying
- Implement rate limiting on frontend
- Show user: "Too many attempts, try again in 1 minute"

### Issue: "API returns empty response"
**Solution:**
- Check if API endpoint is correct
- Verify WHATSAPP_API_URL in .env
- Check API provider status page

---

## 📝 API Documentation

### Official API Reference

**Base URL:** `https://whatsapp.thechintanpatel.co.in`

**Endpoint:** `/api/create-message`

**Method:** `POST`

**Request Format:** `application/x-www-form-urlencoded`

**Response Format:** `application/json`

---

## 🔄 Integration Checklist

- [ ] Updated `backend/.env` with credentials
- [ ] Verified API endpoint in `.env`
- [ ] Tested OTP login flow
- [ ] Received test OTP on WhatsApp
- [ ] Verified message format is correct
- [ ] Tested with multiple phone numbers
- [ ] Checked error handling
- [ ] Configured rate limiting
- [ ] Added to security hardening docs
- [ ] Tested in staging environment

---

## 📚 Related Documentation

- **README.md** - Full project documentation
- **SMTP_SETUP.md** - Email OTP configuration
- **AUTHENTICATION_GUIDE.md** - Auth flow details
- **CPANEL_DEPLOYMENT.md** - Production setup
- **backend/config/whatsapp.js** - Implementation code
- **backend/controllers/AuthController.js** - Usage example

---

## ✨ Features Enabled

With this WhatsApp integration you can:

✅ Send OTP via WhatsApp (primary auth method)  
✅ Send commission notifications  
✅ Send order status updates  
✅ Send invoices as PDF attachments  
✅ Send admin alerts  
✅ Use message templates (future)  
✅ Track message delivery  
✅ Fallback to email if WhatsApp fails  

---

## 🎯 Next Steps

1. **Test immediate:**
   ```bash
   npm start
   # Visit http://localhost:3000
   # Try login with WhatsApp OTP
   ```

2. **For production:**
   - Add API credentials to cPanel environment
   - Test with real phone numbers
   - Monitor delivery in first week
   - Set up alert notifications

3. **Customize messages:**
   - Edit message templates in `AuthController.js`
   - Add order-specific messages in `OrderController.js`
   - Create commission alerts in `CommissionController.js`

---

## 💡 Pro Tips

1. **Use emojis in messages:**
   ```
   "✅ Your OTP is: 123456"
   "💰 Commission: ₹500"
   "📦 Order Status Updated"
   ```

2. **Include timestamps:**
   ```
   "Valid for 10 minutes. Expires at 14:30"
   ```

3. **Add CTA buttons:**
   ```
   "Confirm order on: https://yourdomain.com/orders/123"
   ```

4. **Template variables:**
   ```
   "Hi {name}, your commission {amount} is pending approval"
   ```

---

## 📞 API Provider Support

**Support URL:** `https://whatsapp.thechintanpatel.co.in`

**For issues:**
- Contact API provider directly
- Provide error message and request details
- Check API status page for incidents

---

## Version Info

- **Integration Version:** 1.0.0
- **API Version:** v1
- **Last Updated:** March 2026
- **Status:** ✅ Production Ready

---

**Trust Tax Advisor now sends WhatsApp OTPs and alerts via your custom API!** 🚀

For questions or issues, refer to backend logs:
```bash
tail -f logs/backend.log
```
