Struts2 – Stripe Payment Gateway Integration & Stripe Subscription

January 3rd . 5 min read
Struts2 – Stripe Payment Gateway Integration & Stripe Subscription

Stripe is one of the most popular cloud-based payment gateway service providers that makes individuals as well as corporate businesses to receive payments over the world wide online. It has some client-side libraries in JavaScript and native mobiles. To handle the payment request on server side, it has a collection of rich server-side libraries in various technologies such as Java, Node.js, PHP, Ruby, etc. These libraries help us to reduce the complexity of payment receiving methodology by having the abstracted layers.

So, due to its simplicity, we don’t even have to deal with the card detail directly, instead, we can deal with a token symbolizing an authorization to recharge the card. As Stripe has a lot of useful services, Struts2 offers support for integrating the Stripe API and implementing the payment functionality into your Struts2 applications. Here, we will learn about some useful steps to integrate Stripe payment gateway with struts2 application.

Integrating Stripe with a Struts2 Application

To start integrating this payment gateway with the API, we require to create an account on Stripe.

#Create a Stripe Account

Creating an account is very simple, and the only thing you need to do is verify your email address and phone number. Although this will only provide you with a test account while your application is approved by Stripe, which can take anywhere from a few minutes to a few days.

Right at the dashboard, you’ll be able to find the live/test keys for the API:


Before getting started to coding, you need to understand a very important that Stripe service is based on tokens. Whenever you want to charge your credit card, all you need to do is to create token passing credit card info as parameters and then use the created token as a source. A token can be used only once, so if you’ll try to use it twice, you will get an error that token is invalid or expired.

A token can be generated on the back-end from Stripe using an appropriate method, but it’s not a good idea to send the credit card details directly to your server, as someone can easily intercept the data (Man-in-the-middle attack).

Sending credit card info directly to Stripe using Stripe.js library is the best and secure way. The flow for such a case is the following:

  • Send data from the web page to Stripe.
  • Stripe returns token.
  • Send a token to the backend server.
  • Charge credit card using token.

Such an approach has two benefits:

  1. You don’t pass any sensitive data to your backend server.
  2. Even if the token will be intercepted by a man-in-the-middle he cannot retrieve any credit card info from this token

Here we are using the test API keys for integration. Since the stripe-java dependency isn’t in the initial pom.xml, we’ll add it directly to this file:


There are much more payment transaction API for integration, but most of these are having two frequently integration methods of charging a customer:

  1. One-time Purchase (I am going explain this way here in this blog)
  2. Subscription (Click here to learn about the Stripe subscription for recurring payments.

One-Time Purchase

To implement the one-time payment, you need to follow the below steps to integrate charge API in the struts2 application.

#1. Create Checkout Form

Stripe Checkout is a customizable, localizable and mobile-ready widget used to render a form to introduce credit card details. It includes and configures “checkout.js”, which is responsible for:

– “Pay with Card” button rendering

– Payment overlay dialog rendering (triggered after clicking “Pay with Card”)

– Credit card validation

– “Remember me” feature (associates the card with a mobile number)

– Sending the credit card to Stripe and replacing it with a token in the enclosing form

<form id="myForm" action="/payment/pay.html" method="POST">
<input type="hidden" name="amount" value="500.0" />
    <script src="" class="stripe-button"


The “checkout.js” script automatically triggers a request to Stripe right before submission, which then appends the Stripe token and the user email as the hidden fields “stripeToken” and “stripeEmail”.

The amount (“data-amount”) is used only for display purposes (along with “data-currency”). Its unit is Cents of the used currency, so we divide it by 100 to display it.

The Stripe public key is passed to Stripe after the user asks to pay. Do not use the secret key here, as this is sent to the browser.

#2. Configure struts.xml File

Map the above form action in struts.xml configuration file:

<action name="payment/pay" class="paymentAction" method="payNow">
	<result name="error">/WEB-INF/jsp /pay-now.jsp</result>
	<result name="success" type="redirect">/payout-success.html?topup=true</result>

#3. Create Struts2 Action

Create the to handle the stripe request in back-end:

import com.stripe.exception.StripeException;
import com.stripe.model.*;
import com.stripe.param.PlanRetrieveParams;
public class PaymentAction extends BaseAction {
    private static final long serialVersionUID = 5745206363886171770L;
    private String email;
    private String phoneNumber;
    private String token;
    private String stripeToken;
    private float amount;
    public String payNow() {
    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here:
    //Stripe.apiKey = "sk_test_ox1kkZ7ukxBQbPcDSEYYjnM7";
    // Charge the user's card:
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("amount", (int) (amount * 100));
    params.put("currency", "usd");
    params.put("description", "Snaprecruit Topup");
    params.put("source", stripeToken);
    Charge charge = Charge.create(params);
    if (charge.getPaid()) {
        //Do your stuffs here if payment is successfully done.
        return "success";
    else {
        return "error";

Subscription for Recurring Payment

Before we move to integrate the subscription API, we need to have a quick glance at the subscription requirement. A subscription, formally for recurring payments is referred to as Automatic Payment process, which means that a customer has permitted the merchant or retailer to deduct payments for services or goods every month from his/her bank account to automatically charge his/her credit card in the amount due each month.


The merchant needs to get one-time front permission from the customer. The merchant deducts the amount for a scheduled day in every month automatically, so the customer needs not worry about the late fee. The automatic payments continue until the consumer retracts his permission.

In the previous paragraph about One-Time Purchase, we learned about how to create a stripe account and get the publishable key and secret key.

To implement the subscription for a recurring payment, you need to follow the below steps to integrate charge API in the struts2 application.

Use stripe’s official guide to set up a subscription and charge a customer. In this link, you will be able to create some products and plans on your stripe account. Here, we will cover the following points:

  1. Using Stripe form element for card details.

  2. Create customer by user inputs.

  3. Apply Subscription for a selected plan.

#1. Create Checkout Form for Subscription

Create an HTML form with below UI:


#2. Code to Create Subscription Form

Use the following HTML code for the above UI design-

<!DOCTYPE html>
  <title>Stripe Checkout Form</title>
<form action="/payment/pay-subscription.html " method="post" id="payment-form">
<div id="emaildiv">
  Email: <input type="email" name="email" id="email" class="form-control"   value="" required="required" /> 
<div id="phone-number">
  Phone Number:<input type="text" name="phoneNumber" id="phoneNumber"  required="required" />
 <div id="bill-name">
  Name: <input type="text" name="billingName" id="billingName" class="form-control"  required="required"/>
<div class="form-group">
  <label for="card-element"> Card Information <span style="color:red;">*</span></label>
  <div id="card-element">
    <!-- A Stripe Element will be inserted here. -->
  <!-- Used to display form errors. -->
  <div id="card-errors" role="alert"></div>
<div id="addline1">
  Address Line1:  <input type="text" name="billingAddressLine1" id="billingAddressLine1” required />
<div id="addline2">
  Address Line2: <input type="text" name="billingAddressLine2" id="billingAddressLine2"/>
<div id="city">
  City:<input type="text" id="city-select" name="billingCity" placeholder="City" required>
<div class="dd-div">
  State:  <select id="state-selectSelectBoxIt” name="billingStateCode" required>
    <option value="">Select a state</option>
    <option value="A">Alaska</option>
 <div id="zipcode">
 ZIP Code:  <input type="text" name="billingZip" id="billingZip" class="form-control" required="required"/>
<div class="dd-div">
 Country: <select id="country-select" name="billingCountry" class="form-control" required>
    <option value="">Select a country</option>
    <option value="US">United States</option>
<div id="name-on-card" class="cstmcheck">
  <input type="checkbox" id="agreeterm" name="userAgree" value="true" />
  <label for="agreeterm">I Agree to Terms & Conditions</label>
<div class="sbmtpayment">
  <!-- Add the amount in hidden field ----->
  <input type="hidden" name="amount" id="amount" value="500"/>
  <!-- Add the stripe plan id in hidden field ----->
  <input type="hidden" name="stripePlanId" id="stripePlanId"  value="plan_adbxodroeXXXX"/>     
  <button class="btn btn-primary green-btn ml-0">Submit Payment</button>
<script src=""></script>

#3. Credit Card Validation and Form Submission

Before the closing body tag in the above code snippet, add the following JavaScript code which handles the client credit card validation and the form submission with the appropriate plan, the amount generated stripe token.

     //var stripe = Stripe('pk_test_v8tRSPbxyEfKTlcJo8uAeEgh');
    var elements = stripe.elements();
    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
        base: {
            color: '#32325d',  fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',  fontSize: '16px',  '::placeholder': { color: '#aab7c4'   }
        invalid: {
            color: '#fa755a',  iconColor: '#fa755a'
    // Create an instance of the card Element.
    var card = elements.create('card', {hidePostalCode: true, style: style});
    // Add an instance of the card Element into the `card-element` <div>.
    // Handle real-time validation errors from the card Element.
    card.addEventListener('change', function(event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
    // Handle form submission.
    var form = document.getElementById('payment-form');
    form.addEventListener('submit', function(event) {
        if($('input[name="userAgree"]:checked').length == 0) {
            alert("Please accept the Terms and Conditions!!");
        else {
  stripe.createToken(card).then(function (result) {
  if (result.error) {
    // Inform the user if there was an error.
    var errorElement = document.getElementById('card-errors');
    errorElement.textContent = result.error.message;
  } else {
    // Send the token to your server.
    // Submit the form with the token ID.
    function stripeTokenHandler(token) {
        // Insert the token ID into the form so it gets submitted to the server
        var form = document.getElementById('payment-form');
        var hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'stripeToken');
        // Submit the form


In this blog, we’ve shown how to make use of the Stripe Java API to charge a credit card and using the struts2 framework. To test the entire charge and subscription flow, we don’t need to use a real credit card even in test mode. We can use Stripe testing cards instead.

The charge operation is one of many possibilities offered by the Stripe Java API. The official API reference will guide us through the whole set of operations.