Stripe provides example in docs for using PaymentElement
where they create the <Elements>
component at the root of the app and wrap it around the entire website. This works well with being able to access the stripe object from anywhere within the app using the useStripe
and useElements
hooks.
However, when they create elements at the root, they also specify the options
parameter which contains a clientPromise
. clientPromise
can only be obtained once the item being purchased is known. Hence, I need to generate the clientPromise
in a subcomponent that deals with checkout.
Stripe Docs Code
const stripePromise = loadStripe('fake_test_key');
function App() {
const options = {
// passing the client secret obtained from the server
clientSecret: fetchClientSecretFromServer(),
};
return (
<Elements stripe={stripePromise} options={options}>
<CheckoutForm />
</Elements>
);
};
Is there a way to manually set clientPromise, or overwrite stripe options in a component that is a child of <Elements>
instead of having to generate it at the point where the ` component is rendered?
CodePudding user response:
Unfortunately I think the only way to handle this is to delay the loading of Elements
until you know the details of the purchase.
All of react-stripe-js is just a React style wrapper around classes and methods provided by stripe.js. If you examine how Payment Intents and Setup Intents docs make use of the stripe.js elements, they are always instantiated after the creation of the Intent object and the sending of the clientSecret
to the front-end.