How to save stripe PaymentIntent customer ID for future charges?

  laravel, php, stripe-payments

I’m trying to save and retrieve stripe customer id for future charges, I use payment intent and so far everything works fine, I can charge a customer and attach the card, but I don’t know how to retrieve the customer id outside of the payment intent function.
this is the payment intent code where I charge the user for the first time and attach the card:

   public function checkitout (Request $request, $subscription_id)
    {
        StripeStripe::setApiKey('sk_test_XXXXXXXXXXXXXX');
        header('Content-Type: application/json');

        try {
            $subscription = Subscription::findByUid($subscription_id);
            // retrieve JSON from POST body
            $json_str = file_get_contents('php://input');
            $json_obj = json_decode($json_str);
            $customer = StripeCustomer::create();
            $paymentIntent = StripePaymentIntent::create([
                'amount' => $subscription->plan->stripePrice(),
                'currency' => 'usd',
                'customer' => $customer->id,
                'setup_future_usage' => 'off_session',
                'description' => "$subscription_id",

            ]);
        

            $output = [
                'clientSecret' => $paymentIntent->client_secret,
            ];

            echo json_encode($output);
        } catch (Error $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }

I use webhooks to activate the membership (and I stored the subscription id in description … but this doesn’t matter in this case):

case 'charge.succeeded':
                $paymentIntent = $event->data->object;
                $getsubscriptionid = $paymentIntent->description;
                $subscription = Subscription::findByUid($getsubscriptionid);
                $subscription->start();
break;

as you can see the customer gets created in the payment intent, I don’t know how to store it in a database and retrieve it later, or if there is another method to do that?
Thank you

Source: Laravel

Leave a Reply