# WhatsApp Custom API - Implementation Examples

## Quick Start Configuration

### Step 1: Set Environment Variables

**File:** `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: WhatsApp Service Implementation

**File:** `backend/config/whatsapp.js` (Already Modified ✅)

---

## 📤 Usage Examples

### 1. Send OTP Text Message

```javascript
// In AuthController.js
import { sendWhatsAppOTP } from '../config/whatsapp.js';

const result = await sendWhatsAppOTP(
  '9876543210',  // 10-digit phone number (without country code)
  '123456'       // 6-digit OTP
);

if (result.success) {
  console.log('OTP sent successfully');
  console.log(`Message ID: ${result.messageId}`);
} else {
  console.error(`Failed: ${result.error}`);
}
```

**Expected Response:**
```json
{
  "success": true,
  "messageId": "919876543210-919876543210",
  "response": {
    "message_status": "Success",
    "data": {
      "from": "919876543210",
      "to": "919876543210",
      "status_code": 200
    }
  }
}
```

---

### 2. Send Alert Message

```javascript
// In CommissionController.js
import { sendWhatsAppAlert } from '../config/whatsapp.js';

const result = await sendWhatsAppAlert(
  '9876543210',
  '💰 Congratulations! You earned ₹500 commission on Order #1234. Check your dashboard for details.'
);

if (result.success) {
  console.log('Alert sent successfully');
} else {
  console.error(`Failed: ${result.error}`);
}
```

---

### 3. Send Message with File

```javascript
// In OrderController.js
import { sendWhatsAppAlert } from '../config/whatsapp.js';

const result = await sendWhatsAppAlert(
  '9876543210',
  '📄 Your invoice is attached. Thank you for using Trust Tax Advisor!',
  'https://yourdomain.com/documents/invoice-2026-001.pdf'
);

if (result.success) {
  console.log('Message with file sent successfully');
} else {
  console.error(`Failed: ${result.error}`);
}
```

**Supported File Types:**
- Images: jpg, jpeg, png, webp
- Documents: pdf, docx, xlsx, csv, txt

---

### 4. Send Template Message (Future Use)

```javascript
// For future template support
const formData = {
  appkey: process.env.WHATSAPP_APP_KEY,
  authkey: process.env.WHATSAPP_AUTH_KEY,
  to: '919876543210',
  template_id: 'order_confirmation',
  variables: {
    '{customerName}': 'John Doe',
    '{orderId}': 'ORD-2026-001',
    '{amount}': '₹1000'
  }
};

const response = await axios.post(
  process.env.WHATSAPP_API_URL,
  formData
);
```

---

## 🔧 Integration in Controllers

### AuthController - OTP Login

```javascript
// File: backend/controllers/AuthController.js

import { sendWhatsAppOTP } from '../config/whatsapp.js';
import { generateOTP } from '../utils/helpers.js';

export class AuthController {
  static async sendOtp(req, res) {
    try {
      const { mobile, email } = req.body;

      // Validate input
      if (!mobile && !email) {
        return res.status(400).json({ 
          error: 'Mobile or email required' 
        });
      }

      // Generate OTP
      const otp = generateOTP(); // Returns 6-digit OTP like "123456"
      const expiresAt = new Date(Date.now() + 10 * 60000); // 10 minutes

      // Save OTP to database
      await OtpLog.create({
        mobile: mobile || null,
        email: email || null,
        otp,
        type: 'login',
        expires_at: expiresAt
      });

      // Send via WhatsApp (if mobile provided)
      if (mobile) {
        const result = await sendWhatsAppOTP(mobile, otp);
        
        if (result.success) {
          return res.json({ 
            success: true, 
            message: 'OTP sent via WhatsApp',
            method: 'whatsapp'
          });
        } else {
          console.warn(`WhatsApp failed: ${result.error}, falling back to email`);
          // Fallback to email would go here
        }
      }

      // Send via Email (if email provided)
      if (email) {
        const htmlContent = `
          <h2 style="color: #333;">Your OTP for Trust Tax Advisor</h2>
          <p style="font-size: 24px; color: #007bff; font-weight: bold;">${otp}</p>
          <p>Valid for 10 minutes. Please do not share this OTP with anyone.</p>
        `;
        await sendEmail(email, 'OTP for Trust Tax Advisor', htmlContent);
        
        return res.json({ 
          success: true, 
          message: 'OTP sent via Email',
          method: 'email'
        });
      }

    } catch (error) {
      console.error('Send OTP error:', error);
      res.status(500).json({ error: 'Failed to send OTP' });
    }
  }

  static async verifyOtp(req, res) {
    try {
      const { mobile, email, otp } = req.body;

      // Validate input
      if (!otp || (!mobile && !email)) {
        return res.status(400).json({ 
          error: 'OTP and mobile/email required' 
        });
      }

      // Find OTP log
      const otpLog = await OtpLog.findLatest(mobile || email);

      if (!otpLog || otpLog.otp !== otp) {
        return res.status(400).json({ error: 'Invalid OTP' });
      }

      // Check expiry
      if (new Date() > new Date(otpLog.expires_at)) {
        return res.status(400).json({ error: 'OTP expired' });
      }

      // User authentication successful
      // ... rest of login logic ...

      return res.json({ 
        success: true, 
        message: 'Login successful',
        token: token
      });

    } catch (error) {
      console.error('Verify OTP error:', error);
      res.status(500).json({ error: 'Failed to verify OTP' });
    }
  }
}
```

---

### CommissionController - Send Alerts

```javascript
// File: backend/controllers/CommissionController.js

import { sendWhatsAppAlert } from '../config/whatsapp.js';
import Commission from '../models/Commission.js';

export class CommissionController {
  // Send WhatsApp alert when commission is created
  static async notifyCommissionCreated(connectorId, amount) {
    try {
      const connector = await Connector.findById(connectorId);
      
      if (!connector || !connector.mobile) {
        console.warn(`No phone number for connector ${connectorId}`);
        return;
      }

      const message = `
🎉 Congratulations!
You have earned a commission of ₹${amount}

💰 Total Pending: ₹${connector.total_pending || 0}
⏳ Payment will be processed within 30 days

Check your dashboard for more details.
      `.trim();

      await sendWhatsAppAlert(connector.mobile, message);
      
    } catch (error) {
      console.error('Commission notification failed:', error);
    }
  }

  // Send WhatsApp alert when commission is marked as paid
  static async notifyCommissionPaid(connectorId, amount) {
    try {
      const connector = await Connector.findById(connectorId);
      
      if (!connector || !connector.mobile) {
        console.warn(`No phone number for connector ${connectorId}`);
        return;
      }

      const message = `
✅ Payment Successful!
You have received ₹${amount} commission.

🏦 Amount transferred to your registered bank account
📧 Check your email for transaction details

Thank you for your dedication! 🙏
      `.trim();

      await sendWhatsAppAlert(connector.mobile, message);
      
    } catch (error) {
      console.error('Payment notification failed:', error);
    }
  }
}
```

---

### OrderController - Send Order Updates

```javascript
// File: backend/controllers/OrderController.js

import { sendWhatsAppAlert } from '../config/whatsapp.js';
import Order from '../models/Order.js';

export class OrderController {
  static async completeOrder(req, res) {
    try {
      const { id } = req.params;
      
      // Update order status
      const order = await Order.update(id, { status: 'completed' });

      // Notify client via WhatsApp
      const client = await Client.findById(order.client_id);
      if (client && client.user_phone) {
        const message = `
✅ Your order has been completed!

📋 Order ID: #${order.id}
💼 Service: ${order.service_name}
💰 Amount: ₹${order.amount}

Thank you for choosing Trust Tax Advisor! 🙏
        `.trim();

        await sendWhatsAppAlert(client.user_phone, message);
      }

      // Notify connector about commission (see CommissionController)
      // ...

      return res.json({ 
        success: true, 
        message: 'Order completed and notifications sent',
        order 
      });

    } catch (error) {
      console.error('Complete order error:', error);
      res.status(500).json({ error: 'Failed to complete order' });
    }
  }
}
```

---

### AdminController - System Alerts

```javascript
// File: backend/controllers/AdminController.js

import { sendWhatsAppAlert } from '../config/whatsapp.js';

export class AdminController {
  // Send alert to admin for critical events
  static async sendAdminAlert(phoneNumber, title, details) {
    try {
      const message = `
🚨 ADMIN ALERT
${title}

📝 Details: ${details}
⏰ Time: ${new Date().toLocaleString('en-IN')}

Action required!
      `.trim();

      await sendWhatsAppAlert(phoneNumber, message);
      
    } catch (error) {
      console.error('Admin alert failed:', error);
    }
  }

  // Example: Payment failure alert
  static async handlePaymentFailure(orderId, error) {
    await this.sendAdminAlert(
      process.env.ADMIN_PHONE,
      'Payment Processing Failed',
      `Order #${orderId}: ${error}`
    );
  }

  // Example: High-value order alert
  static async handleLargeOrder(orderId, amount) {
    if (amount > 50000) {
      await this.sendAdminAlert(
        process.env.ADMIN_PHONE,
        'Large Order Received',
        `Order #${orderId} for ₹${amount} needs verification`
      );
    }
  }
}
```

---

## 📊 Error Handling

```javascript
import { sendWhatsAppOTP } from '../config/whatsapp.js';

async function sendOtpWithFallback(mobile, email, otp) {
  try {
    // Try WhatsApp first
    const result = await sendWhatsAppOTP(mobile, otp);
    
    if (result.success) {
      return { method: 'whatsapp', success: true };
    } else {
      console.warn(`WhatsApp failed: ${result.error}`);
      
      // Fallback to email
      await sendEmail(email, 'OTP for Trust Tax Advisor', 
        `Your OTP is: ${otp}`);
      
      return { method: 'email', success: true };
    }
    
  } catch (error) {
    console.error('OTP send failed:', error);
    return { success: false, error: error.message };
  }
}
```

---

## ✅ Testing Checklist

```bash
# 1. Start backend
cd backend
npm start

# 2. Test OTP endpoint
curl -X POST http://localhost:5000/api/auth/send-otp \
  -H "Content-Type: application/json" \
  -d '{"mobile": "9876543210"}'

# Expected: OTP received on WhatsApp within 5 seconds

# 3. Test verification
curl -X POST http://localhost:5000/api/auth/verify-otp \
  -H "Content-Type: application/json" \
  -d '{"mobile": "9876543210", "otp": "123456"}'

# 4. Check logs
tail -f logs/whatsapp.log

# 5. Verify JWT token received
# Token should be valid for 7 days
```

---

## 🔒 Security Notes

1. **Never log credentials:**
   ```javascript
   // ❌ WRONG
   console.log(`Sending with key: ${APP_KEY}`);
   
   // ✅ RIGHT
   console.log('Sending WhatsApp message...');
   ```

2. **Validate inputs:**
   ```javascript
   if (!isValidPhone(phoneNumber)) {
     throw new Error('Invalid phone number');
   }
   ```

3. **Rate limit OTP requests:**
   ```javascript
   // Configured in middleware/auth.js
   // 3 requests per minute per number
   ```

4. **Use HTTPS in production:**
   ```env
   # Production
   WHATSAPP_API_URL=https://whatsapp.thechintanpatel.co.in/api/create-message
   NODE_ENV=production
   ```

---

## 📞 Monitoring & Logging

```javascript
// Add logging for monitoring
import logger from '../utils/logger.js';

export const sendWhatsAppOTP = async (phoneNumber, otp) => {
  try {
    logger.info(`Sending OTP to ${phoneNumber}`);
    
    const response = await axios.post(API_ENDPOINT, {
      appkey: APP_KEY,
      authkey: AUTH_KEY,
      to: `91${phoneNumber}`,
      message: `Your OTP for Trust Tax Advisor is: ${otp}. Valid for 10 minutes.`
    });

    if (response.data?.message_status === 'Success') {
      logger.info(`OTP sent successfully to ${phoneNumber}`);
      return { success: true, messageId: response.data?.data?.id };
    } else {
      logger.error(`OTP send failed for ${phoneNumber}: ${response.data?.error}`);
      return { success: false, error: 'Failed to send OTP' };
    }
    
  } catch (error) {
    logger.error(`WhatsApp API error: ${error.message}`);
    return { success: false, error: error.message };
  }
};
```

---

## 🚀 Production Deployment

### cPanel Configuration

```bash
# 1. Update .env on server
WHATSAPP_API_URL=https://whatsapp.thechintanpatel.co.in/api/create-message
WHATSAPP_APP_KEY=1a68fcd1-3746-4be7-9cc0-334423e4e1d5
WHATSAPP_AUTH_KEY=yoQ5tAx2MjtnOM2JCu8HU5IuL14DDkKesmGnCVOLRzuyVbu1qv

# 2. Restart Node.js app
# In cPanel: Setup Node.js App → Restart

# 3. Monitor logs
tail -f /var/log/nodejs/app.log
```

---

## 💡 Best Practices

1. **Use descriptive messages:** Include order/commission details
2. **Add emojis:** Makes messages more engaging
3. **Keep messages short:** Max 1000 characters
4. **Include timestamps:** "Valid for 10 minutes"
5. **Test with multiple numbers:** Ensure consistency
6. **Monitor delivery:** Log all requests
7. **Handle failures gracefully:** Fallback to email
8. **Rate limit:** Prevent abuse

---

## Version Info
- **Version:** 1.0.0
- **Last Updated:** March 2026
- **Status:** ✅ Production Ready
