Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Reached's avatar

Charge Stripe customer later method help and refactoring

Hi guys,

So im trying to rewrite a method, and I somehow messed it all up in the process, so I figured I might as well get some feedback from here on how to improve the code, while I also try to make it work again.

Essentially I want to check if the user who is trying to buy exists, otherwise it should create it. At the same time it should create a new stripe customer, so I can charge them later.

public function verifyPayment(Request $request)
    {
        // Set your secret key: remember to change this to your live secret key in production
        // See your keys here https://dashboard.stripe.com/account/apikeys
        Stripe::setApiKey(env('STRIPE_API_KEY'));

        // Get the details submitted by the form
        $email = $request->input('email');
        $first_name = $request->input('first_name');
        $last_name = $request->input('first_last');
        $zip = $request->input('zip');
        $street = $request->input('street');
        $sendSms = $request->input('sendSms');
        $countryCode = $request->input('country');

        $user = User::where('email', '=', $email)->firstOrFail();

        if ($user->exists() and $user->whereNotNull('stripe_billing_id')) {

            $billing_id = $user->stripe_billing_id;

        } else {
            $customer = Customer::create([
                'source' => $request->input('stripeToken'),
                'email' => $email
            ]);

            User::firstOrCreate([
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email,
                'zip' => $zip,
                'street' => $street,
                'stripe_customer_id' => $customer->id
            ]);

            $billing_id = $customer->id;
        }

        // Get the amount total in the smallest denominator
        $amount = $this->calculateAmount($countryCode);

        Event::fire(new OrderWasPlaced($amount, $billing_id, $sendSms));

        return 'Your order is now pending. The money will not be taken from your account before the products has been shipped.';
    }

Right now I get an error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'stripe_billing_id' cannot be null (SQL: insert into `orders` (`amount`, `stripe_billing_id`, `sendSms`, `user_id`, `updated_at`, `created_at`) values (1562500, , 0, 1, 2016-02-22 20:13:36, 2016-02-22 20:13:36))

Any pointers here would be helpful, if you have some general feedback on code structure etc. I am also listening as I am still learning this stuff :)..

0 likes
0 replies

Please or to participate in this conversation.