I have the following standard JavaScript to mount my Stripe Element to my DOM:
export function MountStripeElement() {
const stripe = Stripe("pk_test...");
const options = {
mode: 'subscription',
amount: 1099,
currency: 'usd',
// Fully customizable with appearance API.
appearance: {/*...*/ },
};
// Set up Stripe.js and Elements to use in checkout form
const elements = stripe.elements(options);
// Create and mount the Payment Element
const paymentElement = elements.create('payment');
paymentElement.mount('#payment-element');
}
Later on, I am calling my own submit method manually (I can't register an event listener and pass elements as part of the mount element method above for various reasons) I need access to the Stripe elements object that was available to me when I mounted/created the element.
export async function CreateStripeSubscription() {
event.preventDefault();
var submitBtn = document.getElementById('submit');
var stripe = Stripe("pk_test...");
const handleError = (error) => {
const messageContainer = document.querySelector('#error-message');
messageContainer.textContent = error.message;
submitBtn.disabled = false;
}
// Disable form submission while loading
submitBtn.disabled = true;
const { error: submitError } = await elements.submit();
if (submitError) {
handleError(submitError);
return;
}
var paymentElement = elements.getElement('payment');
// Confirm the PaymentIntent using the details collected by the Payment Element
const { error } = await stripe.confirmPayment({
paymentElement,
clientSecret,
confirmParams: {
return_url: 'https://www.google.co.uk/',
},
});
if (error) {
handleError(error);
} else {
}
}
However the above is failing on this line as elements is undefined:
var paymentElement = elements.getElement('payment');
The Stripe documentation seems to suggest I can just grab the previously created payment element here
My question is, how can i get a handle on 'elements' later on when im trying to submit my form to Stripe (which requires the payment element) given I cannot pass it as a parameter from the initial MountStripeElement at the start. Surely being able to grab your payment element later in a separate method should be possible?