Laravel проверка полосы - PullRequest
       0

Laravel проверка полосы

0 голосов
/ 14 февраля 2020

Здравствуйте, я использую пакет Stripe (composer Требуется Stripe / Stripe- php) для интеграции бегства оплаты полосы на моем веб-сайте. Я использую этот код для платного пользователя.

   public function stripe(Request $request){
    $customer = json_decode(Session::get('customer'));
    if (Cart::getContent() == null || $customer == null){
        return redirect()->back();
    }
    $cartCollection = Cart::getContent();
    $shippingCost=0;
    foreach ($cartCollection as $getSingleCartProduct){
        $shippingCost += $getSingleCartProduct->attributes->unit_charge;
    }
    $total_price =Cart::getSubTotal()+$shippingCost;

    $error = '';
    $success = '';
    $currency = Currency::find('1');

    Stripe::setApiKey("sk_live_xxxxxxxxxxxxxxxxxxxxxxxx");
    if (Cart::getContent()){
        $charge = Charge::create([
            'amount' => $total_price * 100,
            'currency' => 'usd',
            'source' => $request->stripeToken,
            'receipt_email' => $request->email,
        ]);
    }



    $cartCollections= Cart::getContent();
    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()){
        $delete_carts = Cart::getContent();
        foreach ($delete_carts as $delete_cart){
            Cart::remove($delete_cart->id);
        }
        return redirect()->route('charge.complete')->with('success', 'Yor order successfully placed');
    }else{
        return redirect()->route('charge.complete')->with('success', 'Invalid Activity!');
    }
}

Он будет работать, когда карта действительна, иметь достаточное количество. Но когда карта недействительна, я не могу ее показать. Laravel показывает ошибку по умолчанию (на карте недостаточно баланса) вот мой полный код

1 Ответ

1 голос
/ 14 февраля 2020

Я реорганизовал часть вашего кода, повторно использовал извлеченный 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

...