Add Stripe library in your HTML file:
<script src="https://js.stripe.com/v3/"></script><form id="payment-form">
<!-- Stripe Card Input -->
<div id="card-element"></div>
<button id="submit">Add Card</button>
</form>
<script>
// Initialize Stripe with your Publishable Key
const stripe = Stripe("pk_test_xxx"); // replace with real publishable key
// Create an instance of Elements
const elements = stripe.elements();
// Create a card input field
const cardElement = elements.create("card");
cardElement.mount("#card-element");
</script>const form = document.getElementById("payment-form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
// Step 1: Create payment method from card input
const {paymentMethod, error} = await stripe.createPaymentMethod({
type: "card",
card: cardElement,
});
if (error) {
alert(error.message);
return;
}
console.log("✅ Payment Method ID:", paymentMethod.id);
// Step 2: Send Payment Method ID to backend
const response = await fetch("/api/payment-method/add", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-CSRF-TOKEN": "{{ csrf_token() }}" // for Laravel
},
body: JSON.stringify({
payment_method_id: paymentMethod.id
}),
});
const data = await response.json();
if (data.status) {
alert("Card added successfully!");
} else {
alert("Error: " + data.message);
}
});- User enters card info in Stripe input.
stripe.createPaymentMethodgenerates apayment_method.id.- This ID is sent to Laravel backend (
/api/payment-method/add). - Backend attaches the card to the customer and sets as default.
⚡ Tip:
Always use Publishable Key on frontend, never the Secret Key.
<!-- Stripe JS Load -->
<script src="https://js.stripe.com/v3/"></script>
<form id="payment-form">
<div id="card-element"></div>
<button id="submit">Add Card</button>
</form>
<script>
const stripe = Stripe("pk_test_xxx"); // ✅ Stripe publishable key
const elements = stripe.elements();
const cardElement = elements.create("card");
cardElement.mount("#card-element");
const form = document.getElementById("payment-form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
// Step 1: Create payment method from card input
const {paymentMethod, error} = await stripe.createPaymentMethod({
type: "card",
card: cardElement,
});
if (error) {
alert(error.message);
return;
}
// Step 2: Send payment method id to backend
const response = await fetch("/api/payment-method/add", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-CSRF-TOKEN": "{{ csrf_token() }}"
},
body: JSON.stringify({
payment_method_id: paymentMethod.id
}),
});
const data = await response.json();
console.log(data);
if (data.status) {
alert("Card added successfully!");
} else {
alert("Error: " + data.message);
}
});
</script>-- 👉 Ei part e Stripe card input box ashbe, user card entry korbe → paymentMethod.id generate hobe → backend e pathabo.