# 🚨 Troubleshooting: "Erreur technique lors du don"

## Problem
When trying to make a donation on production (cPanel), users see:
**"Erreur technique lors du don."**

## Root Causes (in order of likelihood)

### 1. ❌ Missing PayTech Environment Variables
The `.env` file in cPanel doesn't have PayTech credentials configured.

**Solution:**
1. Log into cPanel File Manager
2. Navigate to your application root directory
3. Find or create `.env` file
4. Add these variables (get values from PayTech dashboard):

```bash
PAYTECH_API_KEY=your_actual_api_key_here
PAYTECH_API_SECRET=your_actual_api_secret_here
PAYTECH_ENV=prod
PAYTECH_BASE_URL=https://paytech.sn/api
PAYTECH_SUCCESS_URL=https://sponsor.enfantsoleilmonde.org/payment/success/
PAYTECH_CANCEL_URL=https://sponsor.enfantsoleilmonde.org/payment/cancel/
PAYTECH_IPN_URL=https://sponsor.enfantsoleilmonde.org/payment/ipn/

**Security Note**: Success and cancel pages are now protected against direct access. Users must come from PayTech with valid payment parameters (token or ref_command). Direct access attempts will redirect to the home page and be logged.
```

5. **Important:** Replace with your actual PayTech credentials from https://paytech.sn
6. Restart your application (passenger_wsgi.py restart)

### 2. ❌ Incorrect Callback URLs
The URLs in `.env` don't match your actual domain.

**Solution:**
Make sure all URLs use `sponsor.enfantsoleilmonde.org` (not `enfantsoleilmonde.org`):
- Success URL: `https://sponsor.enfantsoleilmonde.org/payment/success/`
- Cancel URL: `https://sponsor.enfantsoleilmonde.org/payment/cancel/`
- IPN URL: `https://sponsor.enfantsoleilmonde.org/payment/ipn/`

### 3. ❌ Python Packages Missing
Required packages (`requests`, `python-dotenv`) not installed on production.

**Solution:**
SSH into cPanel or use Terminal in cPanel:
```bash
cd /path/to/your/app
pip install -r requirements.txt
```

### 4. ❌ Django Not Loading .env File
The `.env` file exists but Django isn't reading it.

**Solution:**
Verify in your cPanel Python app setup:
1. Check the application startup file
2. Ensure `.env` is in the same directory as `settings.py`
3. Restart the application

## 🔍 Debugging Steps

### Step 1: Check Configuration
Upload and run the diagnostic script:

```bash
cd /path/to/your/app
python check_config.py
```

This will check:
- ✅ PayTech API credentials
- ✅ Callback URLs
- ✅ Database connection
- ✅ PayTech API connectivity

### Step 2: Check Application Logs
In cPanel, check:
- **Error logs:** Usually in `logs/` or accessible via cPanel Error Log viewer
- Look for Python tracebacks or exceptions
- Search for "PayTech" or "donation" errors

### Step 3: Test PayTech API Manually
From cPanel Terminal or SSH:

```python
python manage.py shell

# Run these commands:
from django.conf import settings
print(f"API Key: {settings.PAYTECH_API_KEY}")
print(f"API Secret: {settings.PAYTECH_API_SECRET}")
print(f"IPN URL: {settings.PAYTECH_IPN_URL}")

# Test API connection:
from appsponsor.paytech_service import PaytechService
service = PaytechService()
print("Service initialized successfully!")
```

### Step 4: Check Browser Console
1. Open the donation page in production
2. Press F12 (Developer Tools)
3. Go to Console tab
4. Try to make a donation
5. Look for error messages (red text)

Expected output:
- ✅ `SUCCESS Data received from server:` → Working
- ❌ `Donation failed:` → Check error details

### Step 5: Check Network Tab
In Browser Developer Tools:
1. Go to **Network** tab
2. Try to make a donation
3. Click on the POST request
4. Check:
   - **Status Code:** Should be 200, not 500 or 404
   - **Response:** Should be valid JSON
   - **Response body:** Look for error messages

## 🔧 Quick Fixes

### Fix 1: Create .env file in cPanel
```bash
# In cPanel File Manager or via SSH:
cd /home/your-username/public_html/projectesm
nano .env

# Paste your environment variables
# Save: Ctrl+O, Enter
# Exit: Ctrl+X
```

### Fix 2: Update Production Settings
Copy the template:
```bash
cp .env.production .env
# Then edit .env with your actual credentials
nano .env
```

### Fix 3: Restart Application
In cPanel:
- Find "Setup Python App"
- Click on your application
- Click "Restart" button

OR via command line:
```bash
touch tmp/restart.txt
```

## ✅ Verification

After applying fixes:
1. Run `python check_config.py` → Should show all green ✅
2. Try making a test donation
3. Check browser console for success message
4. Should redirect to PayTech payment page

## 🆘 Still Not Working?

### Get Better Error Messages
The code has been updated with better error logging. After redeploying:
1. Try making a donation
2. The error message should now show the actual problem
3. Check example: "❌ Erreur: 'NoneType' object has no attribute 'get'"

### Manual Test via Django Shell
```python
python manage.py shell

from appsponsor.models import Donation
from django.contrib.auth.models import User
from appsponsor.paytech_service import PaytechService
import time

# Find a user
user = User.objects.first()

# Create test donation
donation = Donation.objects.create(
    user=user,
    amount=1000,
    created_by='test',
    updated_by='test'
)

# Test PayTech service
service = PaytechService()
response = service.request_payment(
    item_name=f"Test Don",
    item_price=1000,
    ref_command=f"TEST_{int(time.time())}",
    command_name="Test donation",
    custom_field={'test': True},
    target_payment="Orange Money"
)

print(response)
# Should show success=1 and redirect_url if working
```

## 📞 Contact Support

If none of the above works:
1. Collect error logs from cPanel
2. Run `python check_config.py` and save output
3. Check browser console errors
4. Contact PayTech support at support@paytech.sn

## Common Error Messages

| Error | Cause | Solution |
|-------|-------|----------|
| `'NoneType' object has no attribute` | Environment variable not set | Add to .env file |
| `Connection refused` | PayTech API unreachable | Check internet, firewall |
| `Invalid API credentials` | Wrong API_KEY or API_SECRET | Verify credentials in PayTech dashboard |
| `Invalid IPN URL` | URL not accessible | Make sure URL is HTTPS and publicly accessible |
| `HMAC verification failed` | Wrong API_SECRET | Double-check API_SECRET |

## Prevention

To avoid this in future deployments:
1. ✅ Always use `.env.production` template
2. ✅ Run `python check_config.py` before deploying
3. ✅ Test donations in test mode first (PAYTECH_ENV=test)
4. ✅ Keep error logs accessible via cPanel
5. ✅ Document your PayTech credentials securely
