简体   繁体   中英

Given a Stripe payment intent ID, how can I find the checkout session ID?

For a successful payment, how can I find the related checkout session ID given the payment intent ID?

In that case you would just use the Checkout Session List API and pass in the Payment Intent ID for the payment_intent parameter. That will return an array with the related Checkout Session in it.

Given a Stripe payment intent ID, you can find the checkout session ID like so:

From Stripe CLI

stripe checkout sessions list --payment-intent=pi_abc --limit=1 --expand=data.line_items

Line items

Taking it a step further, this PHP example will return the line items for a given payment intent:

/**
 * Returns an array of line items. On each, can access properties `price`,
 * `quantity` and more. e.g.:
 * - getLinesItemsFromPaymentIntent('pi_3MCJzWBkWO5ojRjq1zBX6gA3')[0]->price->id
 * - getLinesItemsFromPaymentIntent('pi_3MCJzWBkWO5ojRjq1zBX6gA3')[0]->quantity
 */
function getLinesItemsFromPaymentIntent($payment_intent_id) {
    $stripe = new \Stripe\StripeClient(
        getenv('STRIPE_API_SECRET_KEY')
    );

    // https://stripe.com/docs/api/checkout/sessions/list?lang=cli#list_checkout_sessions-payment_intent
    $session = $stripe->checkout->sessions->all([
        'limit' => 1,
        'payment_intent' => $payment_intent_id,
        'expand' => ['data.line_items'],
    ]);

    return $session->data[0]->line_items->data ?? false;
}

Limitations

In passing, note that this will only work with products ordered through a Stripe Payment Link AKA Stripe-hosted payment page AKA checkout sessions in the API.

If/when using your own payment form, you will need to use yet another approach to retrieve line items / what was ordered by your customer

Ergo, the way to make things more consistent when using multiple types of order forms is to set/read metadata on the Subscription, payment_intent_data or whatever handles your orders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM