7.1 KiB
7.1 KiB
PhonePe Payment Gateway Integration
Complete guide to integrate PhonePe payments in LuckyChit app.
🚀 Features
- ✅ Direct UPI Payments - Members pay installments via PhonePe
- ✅ Secure Transactions - SHA256 checksum verification
- ✅ Real-time Status - Instant payment confirmation
- ✅ Auto-recording - Payments automatically recorded in system
- ✅ Refund Support - Managers can initiate refunds
- ✅ Transaction History - Complete payment audit trail
📋 Prerequisites
1. PhonePe Merchant Account
- Sign up at PhonePe Business Portal
- Complete KYC verification
- Get your merchant credentials:
- Merchant ID (e.g.,
M1234567890) - Salt Key (secret key for checksum)
- Salt Index (usually
1)
- Merchant ID (e.g.,
2. Backend Setup
Install Dependencies
cd backend
npm install axios crypto
Environment Variables
Add to backend/.env:
# PhonePe Configuration
PHONEPE_MERCHANT_ID=your_merchant_id_here
PHONEPE_SALT_KEY=your_salt_key_here
PHONEPE_SALT_INDEX=1
PHONEPE_ENV=sandbox # Change to 'production' for live
# PhonePe URLs
PHONEPE_REDIRECT_URL=https://chitfund.deepteklabs.com/payment/callback
PHONEPE_CALLBACK_URL=https://chitfund.deepteklabs.com/api/payments/phonepe/callback
API Endpoints Created
| Endpoint | Method | Description |
|---|---|---|
/api/payments/phonepe/initiate |
POST | Start payment |
/api/payments/phonepe/callback |
POST | PhonePe webhook |
/api/payments/phonepe/verify |
POST | Verify payment |
/api/payments/phonepe/status/:id |
GET | Check status |
/api/payments/phonepe/refund |
POST | Refund payment |
3. Flutter App Setup
Install Dependencies
Add to luckychit/pubspec.yaml:
dependencies:
url_launcher: ^6.2.1 # For opening PhonePe app
Initialize Service
In luckychit/lib/app.dart:
import 'core/services/phonepe_service.dart';
// In initServices()
Get.put(PhonePeService());
Usage in UI
import 'package:luckychit/interfaces/member/member_payment_dialog.dart';
// Show payment dialog
showDialog(
context: context,
builder: (context) => MemberPaymentDialog(
group: chitGroup,
member: currentMember,
month: DateTime.now().month,
year: DateTime.now().year,
),
);
🔄 Payment Flow
Step 1: Member Initiates Payment
Member Dashboard → Pay Installment → Select Month/Year → Pay with PhonePe
Step 2: Backend Creates Payment Request
- Validates member and group
- Creates pending payment record
- Generates PhonePe payload with checksum
- Returns payment URL to app
Step 3: PhonePe Payment
- App opens PhonePe app/web
- Member completes payment
- PhonePe redirects back to app
Step 4: Verification
- PhonePe sends webhook to callback URL
- Backend verifies checksum
- Checks payment status with PhonePe API
- Updates payment record to 'success'
Step 5: Confirmation
- App shows success message
- Member sees updated payment status
- Manager gets notification
🛠 Testing
Sandbox Mode
PhonePe provides test credentials for sandbox:
PHONEPE_ENV=sandbox
PHONEPE_MERCHANT_ID=PGTESTPAYUAT
PHONEPE_SALT_KEY=099eb0cd-02cf-4e2a-8aca-3e6c6aff0399
PHONEPE_SALT_INDEX=1
Test Cards
| Card Number | Behavior |
|---|---|
4111 1111 1111 1111 |
Success |
4000 0000 0000 0002 |
Declined |
5555 5555 5555 4444 |
Timeout |
Test UPI IDs
success@upi- Successful paymentfailure@upi- Failed payment
🔐 Security
Checksum Generation
// Payload + Endpoint + Salt Key → SHA256
const string = base64Payload + endpoint + saltKey;
const checksum = sha256(string) + '###' + saltIndex;
Checksum Verification
// Verify callback from PhonePe
const [checksum, saltIndex] = header.split('###');
const string = base64Response + saltKey;
const calculatedChecksum = sha256(string);
return checksum === calculatedChecksum;
📊 Payment States
| Status | Description |
|---|---|
pending |
Payment initiated |
success |
Payment completed |
failed |
Payment declined/error |
cancelled |
Refunded |
🔄 Refund Process
Manager Initiates Refund
// From manager dashboard
final success = await phonePeService.initiateRefund(
transactionId: 'TXN_123',
amount: 10000.00,
reason: 'Duplicate payment',
);
Backend Processes
- Validates manager permissions
- Checks payment is 'success' status
- Creates refund request with PhonePe
- Updates payment status to 'cancelled'
📱 Deep Links (Optional)
Android
Add to AndroidManifest.xml:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="luckychit"
android:host="payment" />
</intent-filter>
iOS
Add to Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>luckychit</string>
</array>
</dict>
</array>
🐛 Troubleshooting
Issue: Payment status stuck on "pending"
Solution:
- Check PhonePe callback URL is publicly accessible
- Verify webhook is reaching your server
- Check server logs for callback errors
Issue: Checksum mismatch
Solution:
- Verify salt key and index are correct
- Ensure no extra spaces in environment variables
- Check endpoint path matches exactly
Issue: Payment succeeds but not recorded
Solution:
- Check database connection
- Verify Payment model update logic
- Check for transaction conflicts
📞 PhonePe Support
- Docs: https://developer.phonepe.com/
- Support: https://business.phonepe.com/support
- Status: https://status.phonepe.com/
🚀 Going Live
Checklist
- Get production merchant credentials
- Set
PHONEPE_ENV=production - Update callback URLs to production domain
- Test with small real payments
- Monitor first few transactions closely
- Set up error alerting
- Document transaction IDs
Production Environment
PHONEPE_ENV=production
PHONEPE_MERCHANT_ID=your_production_merchant_id
PHONEPE_SALT_KEY=your_production_salt_key
PHONEPE_REDIRECT_URL=https://chitfund.deepteklabs.com/payment/callback
PHONEPE_CALLBACK_URL=https://chitfund.deepteklabs.com/api/payments/phonepe/callback
💡 Best Practices
- Always verify payments - Never trust client-side status
- Log all transactions - Keep audit trail
- Handle timeouts - Payment might succeed even if timeout
- Retry verification - Network issues can cause false negatives
- Notify users - Send confirmations via SMS/email
- Monitor refunds - Track refund reasons and patterns
📈 Analytics
Track these metrics:
- Payment success rate
- Average payment time
- Failed payment reasons
- Refund frequency
- Member payment patterns
Need Help? Contact PhonePe support or check the developer documentation.