Accepting a payment using Stripe (Kotlin/Javalin)
Stripe is a cloud-based service that enables charging customers for your products or services. With Stripe API, you don’t manage sensitive information like credit cards. Let’s learn how to use it.
2. Web handlers
- Add Javalin (web framework) and Stripe client to your
2. We need to set up the web request handlers. Create a
src/kotlin/Main.kt with the following content:
Beware you need to replace two values:
STRIPE_API_KEY: Ensure your Stripe Dashboard is in “Test mode” (top-right corner). Head on to “Developers” (top right) → “API Keys” (left-side menu) → “Standard keys” → “Publishable key” (this is a demo key). Beware that you should set an environment variable with this rather than leave it in the code and thus in source control.
PRICE_ID: In the Stripe Dashboard find and click “Products” and then, create a new product. Confirm the product creation and within the newly created product, scroll until the “Pricing” section. There, you can copy the “API ID” of the desired price.
📝 You can fetch the product details (e.g. title, image URL) with
3. Web pages
We need the HTML pages that the user will see. In this sample, we could use just resort to hardcoded HTML. However, let’s add a server-side templating library so we can display the price details obtained from the Stripe API. Add jte to
We need a checkout page to represent the checkout of a shopping cart; it contains all the products the customer added. In our case, it contains a single product. In a real case, it could contain the products stored in a session. Add
src/main/jte/checkout.jte with the following content:
We need a success page that represents the callback from Stripe when the payment is successful. Add
src/main/jte/success.jte with the following content:
The cancel page deals with the user canceling the payment. Add
src/main/jte/cancel.jte with the following content:
4. A test payment
Let’s do a fake payment in localhost:
Main.ktand go to
- Click the “Checkout” button to move on to the Stripe payment page.
- Now you can use the fake card
4242 4242 4242 4242(the remaining details can be set at will). This fake card number simulates a fake successful payment so you can test the whole flow.
Accept a payment
Add a checkout button to your website that calls a server-side endpoint to create a Checkout Session. A Checkout…