# PayTech Payment Gateway Integration Guide

## 📚 Official Documentation
This integration is based exclusively on:
- **PayTech Official Documentation**: https://doc.intech.sn/doc_paytech.php
- **PayTech Postman Collection**: https://doc.intech.sn/PayTech%20x%20DOC.postman_collection.json

---

## 🚀 Quick Start

### 1. Get Your PayTech API Keys

1. Sign up at [PayTech](https://paytech.sn/)
2. Go to Dashboard → Settings → API
3. Copy your `API_KEY` and `API_SECRET`

### 2. Update Environment Variables

Edit your `.env` file and add your actual PayTech credentials:

```bash
# PayTech Configuration
PAYTECH_API_KEY=your_actual_api_key_here
PAYTECH_API_SECRET=your_actual_api_secret_here
PAYTECH_ENV=test  # Change to 'prod' when ready for production
PAYTECH_BASE_URL=https://paytech.sn/api
PAYTECH_IPN_URL=https://booking.scadoxus.sn/payment/ipn/
PAYTECH_SUCCESS_URL=https://booking.scadoxus.sn/payment/success/
PAYTECH_CANCEL_URL=https://booking.scadoxus.sn/payment/cancel/
```

### 3. Switch to PayTech Views

Replace your current `views.py` with the new PayTech implementation:

```bash
# Backup your current views
mv appsponsor/views.py appsponsor/views_old.py

# Use the new PayTech views
mv appsponsor/views_paytech.py appsponsor/views.py
```

### 4. Enable IPN Endpoint

Uncomment the IPN URL in `appsponsor/urls.py`:

```python
from appsponsor.views import payment_ipn

urlpatterns = [
    # ... existing patterns ...
    path('payment/ipn/', payment_ipn, name='payment_ipn'),
]
```

### 5. Run Migrations (if needed)

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

---

## 🏗️ Architecture Overview

### Backend Components

1. **`paytech_service.py`**: Core PayTech API integration
   - `request_payment()`: Create payment requests
   - `verify_ipn_hmac()`: Verify IPN notifications (recommended)
   - `verify_ipn_sha256()`: Alternative IPN verification
   - `get_payment_status()`: Check payment status
   - `request_refund()`: Process refunds

2. **`views_paytech.py`**: Django views for PayTech
   - `index_view()`: Handle donations with PayTech
   - `paytech_ipn_view()`: Receive PayTech webhooks
   - `paytech_success_view()`: Success redirect handler
   - `paytech_cancel_view()`: Cancel redirect handler

3. **`models.py`**: Database models
   - `Sponsorship`: User sponsorship levels
   - `Donation`: Payment records

---

## 🔄 Payment Flow

### User Journey

```
1. User fills donation form → 
2. Backend creates Donation record → 
3. PayTech service generates payment URL → 
4. User redirected to PayTech checkout → 
5. User completes payment → 
6. PayTech sends IPN to your server → 
7. Your server updates Donation status → 
8. User redirected to success page (with token/ref_command)
```

**Security Note**: Success and cancel pages are protected. Direct access without valid PayTech parameters (token or ref_command) will redirect users to the home page.

### API Request Example

```python
paytech_service = PaytechService()

response = paytech_service.request_payment(
    item_name="Don pour ONG ESM",
    item_price=5000,  # Amount in XOF
    ref_command="DON_123_1234567890",
    command_name="Don de 5,000 FCFA",
    custom_field={
        'donation_id': 123,
        'user_id': 456,
        'email': 'user@example.com'
    },
    target_payment="Orange Money, Wave, Free Money",
    user=request.user  # For auto-fill
)

if response.get('success') == 1:
    redirect_url = response.get('redirect_url')
    # Redirect user to PayTech checkout
```

---

## 🔔 IPN (Instant Payment Notifications)

### How It Works

PayTech sends POST requests to your `ipn_url` when payment events occur.

### Event Types

| Event Type | Description |
|------------|-------------|
| `sale_complete` | Payment successful |
| `sale_canceled` | Payment canceled by user |
| `refund_complete` | Refund processed |

### IPN Security

PayTech uses **two verification methods**:

1. **HMAC-SHA256** (Recommended):
   ```python
   # For payments: message = amount|ref_command|api_key
   # For transfers: message = amount|id_transfer|api_key
   expected_hmac = hmac.new(api_secret, message, sha256).hexdigest()
   ```

2. **SHA256 Hashes**:
   ```python
   expected_key_hash = sha256(api_key).hexdigest()
   expected_secret_hash = sha256(api_secret).hexdigest()
   ```

### IPN Handler Example

```python
@csrf_exempt
@require_POST
def payment_ipn(request):
    paytech_service = PaytechService()
    ipn_data = request.POST.dict()
    
    # Verify authenticity
    if not paytech_service.verify_ipn_hmac(ipn_data):
        return HttpResponse('IPN KO', status=403)
    
    # Process event
    if ipn_data.get('type_event') == 'sale_complete':
        # Update donation status
        donation = Donation.objects.get(id=custom_field['donation_id'])
        donation.status = 'approved'
        donation.save()
    
    return HttpResponse('IPN OK', status=200)
```

---

## 💰 Payment Methods Supported

PayTech supports multiple payment methods in Senegal:

- **Mobile Money**:
  - Orange Money
  - Wave
  - Free Money
  - Emoney
  - Wizall

- **Bank Cards**:
  - Carte Bancaire (Visa, Mastercard)

### Single vs. Multiple Payment Methods

**Single Method (Auto-fill enabled)**:
```python
target_payment = "Orange Money"
# PayTech will pre-fill user info (phone, name) if user object provided
```

**Multiple Methods**:
```python
target_payment = "Orange Money, Wave, Free Money"
# User chooses payment method on checkout page
```

---

## 🧪 Testing

### Test Environment

```python
PAYTECH_ENV=test
```

- **Test Amount**: Random amount between 100-150 XOF charged (regardless of actual amount)
- **Purpose**: Internal development only
- **Limitation**: Do NOT use for public transactions

### Production Environment

```python
PAYTECH_ENV=prod
```

- **Activation Required**: Contact PayTech support at contact@paytech.sn
- **Documents Needed**:
  - NINEA number
  - ID card or passport
  - Company registration
  - Company status documents
  - Proof of address
  - Phone number
  - Business activity details

---

## 📊 Monitoring & Logging

### Check Payment Status

```python
paytech_service = PaytechService()
status = paytech_service.get_payment_status(token_payment='40j515fgrkynl56hi')
```

### Logs Location

- **Django Console**: Check terminal output
- **Log Files**: Configure in `settings.py`:
  ```python
  LOGGING = {
      'version': 1,
      'handlers': {
          'file': {
              'class': 'logging.FileHandler',
              'filename': 'paytech.log',
          },
      },
      'loggers': {
          'appsponsor': {
              'handlers': ['file'],
              'level': 'INFO',
          },
      },
  }
  ```

---

## 🛠️ Troubleshooting

### Common Issues

1. **"Erreur de connexion à PayTech"**
   - ✅ Check internet connection
   - ✅ Verify API keys in `.env`
   - ✅ Ensure `PAYTECH_BASE_URL=https://paytech.sn/api`

2. **"Invalid signature" in IPN**
   - ✅ Verify API keys match exactly
   - ✅ Check IPN URL is accessible (no firewall blocking)
   - ✅ Ensure CSRF exempt on IPN endpoint

3. **"Compte non activé"**
   - ✅ You're trying to use `env=prod` without account activation
   - ✅ Contact PayTech: +221 77 125 57 99

4. **User phone_number not found**
   - ✅ Add `phone_number` field to User model or UserProfile
   - ✅ Or disable auto-fill by not passing `user` parameter

---

## 🔐 Security Best Practices

1. **Never expose API keys**:
   - ✅ Keep keys in `.env` file
   - ✅ Add `.env` to `.gitignore`

2. **Always verify IPN**:
   - ✅ Use HMAC-SHA256 verification
   - ✅ Never trust IPN data without verification

3. **Use HTTPS**:
   - ✅ All URLs (IPN, success, cancel) must use HTTPS

4. **Rate Limiting**:
   - ✅ Implement rate limiting on payment endpoints

---

## 📞 Support

### PayTech Support

- **Email**: contact@paytech.sn
- **Phone**: +221 77 125 57 99
- **Documentation**: https://doc.intech.sn/doc_paytech.php

### Your Development Team

- Check logs in `paytech.log`
- Review PayTech service in `appsponsor/paytech_service.py`
- Inspect IPN handler in `appsponsor/views.py`

---

## 🔄 Migration from Pay2Up

If you're migrating from Pay2Up:

1. **Backup your database**:
   ```bash
   python manage.py dumpdata > backup.json
   ```

2. **Test in parallel**:
   - Keep both payment systems running
   - Direct test transactions to PayTech
   - Monitor for issues

3. **Switch completely**:
   - Replace views as instructed above
   - Update `.env` with PayTech credentials
   - Remove Pay2Up code

---

## ✅ Implementation Checklist

- [ ] Register PayTech account
- [ ] Get API keys
- [ ] Update `.env` with credentials
- [ ] Test in `env=test` mode
- [ ] Replace views.py with PayTech version
- [ ] Enable IPN endpoint in urls.py
- [ ] Test full payment flow
- [ ] Verify IPN notifications work
- [ ] Request production activation
- [ ] Switch to `env=prod`
- [ ] Monitor first real transactions

---

## 📝 Additional Resources

- **PayTech Dashboard**: https://paytech.sn/dashboard
- **Test Postman Collection**: Download from docs
- **SDK Downloads**: Available for PHP, Java, Flutter, React Native
- **Community Support**: Check PayTech documentation for latest updates

---

**Last Updated**: 2026-02-21
**Based on**: PayTech API Documentation v6.0.3
