I´m trying to integrate a very simple Stripe checkout page with php and JS. I create the session with php and then create a checkout button with JS that redirects to the stripe checkout by the given session-id. I would like to attach metadata to the session which comes from the input field (id: "test"). In the following example the metadata is obviously not updated when the user updates the input field.
<?php
require_once $_SERVER["DOCUMENT_ROOT"].'/NEW/stripe-php-master/init.php';
StripeStripe::setApiKey('sk_test_51NF...');
$stripe = new StripeStripeClient('sk_test_51NFJI...');
$session = StripeCheckoutSession::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => 'T-shirt',
],
'unit_amount' => 2500,
],
'quantity' => 1,
]],
'mode' => 'payment',
'payment_intent_data' => [
'metadata' => [
**'eventId' => '123',**
],
],
'success_url' => 'http://localhost:4242/success',
'cancel_url' => 'http://example.com/cancel',
]);
?>
<html>
<head>
<title>Buy cool new product</title>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<input id="test" type="text">
<button id="checkout-button">Checkout</button>
<script>
var stripe = Stripe('pk_test_51NFJ...');
const btn = document.getElementById("checkout-button")
btn.addEventListener('click', function(e) {
e.preventDefault();
stripe.redirectToCheckout({
sessionId: "<?php
echo $session->id;
?>"
});
});
</script>
</body>
</html>
The code comes from this tutorial:
https://www.youtube.com/watch?v=Ofyhamy76cQ
The problem is also mentioned in this video – but I can´t figure it out.
https://www.youtube.com/watch?v=FOLRATK4pVA&t=1756s
Thanks in advance!
2
Answers
The only way to add metadata to a Checkout Session is to set it when you create the Checkout Session here. So you would need to update your flow:
metadata
First of all, you should separate the pages, get the necessary information with the inputs on the first page, and then redirect them to the payment page.
Yo can use basicly like that (you will edit your code with that idea);
First Page;
Payment Page;