Я реорганизовал часть вашего кода, повторно использовал извлеченный Cart::getContent
и добавил некоторую обработку ошибок. Надеемся, что эта обработка ошибок даст вам больше контроля, когда дело доходит до отображения ошибок так, как вам нравится.
public function stripe(Request $request) {
$cartCollections = Cart::getContent();
$customer = json_decode(Session::get('customer'));
if ($cartCollections == null || $customer == null) {
return redirect()->back()->withErrors(['msg', 'Your session has expired']);
}
$shippingCost = 0;
foreach ($cartCollections as $cartCollection) {
$shippingCost += $cartCollection->attributes->unit_charge;
}
$total_price = Cart::getSubTotal() + $shippingCost;
$currency = Currency::find(1);
Stripe::setApiKey("XXXXXXXXXXXXXXXXXXXXXXXX");
try {
$charge = Charge::create([
'amount' => $total_price * 100,
'currency' => 'usd',
'source' => $request->stripeToken,
'receipt_email' => $request->email,
]);
foreach ($cartCollections as $cartCollection) {
$order = new Order();
$order->name = $cartCollection->name;
$order->price = $cartCollection->price;
$order->quantity = $cartCollection->quantity;
$order->image = $cartCollection->attributes->image;
$order->product_id = $cartCollection->attributes->product_id;
$order->unit_charge = $cartCollection->attributes->unit_charge;
$order->curier_id = $cartCollection->attributes->curier_id;
$order->seller_id = $cartCollection->attributes->seller_id;
$order->buyer_id = \Illuminate\Support\Facades\Auth::user()->id;
$order->color = $cartCollection->attributes->color;
$order->size = $cartCollection->attributes->size;
$order->color_image = $cartCollection->attributes->color_image;
$order->first_name = $customer->first_name;
$order->last_name = $customer->last_name;
$order->email = $customer->email;
$order->address1 = $customer->address1;
$order->address2 = $customer->address2;
$order->country = $customer->country;
$order->state = $customer->state;
$order->zip = $customer->zip;
$order->payment_status = $customer->payment_status;
$order->status ='0';
$order->save();
}
if ($order->save()) {
foreach ($cartCollections as $cartCollection) {
Cart::remove($cartCollection->id);
}
return redirect()->route('charge.complete')->with('success', 'Yor order successfully placed');
}
return redirect()->route('charge.complete')->withErrors(['msg', 'Invalid Activity!']);
} catch (Error\Base $e) {
// change to the route you want to display error
return redirect()->route('charge.complete')->withErrors(['msg', $e->getMessage()]);
} catch (Exception $e) {
// change to the route you want to display error
return redirect()->route('charge.complete')->withErrors(['msg', $e->getMessage()]);
}
}
По вашему мнению, добавьте следующий фрагмент кода для отображения сообщения об ошибке:
@if($errors->any())
<p>Error: {{$errors->first()}}</p>
@endif
Если вы хотите обработать больше возможных исключений, вы можете взглянуть на доступные типы исключений в документации Stripe: https://stripe.com/docs/api/errors/handling