Categories

Meta

Using Stimulus to Manage Stripe Elements

Published April 11, 2019 by john

If you use Stripe to accept payments, you’ve likely had to insert the little Javascript snippet needed to wire up their library with your page. With a little refactoring, it works really well with a Stimulus controller. This setup simplifies your whole development process, and keeps your Javascript neatly stored together.

Stripe’s JS & HTML

Stripe’s main library is a snippet you can include in your page’s head:

The connect() function sets up the Stripe element, loading in the API passed in via a HTML data-attribute. A callback for real time validations is added, which will add any errors onto the cardErrorsTarget element. The form’s submission is watched, and stopped, so that Stripe can process the card and return a card token. The returned Stripe token is then inserted into the form, and the form is submitted normally.

The Possibilities are endless

I hope this example helps if you’re integrating Stripe payments into your web app, and want to keep all your Javascript in one spot. You can also see how many third party snippets can be refactored into a Stimulus controller, resulting in cleaner code organization.

Comments or Questions? Let me know how the practice problems went on twitter @jpbeatty