skip to Main Content

My checkout flow requires a PaymentIntent to be created only once per order. Thus its ID is basically the same as the order ID. The API documentation is a bit unclear regarding the behavior of create() and retrieve(). So, what is the correct way to do this?

This best reflects the intention but doesn’t work:

$stripeIntentId = "pi_{$order->id}";
if (!$stripe->paymentIntents->retrieve($stripeIntentId, []))
{
    $stripe->paymentIntents->create([
        'id' => $stripeIntentId,
        'amount' => $payAmount,
        'currency' => $payCurrency,
        'description' => $payDescription,
        'automatic_payment_methods' => ['enabled' => true],
        'metadata' => ['order_id' => $order->id],
    ]);
}

So I’m now pondering this, although this seems a bit overkill for the purpose.

$stripeIntentId = "pi_{$order->id}";
try
{
    $stripe->paymentIntents->retrieve($stripeIntentId, []);
} catch (Exception $e)
{
    $stripe->paymentIntents->create([
        'id' => $stripeIntentId,
        'amount' => $payAmount,
        'currency' => $payCurrency,
        'description' => $payDescription,
        'automatic_payment_methods' => ['enabled' => true],
        'metadata' => ['order_id' => $order->id],
    ]);
}

I could not yet test this, but wonder if there is a more elegant way to do this. Exception handling is clearly not the best tool here.

2

Answers


  1. I’d recommend just updating your database at the time of PaymentIntent creation. So, for a return customer/order, you query your database to check if a a PaymentIntent ID associated to the order ID, otherwise you create one. As you noted, you shouldn’t use the Stripe API to help you determine whether the PaymentIntent exists or not.

    Login or Signup to reply.
  2. You can’t manipulate Stripe object IDs (except Coupons, for some reason).

    The Payment Intent ID is going to be randomly generated once you create it.

    What you should do is use metadata, like this:

    //Check for existing payments with metadata
    $stripe->paymentIntents->search([
      'query' => 'metadata['order_id']:'6735'',
    ]);  
    //If none, proceed to creation
    $stripe->paymentIntents->create([
            'amount' => $payAmount,
            'currency' => $payCurrency,
            'description' => $payDescription,
            'automatic_payment_methods' => ['enabled' => true],
            'metadata' => ['order_id' => '6735'],
        ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search