// Initialize Stripe
const stripe = Stripe('pk_test_your_key');
// Create payment element
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
// Handle form submission
form.addEventListener('submit', async (event) => {
event.preventDefault();
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
});
if (error) {
console.error(error);
} else {
console.log(paymentMethod);
}
});
// Node.js example
const stripe = require('stripe')('sk_test_your_key');
app.post('/create-payment-intent', async (req, res) => {
const {amount, currency = 'usd'} = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: amount * 100, // cents
currency,
automatic_payment_methods: {
enabled: true,
},
});
res.json({
clientSecret: paymentIntent.client_secret
});
} catch (error) {
res.status(400).json({error: error.message});
}
});