skip to Main Content

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


  1. 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:

    • First collect the input from the user
    • Then create the Checkout Session with the correct metadata
    • Finally redirect the user to the Checkout Session url
    Login or Signup to reply.
  2. 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;

    <html>
    <head>
        <title>Buy cool new product</title>
        <script src="https://js.stripe.com/v3/"></script>
    </head>
    <body>
    <input id="test" type="text" name="event_id">
    <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();
            var xhr = new XMLHttpRequest();
            formData = new FormData();
            formData.append("event_id", document.getElementById("test").value);
    
            xhr.withCredentials = true;
            xhr.addEventListener("readystatechange", function () {
                if (this.readyState === 4) {
                    var response = JSON.parse(this.responseText);
                    if (response.status == "success") {
                        stripe.redirectToCheckout({
                            sessionId: response.sessionId
                        });
                    } else {
                        alert(response.message);
                    }
                }
            });
            xhr.open("POST", "my-payment-page.php");
            xhr.send(formData);
    
        });
    </script>
    </body>
    </html>
    

    Payment Page;

      <?php
        header('Content-Type: application/json; charset=utf-8');
        if (!empty($_POST)) {
        
        //You can validate your post fields on there
        
            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' => $_POST['event_id'],
                    ],
                ],
                'success_url' => 'http://localhost:4242/success',
                'cancel_url' => 'http://example.com/cancel',
            ]);
            die(json_encode(["status" => "success","sessionId" => $session->id]));
        } else {
            die(json_encode(["status" => "failure","message" => "Something went wrong..."]));
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search