Home » Php » php – Laravel stripe validation

php – Laravel stripe validation

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hello i am using stripe package(composer require stripe/stripe-php) for integrate stripe payment getaway in my website. I am using this code for charge user.

   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!');
    }
}

It will work when the card is valid, have sufficient amount. But when the card is invalid i can’t show it. Laravel showing it’s default error(card not have sufficient balance)
here is my full code

How to&Answers:

I have refactored some of your code, reused the fetched Cart::getContent and added some error handling. Hopefully this error handling will give you more control when it comes to displaying the errors the way you like.

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()]);
    }
}

In your view, add the following snippet to display the error message:

@if($errors->any())
<p>Error: {{$errors->first()}}</p>
@endif

If you want to handle more possible exceptions, you can take a look at the available exception types in Stripe’s documentation: https://stripe.com/docs/api/errors/handling