implemented razorpay payment successfully

This commit is contained in:
Manish 2025-10-30 17:23:00 +05:30
parent 70fcc2e662
commit c556df1f80
2 changed files with 45 additions and 66 deletions

View File

@ -14,87 +14,64 @@ class PaymentController with ChangeNotifier {
/// ============================== /// ==============================
/// START PAYMENT (Safe init) /// START PAYMENT (Safe init)
/// ============================== /// ==============================
Future<bool> startPayment({ Future<void> startPayment({
required double amount, required double amount,
required String description, required String description,
required BuildContext context, required BuildContext context,
}) async { }) async {
//_context = context;
isProcessing = true;
notifyListeners();
logSafe("🟢 Starting payment for ₹$amount - $description");
// Clear any old instance (prevents freeze on re-init)
_cleanup();
// Create order first (no login dependency)
Map<String, dynamic>? result;
try { try {
result = await _paymentService isProcessing = true;
.createOrder(amount)
.timeout(const Duration(seconds: 10));
} catch (e) {
logSafe("⏱️ API Timeout or Exception while creating order: $e",
level: LogLevel.error);
}
if (result == null) {
_showError("Failed to connect to server or timeout.");
isProcessing = false;
notifyListeners(); notifyListeners();
return false;
}
final orderId = result['data']?['orderId']; // Step 1: Create payment order
final key = result['data']?['key']; final result = await _paymentService.createOrder(amount);
if (orderId == null || key == null) { logSafe("🧩 Raw response in PaymentController: $result");
_showError("Invalid response from server.");
logSafe("Invalid response from server.");
isProcessing = false; // Step 2: Validate result before accessing keys
notifyListeners(); if (result == null) {
return false; _showError("Failed to create order. Server returned null response.");
} isProcessing = false;
notifyListeners();
return;
}
// Safe initialization of Razorpay (deferred) // Step 2: Handle both wrapped and unwrapped formats
try { final data = result['data'] ?? result;
logSafe("🟡 Initializing Razorpay instance..."); final orderId = data?['orderId'];
_razorpay = Razorpay(); final key = data?['key'];
_razorpay?.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay?.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay?.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
logSafe("✅ Razorpay instance initialized successfully.");
} catch (e) {
logSafe("❌ Razorpay init failed: $e", level: LogLevel.error);
_showError("Payment system initialization failed.");
isProcessing = false;
notifyListeners();
return false;
}
// Prepare payment options if (orderId == null || key == null) {
final options = { _showError("Invalid response from server. Missing orderId or key.");
'key': key, logSafe("💥 Invalid response structure: $result");
'amount': (amount * 100).toInt(), isProcessing = false;
'name': 'Your Company Name', notifyListeners();
'description': description, return;
'order_id': orderId, }
'theme': {'color': '#0D47A1'},
'timeout': 120, // seconds // Step 3: Initialize Razorpay if needed
}; _razorpay ??= Razorpay();
_razorpay!.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay!.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay!.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
// Step 4: Open Razorpay checkout
final options = {
'key': key,
'amount': (amount * 100).toInt(), // Razorpay expects amount in paise
'name': 'Marco',
'description': 'Subscription Payment',
'order_id': orderId,
'prefill': {'contact': '9999999999', 'email': 'test@marco.com'},
};
try {
logSafe("🟠 Opening Razorpay checkout with options: $options"); logSafe("🟠 Opening Razorpay checkout with options: $options");
_razorpay!.open(options); _razorpay!.open(options);
return true; } catch (e, s) {
} catch (e) { _showError("Payment initialization failed. Please try again.");
logSafe("❌ Error opening Razorpay: $e", level: LogLevel.error); logSafe("💥 Exception in startPayment: $e\n$s");
_showError("Error opening payment gateway."); } finally {
_cleanup();
isProcessing = false; isProcessing = false;
notifyListeners(); notifyListeners();
return false;
} }
} }

View File

@ -7,6 +7,8 @@ class PaymentService {
try { try {
logSafe("🟢 Calling createPaymentOrder API with amount: ₹$amount"); logSafe("🟢 Calling createPaymentOrder API with amount: ₹$amount");
final response = await ApiService.createPaymentOrder(amount); final response = await ApiService.createPaymentOrder(amount);
logSafe("🧩 Raw response in PaymentService: $response");
return response; return response;
} catch (e) { } catch (e) {
logSafe("❌ Error in createOrder: $e", level: LogLevel.error); logSafe("❌ Error in createOrder: $e", level: LogLevel.error);