validate([ 'amount' => ['required', 'numeric', 'min:5', 'max:5000'], 'return_url' => ['nullable', 'url', 'max:2048'], ]); $returnUrl = $validated['return_url'] ?? (string) (url()->previous() ?: url('/')); try { $checkoutUrl = $billing->topup( (string) $request->user()->public_id, (float) $validated['amount'], $returnUrl, ); } catch (\Throwable) { $checkoutUrl = ''; } if ($checkoutUrl === '') { if ($request->expectsJson()) { return response()->json(['error' => 'Unable to start payment. Please try again.'], 422); } return back()->with('error', 'Unable to start payment. Please try again.'); } if ($request->expectsJson()) { return response()->json(['checkout_url' => $checkoutUrl]); } return redirect()->away($checkoutUrl); } }