Search code examples
javascriptphpstripe-paymentsslim

how do we retrive checkout session in stripe success page


This is my server side code

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

use Slim\Http\Request;
use Slim\Http\Response;
use Stripe\Stripe;




require 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();

require './config.php';

$app = new \Slim\App;

$app->add(function ($request, $response, $next) {
    Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
    return $next($request, $response);
});

$app->get('/', function (Request $request, Response $response, array $args) {
  return $response->write(file_get_contents(getenv('STATIC_DIR') . '/index.html'));
});

$app->post('/checkout_sessions', function(Request $request, Response $response) use ($app)  {
  $params = json_decode($request->getBody());
  $payment_method_types = [
    'usd' => ['card'],
    'eur' => ['card'],
    'cad' => ['card']
  ];
  $products = [
    'cause-a' => 'prod_KP3YP2a3IGYqsb',
    'cause-b' => 'prod_KP3iZRGcEjn5W8',
  ];

  $session = \Stripe\Checkout\Session::create([
    'success_url' => 'http://localhost:4242/success.html?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => 'http://localhost:4242/?cancel=true',
    'mode' => 'payment',
    'payment_method_types' => $payment_method_types[$params->currency],
    'metadata' => [
      'cause' => $params->cause,
      'currency' => $params->currency,
    ],
    'submit_type' => 'donate',
    'line_items' => [[
      'price_data' => [
        'currency' => $params->currency,
        'product' => $products[$params->cause],
        'unit_amount' => $params->amount,
      ],
      'quantity' => 1,
    ]]
  ]);

  return $response->withJson([
    'id' => $session->id
  ]);
});

$app->get('/order', function (Request $request, Response $response) {
  $id = $_GET['sessionId'];
  $checkout_session = \Stripe\Checkout\Session::retrieve($id);

  echo json_encode($checkout_session);
});





$app->run();

this is the success page with javascript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Confirm</title>
</head>
<body>
    <div id="main">
        <div id="checkout">
            <div id="payment-forum">
                <h1>Success</h1>
                 payment status: <span id="payment-status"></span>
                 <pre>
                    
                 </pre>
            </div>
        </div>
    </div>
</body>
<script>
    var paymentStatus = document.getElementById('payment-status');
    var urlParams = new URLSearchParams(window.location.search);
    var sessionId = urlParams.get("session_id")
    if (sessionId) {
    fetch("/order?sessionId=" + sessionId).then(function(result){
        return result.json()
    }).then(function(session){
        var sessionJSON = JSON.stringify(session, null, 2);
        document.querySelector("pre").textContent = sessionJSON;
    }).catch(function(err){
        console.log('Error when fetching Checkout session', err);
    });
    }
</script>
</html>

i need help with product detail , customer name , amount on success page and if possible payment paid or not paid status on it.... cant find any tutorial on it or any detail step by step guide on it

i am close but cant get it to bullseyes please help me with it

yeah on success page all i get is payment status and blank


Solution

  • Looks like here is what happened:

    1. Your Checkout Session defined success_url to success.html
    2. Your success.html fired another request to "/success?session_id=xxx"
    3. Your backend handled this with $app->get('/success', function...

    It could be confusing to name both HTML in step 2 and the handling URL in step 3 as "success". You may want to use a different name such as "success" and "get-checkout-session" like Stripe example on Github. After that, debug your server log on step 3 to see whether you got the session id correctly and have retrieved the Customer Id.

    There is more information to extract from a CheckoutSession. See Stripe's API Reference on available properties. You probably want to expand its payment_intent to see the amount and payment status.