Friday, 1 September 2023

Stripe Javascript Cart

create a session

        \Stripe\Stripe::setApiKey($this->getSecret());
        $data = [
            'payment_method_types' => ['card'],
            'line_items' => [[
                'price_data' => [
                    'currency' => $currencyCode,
                    'product_data' => [
                        'name' => $productName,
                    ],
                    'unit_amount' => $amountWithoutDecimal,
                ],
                'quantity' => $quantity,
            ]],
            'metadata' => [
                "order_id" => $orderID,
                'order_type' => $orderType,
                'user_id'=> $userId,
               
            ],
            'client_reference_id' => "{$orderType}_{$orderID}",
            'mode' => 'payment',
            'success_url' => $this->getSuccessUrl(),
            'cancel_url' => $this->getCancelUrl(),
        ];

        try {
            $session = \Stripe\Checkout\Session::create($data);
            return $session;
        } catch (Exception $e) {
            echo $e->getMessage();
        }

Initiate Cart By JavaScript


<script  type="text/javascript" src="https://js.stripe.com/v3/"></script>
const stripeSession = await fetch("/stripe/create-checkout-session.php", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                //info needed to create session
                body: JSON.stringify({
                    price: myPrice,
                    type: "product",
                    .....
                    
                }),
            })

            const data = await stripeSession.json()

            var stripe = Stripe('{$stripePublicKey}');
            stripe.redirectToCheckout({
                sessionId: data.sessionId,
            })

Process After Payment

When set up successful url, we can use the placeholder: session_id={CHECKOUT_SESSION_ID}

$successUrl = "https://example.com?session_id={CHECKOUT_SESSION_ID}";

when we create session, we can remember strip checkout session id in server side. Do compare in the successful url page and we know it is paid. Then we can do what we want for a successful transaction.

No comments:

Post a Comment