# Paydunya Integration - ONG Enfants Soleil Sénégal

## 📋 Overview

This document explains the complete Paydunya payment integration implemented for the donation system. The implementation supports both authenticated and anonymous users, and works alongside the existing PayTech integration.

---

## 🎯 Features Implemented

### 1. **Dual Payment Provider Support**
- Users can choose between **PayTech** or **Paydunya** via radio buttons
- Both providers work independently
- Same donation flow with provider-specific handling

### 2. **User Support**
- ✅ **Authenticated users** - Full tracking and history
- ✅ **Anonymous users** - Guest user system for unregistered donations
- ✅ **GivingCircle members** - Support for monthly subscriptions

### 3. **Payment Flow**
```
User selects provider (PayTech/Paydunya)
    ↓
Enter donation amount
    ↓
Submit form → AJAX call to appropriate endpoint
    ↓
Backend creates Donation record (status='pending')
    ↓
Service layer creates invoice on Paydunya
    ↓
User redirected to Paydunya payment page
    ↓
User completes payment
    ↓
[Path 1] IPN callback updates status (commented for now)
[Path 2] User redirects to success page → Verify payment
    ↓
Display success/cancel page with receipt
```

---

## 📁 Files Modified/Created

### **Models** ([models.py](appsponsor/models.py))
Added to `Donation` model:
```python
payment_provider = models.CharField(max_length=20, choices=PROVIDER_CHOICES, default='paytech')
invoice_token = models.CharField(max_length=100, blank=True, null=True)
receipt_url = models.URLField(blank=True, null=True)
```

### **Service Layer** ([paydunya_service.py](appsponsor/paydunya_service.py))
New service class with methods:
- `__init__()` - Initialize Paydunya SDK
- `create_donation_invoice()` - Create invoice for donations
- `create_subscription_invoice()` - Create invoice for GivingCircle subscriptions
- `confirm_payment()` - Verify payment status by token
- `verify_ipn_hash()` - Verify IPN authenticity (SHA-512)
- `get_guest_user()` - Get/create guest user for anonymous donations

### **Views** ([views_paydunya.py](appsponsor/views_paydunya.py))
New views:
- `paydunya_donate_view()` - Handle donation requests (AJAX)
- `paydunya_success_view()` - Handle successful payment return
- `paydunya_cancel_view()` - Handle cancelled payment
- `paydunya_ipn_view()` - **[COMMENTED]** IPN notification handler

### **Templates**
- [paydunya_success.html](templates/appsponsor/paydunya_success.html) - Success page with receipt download
- [paydunya_cancel.html](templates/appsponsor/paydunya_cancel.html) - Cancellation page
- [index.html](templates/appsponsor/index.html) - Updated with provider selector

### **Configuration**
- [settings.py](projectesm/settings.py) - Paydunya configuration
- [.env.example](.env.example) - Environment variables template
- [urls.py](appsponsor/urls.py) - Paydunya endpoints

---

## ⚙️ Configuration

### 1. Environment Variables

Copy the following to your `.env` file:

```bash
# ========================================
# Paydunya Payment Gateway Configuration
# ========================================
PAYDUNYA_MASTER_KEY=wQzk9ZwR-Qq9m-0hD0-zpud-je5coGC3FHKW
PAYDUNYA_PRIVATE_KEY=test_private_rMIdJM3PLLhLjyArx9tF3VURAF5
PAYDUNYA_TOKEN=IivOiOxGJuWhc5znlIiK
PAYDUNYA_MODE=test  # 'test' or 'live'

# Store Information
PAYDUNYA_STORE_NAME=ONG Enfants Soleil Sénégal
PAYDUNYA_STORE_TAGLINE=Different Make Me Amazing!
PAYDUNYA_STORE_PHONE=+221336530583
PAYDUNYA_STORE_POSTAL_ADDRESS=Dakar, Sénégal
PAYDUNYA_STORE_WEBSITE=https://enfantsoleilmonde.org
PAYDUNYA_STORE_LOGO=https://enfantsoleilmonde.org/static/theme/assets/img/ONG-Enfants-Soleil-Senegal-LOGO.jpeg

# Callback URLs (use ngrok for local development)
PAYDUNYA_CALLBACK_URL=https://enfantsoleilmonde.org/paydunya/ipn/
PAYDUNYA_RETURN_URL=https://enfantsoleilmonde.org/paydunya/success/
PAYDUNYA_CANCEL_URL=https://enfantsoleilmonde.org/paydunya/cancel/
```

### 2. Install Paydunya SDK

```bash
source venv/bin/activate
pip install paydunya
```

### 3. Run Migrations

```bash
python manage.py migrate
```

---

## 🚀 Usage

### For End Users

1. Go to homepage
2. Select payment provider (PayTech or Paydunya)
3. Enter donation amount (1,000 - 8,000,000 FCFA)
4. Click "Faire un DON"
5. Redirected to Paydunya payment page
6. Complete payment with preferred method (Orange Money, Wave, Free Money, Card)
7. Redirected to success page with receipt

### For Developers

#### Creating a Donation Programmatically

```python
from appsponsor.paydunya_service import PaydunyaService
from appsponsor.models import Donation

# Initialize service
service = PaydunyaService()

# Create donation record
donation = Donation.objects.create(
    user=user,
    amount=5000,
    payment_provider='paydunya',
    status='pending'
)

# Create invoice
success, response = service.create_donation_invoice(
    amount=5000,
    user=user,
    custom_data={'donation_id': donation.id}
)

if success:
    donation.invoice_token = response['token']
    donation.save()
    redirect_url = response['redirect_url']
```

#### Verifying Payment Status

```python
# After user returns from payment page
token = request.GET.get('token')

service = PaydunyaService()
success, response = service.confirm_payment(token)

if success and response['status'] == 'completed':
    # Payment successful
    receipt_url = response['receipt_url']
```

---

## 🔒 Security Considerations

### 1. **Hash Verification (IPN)**
The IPN handler **MUST** verify the hash before processing:

```python
# Hash is SHA-512 of MASTER_KEY
expected_hash = hashlib.sha512(MASTER_KEY.encode()).hexdigest()
if received_hash != expected_hash:
    return HttpResponse('Invalid hash', status=403)
```

### 2. **Environment Variables**
- **Never commit** real API keys to version control
- Use different keys for test and production
- Store keys in `.env` file (not tracked by git)

### 3. **HTTPS Required**
- IPN callback URL **must** be HTTPS in production
- Use ngrok for local development testing

---

## 📊 Testing

### Test Mode
Paydunya test mode randomly charges 100-150 XOF for validation.

### Local Testing Steps

1. **Start development server**
   ```bash
   python manage.py runserver
   ```

2. **Setup ngrok (for IPN testing)**
   ```bash
   ngrok http 8000
   ```
   Update `PAYDUNYA_CALLBACK_URL` in `.env` with ngrok URL

3. **Test donation flow**
   - Go to homepage
   - Select Paydunya
   - Enter test amount (e.g., 1000 FCFA)
   - Complete payment on Paydunya test page
   - Verify success page shows correctly
   - Check donation status in admin

4. **Test scenarios**
   - ✅ Anonymous user donation
   - ✅ Authenticated user donation
   - ✅ Payment cancellation
   - ✅ Receipt download

---

## 🔄 IPN Implementation (When Ready)

The IPN handler is **commented out** but fully implemented. To activate:

### 1. Uncomment in [views_paydunya.py](appsponsor/views_paydunya.py)
Remove the `"""` comment blocks around the `paydunya_ipn_view` function.

### 2. Uncomment in [urls.py](appsponsor/urls.py)
```python
from appsponsor.views_paydunya import paydunya_ipn_view

urlpatterns = [
    # ...
    path('paydunya/ipn/', paydunya_ipn_view, name='paydunya_ipn'),
]
```

### 3. Configure IPN URL
Ensure `PAYDUNYA_CALLBACK_URL` is publicly accessible (HTTPS).

### 4. Test IPN
Use Postman to simulate IPN POST request:
```
POST https://your-domain.com/paydunya/ipn/
Content-Type: application/x-www-form-urlencoded

data[status]=completed
data[hash]=sha512_of_master_key
data[invoice][token]=test_xxx
data[custom_data][donation_id]=123
```

---

## 🎨 Frontend Components

### Provider Selector
```html
<div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="provider" id="paydunya" value="paydunya">
    <label class="form-check-label" for="paydunya">
        <i class="bi bi-wallet2 me-1"></i> Paydunya
    </label>
</div>
```

### JavaScript Handler
Routes to appropriate endpoint based on selected provider:
```javascript
const provider = document.querySelector('input[name="provider"]:checked').value;
const endpoint = provider === 'paydunya' 
    ? "{% url 'paydunya_donate' %}"
    : window.location.href;
```

---

## 📝 Database Schema

### Donation Model Fields
```sql
payment_provider VARCHAR(20)  -- 'paytech' or 'paydunya'
invoice_token VARCHAR(100)    -- Paydunya invoice token
receipt_url VARCHAR(200)      -- PDF receipt URL from Paydunya
```

---

## 🐛 Troubleshooting

### Issue: "ModuleNotFoundError: No module named 'paydunya'"
**Solution:** Install Paydunya SDK
```bash
pip install paydunya
```

### Issue: "IPN hash verification failed"
**Solution:** Check that MASTER_KEY in `.env` matches your Paydunya account

### Issue: "Callback URL not accessible"
**Solution:** Use ngrok for local development, ensure HTTPS in production

### Issue: "Invoice creation failed"
**Solution:** Check API keys are correct and Paydunya account is active

---

## 📚 Resources

- **Paydunya Python Documentation:** https://developers.paydunya.com/doc/FR/Python
- **Paydunya Dashboard:** https://paydunya.com/dashboard
- **Test Credentials:** Already in `.env.example`

---

## 🔜 Future Enhancements

1. **User Profile Dashboard**
   - View donation history
   - Download all receipts
   - Manage GivingCircle subscription

2. **Email Notifications**
   - Send confirmation emails to authenticated users
   - Monthly subscription reminders

3. **Recurring Payments**
   - Automatic monthly invoices for GivingCircle members
   - Subscription management

4. **Analytics Dashboard**
   - Track donations by provider
   - Compare PayTech vs Paydunya usage
   - Revenue analytics

---

## ✅ Deployment Checklist

Before deploying to production:

- [ ] Replace test API keys with production keys
- [ ] Set `PAYDUNYA_MODE=live` in production `.env`
- [ ] Ensure all callback URLs use HTTPS
- [ ] Test payment flow end-to-end
- [ ] Uncomment and test IPN handler
- [ ] Verify receipt PDF generation
- [ ] Test with real payment amounts
- [ ] Monitor logs for errors
- [ ] Set up email notifications

---

## 👥 Support

For issues or questions:
- **Technical:** Check logs in `audits` app
- **Paydunya:** https://paydunya.com/support
- **Project:** contact@enfantsoleilmonde.org

---

**Implementation Date:** April 3, 2026  
**Version:** 1.0.0  
**Status:** ✅ Ready for Testing
