305 lines
9.3 KiB
Markdown
305 lines
9.3 KiB
Markdown
# WhatsApp Invitation Integration Guide
|
||
|
||
## Overview
|
||
Complete WhatsApp Cloud API integration for sending wedding invitation template messages to guests via Meta's WhatsApp Business Platform.
|
||
|
||
## Features Implemented
|
||
|
||
### Backend (FastAPI)
|
||
- ✅ WhatsApp service module with template message support
|
||
- ✅ Single guest invitation endpoint: `POST /events/{event_id}/guests/{guest_id}/whatsapp/invite`
|
||
- ✅ Bulk guest invitation endpoint: `POST /events/{event_id}/whatsapp/invite`
|
||
- ✅ Phone number normalization to E.164 format (international standard)
|
||
- ✅ Event data auto-mapping to template variables
|
||
- ✅ Rate limiting protection (0.5s delay between sends)
|
||
- ✅ Error handling and detailed response reporting
|
||
- ✅ Secure credential management via environment variables
|
||
|
||
### Database
|
||
- ✅ Event model extended with WhatsApp-specific fields:
|
||
- `partner1_name` - First partner name (for template {{2}})
|
||
- `partner2_name` - Second partner name (for template {{3}})
|
||
- `venue` - Wedding venue/hall name (for template {{4}})
|
||
- `event_time` - Event time in HH:mm format (for template {{6}})
|
||
- `guest_link` - RSVP/guest link URL (for template {{7}})
|
||
|
||
### Frontend (React/Vite)
|
||
- ✅ `WhatsAppInviteModal` component with full Hebrew RTL support
|
||
- ✅ Guest selection checkboxes in guest list table
|
||
- ✅ "Send WhatsApp" button (💬 שלח בוואטסאפ) that appears when guests selected
|
||
- ✅ Modal form for event details input with message preview
|
||
- ✅ Results screen showing send success/failure details
|
||
- ✅ Dark/light theme support throughout
|
||
- ✅ API integration with error handling
|
||
|
||
## Setup Instructions
|
||
|
||
### 1. Environment Configuration (.env)
|
||
|
||
Add these variables to your `.env` file:
|
||
|
||
```env
|
||
# ============================================
|
||
# WhatsApp Cloud API Configuration
|
||
# ============================================
|
||
WHATSAPP_ACCESS_TOKEN=your_permanent_access_token_here
|
||
WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id_here
|
||
WHATSAPP_API_VERSION=v20.0
|
||
WHATSAPP_TEMPLATE_NAME=wedding_invitation
|
||
WHATSAPP_LANGUAGE_CODE=he
|
||
WHATSAPP_VERIFY_TOKEN=your_webhook_verify_token_here # Optional
|
||
```
|
||
|
||
**Where to get these credentials:**
|
||
1. Go to https://developers.facebook.com/
|
||
2. Select your WhatsApp Business Account
|
||
3. In "API Setup", find your Phone Number ID
|
||
4. Generate a permanent access token with `whatsapp_business_messaging` scope
|
||
5. Your template name must match the approved template in Meta (e.g., "wedding_invitation")
|
||
|
||
### 2. Database Migration
|
||
|
||
The database schema has been automatically updated with:
|
||
```sql
|
||
ALTER TABLE events ADD COLUMN partner1_name TEXT;
|
||
ALTER TABLE events ADD COLUMN partner2_name TEXT;
|
||
ALTER TABLE events ADD COLUMN venue TEXT;
|
||
ALTER TABLE events ADD COLUMN event_time TEXT;
|
||
ALTER TABLE events ADD COLUMN guest_link TEXT;
|
||
```
|
||
|
||
**If migration wasn't run automatically:**
|
||
```bash
|
||
cd backend
|
||
python run_migration.py
|
||
```
|
||
|
||
### 3. Start the Servers
|
||
|
||
**Backend:**
|
||
```bash
|
||
cd backend
|
||
python main.py
|
||
# Runs on http://localhost:8000
|
||
```
|
||
|
||
**Frontend:**
|
||
```bash
|
||
cd frontend
|
||
npm run dev
|
||
# Runs on http://localhost:5173
|
||
```
|
||
|
||
## Template Variables Mapping
|
||
|
||
The approved Meta template body (in Hebrew):
|
||
```
|
||
היי {{1}} 🤍
|
||
|
||
זה קורה! 🎉
|
||
{{2}} ו-{{3}} מתחתנים ונשמח שתהיה/י איתנו ברגע המיוחד הזה ✨
|
||
|
||
📍 האולם: "{{4}}"
|
||
📅 התאריך: {{5}}
|
||
🕒 השעה: {{6}}
|
||
|
||
לאישור הגעה ופרטים נוספים:
|
||
{{7}}
|
||
|
||
מתרגשים ומצפים לראותך 💞
|
||
```
|
||
|
||
**Auto-filled by system:**
|
||
- `{{1}}` = Guest first name (or "חבר" if empty)
|
||
- `{{2}}` = `event.partner1_name` (e.g., "דביר")
|
||
- `{{3}}` = `event.partner2_name` (e.g., "וורד")
|
||
- `{{4}}` = `event.venue` (e.g., "אולם כלות גן עדן")
|
||
- `{{5}}` = `event.date` formatted as DD/MM (e.g., "25/02")
|
||
- `{{6}}` = `event.event_time` in HH:mm (e.g., "19:00")
|
||
- `{{7}}` = `event.guest_link` or auto-generated RSVP URL
|
||
|
||
## Usage Flow
|
||
|
||
### 1. Create/Edit Event
|
||
When creating an event, fill in the wedding details:
|
||
- **Partner 1 Name**: חתן/ה ראשון/ה
|
||
- **Partner 2 Name**: חתן/ה שני/ה
|
||
- **Venue**: אולם/מקום
|
||
- **Date**: automatically formatted
|
||
- **Time**: HH:mm format
|
||
- **Guest Link**: Optional custom RSVP link (defaults to system URL)
|
||
|
||
### 2. Send Invitations
|
||
1. In guest list table, select guests with checkboxes
|
||
2. Click "💬 שלח בוואטסאפ" (Send WhatsApp) button
|
||
3. Modal opens with preview of message
|
||
4. Confirm details and click "שלח הזמנות" (Send Invitations)
|
||
5. View results: successful/failed deliveries
|
||
|
||
### 3. View Results
|
||
Results screen shows:
|
||
- ✅ Number of successful sends
|
||
- ❌ Number of failed sends
|
||
- Guest names and phone numbers
|
||
- Error reasons for failures
|
||
|
||
## API Endpoints
|
||
|
||
### Single Guest Invitation
|
||
```http
|
||
POST /events/{event_id}/guests/{guest_id}/whatsapp/invite
|
||
Content-Type: application/json
|
||
|
||
{
|
||
"phone_override": "+972541234567" # Optional
|
||
}
|
||
|
||
Response:
|
||
{
|
||
"guest_id": "uuid",
|
||
"guest_name": "דביר",
|
||
"phone": "+972541234567",
|
||
"status": "sent" | "failed",
|
||
"message_id": "wamid.xxx...",
|
||
"error": "error message if failed"
|
||
}
|
||
```
|
||
|
||
### Bulk Guest Invitations
|
||
```http
|
||
POST /events/{event_id}/whatsapp/invite
|
||
Content-Type: application/json
|
||
|
||
{
|
||
"guest_ids": ["uuid1", "uuid2", "uuid3"],
|
||
"phone_override": null
|
||
}
|
||
|
||
Response:
|
||
{
|
||
"total": 3,
|
||
"succeeded": 2,
|
||
"failed": 1,
|
||
"results": [
|
||
{ "guest_id": "uuid1", "status": "sent", ... },
|
||
{ "guest_id": "uuid2", "status": "failed", ... },
|
||
...
|
||
]
|
||
}
|
||
```
|
||
|
||
## Phone Number Format
|
||
|
||
The system automatically converts various phone formats to E.164 international format:
|
||
|
||
Examples:
|
||
- `05XXXXXXXX` (Israeli) → `+9725XXXXXXXX`
|
||
- `+9725XXXXXXXX` (already formatted) → unchanged
|
||
- `+1-555-123-4567` (US) → `+15551234567`
|
||
|
||
## Error Handling
|
||
|
||
Common errors and solutions:
|
||
|
||
| Error | Solution |
|
||
|-------|----------|
|
||
| `Invalid phone number` | Ensure phone has valid country code |
|
||
| `WhatsApp API error (400)` | Check template name and language code |
|
||
| `Not authenticated` | Admin must be logged in (localStorage userId set) |
|
||
| `Guest not found` | Verify guest exists in event and ID is correct |
|
||
| `Template pending review` | Template must be APPROVED in Meta Business Manager |
|
||
|
||
## Hebrew & RTL Support
|
||
|
||
✅ All text is in Hebrew
|
||
✅ RTL (right-to-left) layout throughout
|
||
✅ Component uses `direction: rtl` in CSS
|
||
✅ Form labels and buttons properly aligned for Arabic/Hebrew
|
||
|
||
## Security Considerations
|
||
|
||
1. **No secrets in code**: All credentials loaded from environment variables
|
||
2. **No token logging**: Access tokens never logged, even in errors
|
||
3. **Phone validation**: Invalid numbers rejected before API call
|
||
4. **Rate limiting**: 0.5s delay between sends to avoid throttling
|
||
5. **Authorization**: Only event members can send invitations
|
||
6. **HTTPS in production**: Ensure encrypted transmission of tokens
|
||
|
||
## Database Constraints
|
||
|
||
- Event fields are nullable for backward compatibility
|
||
- Phone numbers stored as-is, normalized only for sending
|
||
- Guest table still supports legacy `phone` field (use `phone_number`)
|
||
- No duplicate constraint on phone numbers (allows plus-ones)
|
||
|
||
## Logging & Monitoring
|
||
|
||
Events logged to console (can be extended):
|
||
```python
|
||
# In backend logs:
|
||
[INFO] Sending WhatsApp to guest: {guest_id} -> {phone_number}
|
||
[INFO] WhatsApp sent successfully: {message_id}
|
||
[ERROR] WhatsApp send failed: {error_reason}
|
||
```
|
||
|
||
## Testing Checklist
|
||
|
||
Before going to production:
|
||
|
||
- [ ] Meta template is APPROVED (not pending)
|
||
- [ ] Phone number ID correctly configured
|
||
- [ ] Access token has `whatsapp_business_messaging` scope
|
||
- [ ] Test with your own phone number first
|
||
- [ ] Verify phone normalization for your country
|
||
- [ ] Check message formatting in different languages
|
||
- [ ] Test with various phone number formats
|
||
- [ ] Verify event creation populates all new fields
|
||
- [ ] Test bulk send with 3+ guests
|
||
- [ ] Verify error handling (wrong phone, missing field)
|
||
- [ ] Check dark/light mode rendering
|
||
|
||
## Troubleshooting
|
||
|
||
### Backend Won't Start
|
||
```bash
|
||
# Check syntax
|
||
python -m py_compile main.py schemas.py crud.py whatsapp.py
|
||
|
||
# Check database connection
|
||
python << 'EOF'
|
||
import psycopg2
|
||
conn = psycopg2.connect("postgresql://wedding_admin:Aa123456@localhost:5432/wedding_guests")
|
||
print("✅ Database connected")
|
||
EOF
|
||
```
|
||
|
||
### Modal Not Appearing
|
||
1. Check browser console for JavaScript errors
|
||
2. Verify guests are selected (checkboxes checked)
|
||
3. Check that GuestList properly imports WhatsAppInviteModal
|
||
4. Clear browser cache and hard refresh
|
||
|
||
### Messages Not Sending
|
||
1. Check WHATSAPP_ACCESS_TOKEN in .env
|
||
2. Verify WHATSAPP_PHONE_NUMBER_ID matches your configured number
|
||
3. Confirm template is APPROVED (not pending/rejected)
|
||
4. Check guest phone numbers are complete and valid
|
||
5. Review backend logs for API errors
|
||
|
||
## Future Enhancements
|
||
|
||
- [ ] Webhook handling for message status updates (delivered/read)
|
||
- [ ] Message template versioning
|
||
- [ ] Scheduled sends (defer until specific time)
|
||
- [ ] Template variable presets per event
|
||
- [ ] Analytics: delivery rates, engagement metrics
|
||
- [ ] Support for local attachment messages
|
||
- [ ] Integration with CRM for follow-ups
|
||
|
||
## Support & References
|
||
|
||
- Meta WhatsApp API Docs: https://developers.facebook.com/docs/whatsapp/cloud-api
|
||
- Error Codes: https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes
|
||
- Message Templates: https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates
|
||
- Phone Number Formatting: https://en.wikipedia.org/wiki/E.164
|