81 lines
2.4 KiB
Plaintext
81 lines
2.4 KiB
Plaintext
|
|
<!DOCTYPE html>
|
||
|
|
<html>
|
||
|
|
<head>
|
||
|
|
<title>Checkout</title>
|
||
|
|
<link rel="stylesheet" href="/styles.css" />
|
||
|
|
</head>
|
||
|
|
<body>
|
||
|
|
<h1>Checkout</h1>
|
||
|
|
<form id="payment-form">
|
||
|
|
<!-- Stripe Elements will inject the Card Element here -->
|
||
|
|
<div id="card-element"></div>
|
||
|
|
<button id="submit-button" type="submit">Pay $19.99</button>
|
||
|
|
</form>
|
||
|
|
|
||
|
|
<!-- Stripe.js -->
|
||
|
|
<script src="https://js.stripe.com/v3/"></script>
|
||
|
|
<script>
|
||
|
|
// Initialize Stripe
|
||
|
|
const stripe = Stripe("pk_test_51QZlMSCHHjDgpHosSrxdAEHgUCBmyhXCihiELaXjxcXzGtIY9Vw1YgOeiJfNpn7P9WkcMj5FWk13cDRavez3HhyN0001mNBtXW");
|
||
|
|
|
||
|
|
// Set up Stripe.js and Elements
|
||
|
|
const elements = stripe.elements();
|
||
|
|
const cardElement = elements.create("card");
|
||
|
|
cardElement.mount("#card-element");
|
||
|
|
|
||
|
|
const paymentForm = document.getElementById("payment-form");
|
||
|
|
paymentForm.addEventListener("submit", async (e) => {
|
||
|
|
e.preventDefault();
|
||
|
|
|
||
|
|
// 1. Create a PaymentMethod
|
||
|
|
const { paymentMethod, error } = await stripe.createPaymentMethod({
|
||
|
|
type: "card",
|
||
|
|
card: cardElement,
|
||
|
|
});
|
||
|
|
|
||
|
|
if (error) {
|
||
|
|
console.error(error);
|
||
|
|
alert(error.message);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 2. Send PaymentMethod ID to server
|
||
|
|
const response = await fetch("/charge", {
|
||
|
|
method: "POST",
|
||
|
|
headers: { "Content-Type": "application/json" },
|
||
|
|
body: JSON.stringify({ paymentMethodId: paymentMethod.id }),
|
||
|
|
});
|
||
|
|
|
||
|
|
const responseData = await response.json();
|
||
|
|
|
||
|
|
if (responseData.error) {
|
||
|
|
console.error(responseData.error);
|
||
|
|
alert(responseData.error);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (responseData.requiresAction) {
|
||
|
|
// 3. Handle Additional Action if required (e.g., 3DS)
|
||
|
|
const { error: confirmError } = await stripe.confirmCardPayment(
|
||
|
|
responseData.paymentIntentClientSecret
|
||
|
|
);
|
||
|
|
|
||
|
|
if (confirmError) {
|
||
|
|
console.error(confirmError);
|
||
|
|
alert(confirmError.message);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
alert("Payment succeeded!");
|
||
|
|
// redirect or show success message
|
||
|
|
window.location.href = "/";
|
||
|
|
} else if (responseData.success) {
|
||
|
|
// Payment succeeded without additional action
|
||
|
|
alert("Payment succeeded!");
|
||
|
|
window.location.href = "/";
|
||
|
|
}
|
||
|
|
});
|
||
|
|
</script>
|
||
|
|
</body>
|
||
|
|
</html>
|