Gabotronix
10 months ago

Catching errors with stripe?

Posted 10 months ago by Gabotronix

Hi everybody, I'm playing with Stripe in laravel, I have my controller function where I create a customer and a source, now I was wondering how could I catch any error that occurs when trying to create customer/source, I would like to return back an error message telling the user what went wrong.

I added a try catch block but tbh I have never used try catch before, is it the best way to do this? How can I get error message?

This is my controller function:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Customer;

class StripeController extends Controller
{
    public function createCustomerAndSource(Request $request){

        try
        {
            Stripe::setApiKey(config('services.stripe.secret'));

            $customer = Customer::create([
                "email" => $request->input('email'),
                "source" => $request->input('sourceId'),
            ]);

            $user = new User;
            $user->name = $request->input('name');
            $user->password = bcrypt($request->input('password'));
            $user->stripeCustomerId = $customer->id;
            $user->save();

            Auth::login($user);

            return response()->json([
                'message' => 'It worked!',
            ]);

        }
        catch(Exception $e)
        {
            return response()->json([
                'message' => 'Oops, something went wrong!',
            ]);

        }
   
    }

Please sign in or create an account to participate in this conversation.