Checkout: redirectToCheckout

Legacy client/server stripe.redirectToCheckout integration

⚠️ Note: This integration is not production ready and should only be used as a reference.

⚙️ Integration

🧑‍💻 Code

<?php

if (isset($_GET['createCheckoutSession'])) {
  $stripeConfiguration = [
    'api_key' => 'sk_•••',
    'stripe_version' => '2023-10-16',
  ];
  
  $stripe = new \Stripe\StripeClient($stripeConfiguration);
  
  $checkoutSession = $stripe->checkout->sessions->create([
    'mode' => 'payment',
    'line_items' => [
      [
        'price_data' => [
          'currency' => 'usd',
          'product_data' => [
            'name' => 'Product name',
          ],
          'unit_amount' => 4200,
        ],
        'quantity' => 1,
      ],
    ],
    'success_url' => 'https://4242.io/test/checkout/?session={CHECKOUT_SESSION_ID}',
  ]);

  header('Content-Type: application/json');
  echo json_encode([
    'checkoutSessionID' => $checkoutSession->id,
  ]);
  exit;
}
<script src="https://js.stripe.com/v3/"></script>

<p><button id="checkout">Go to Checkout</button></p>
const outputElement = document.querySelector('#output');

const stripe = Stripe('pk_test_51O2hxMC4JnNRtz8VToJJbGHrFTPPr6TkP09h7ql3YJaqpNcxoSNxtk38glyzi9VrZKStns858YynOO2ZyGmU7VRi00CIUWuUdk');

async function goToCheckout() {
  const result = await fetch('?createCheckoutSession');
  
  const response = await result.json();
  
  const redirect = await stripe.redirectToCheckout({
    sessionId: response.checkoutSessionID,
  });
  
  if (redirect.error) {
    outputElement.textContent = 'Error redirecting to Checkout: ' + JSON.stringify(redirect.error, true, 2);
  }
}

const checkoutButton = document.querySelector('#checkout');

checkoutButton.addEventListener('click', event => {
  goToCheckout();
});