Monthly Archives: July 2019

How to add Stripe Payment to Spring Boot Application

In this post, we will show how to add Stripe Payment to Spring boot application. Most enterprise applications offer a way where customer can pay online. Online payments are the backbone of internet world in current times. If you ever built an application for a customer, previously there were physical cheques OR credit card payments. With the applications becoming more web based, it has become utmost necessary to integrate your application with some kind of payment gateway. Payment gateway will handle all tax and financial regulation related complications which the application doesn’t have to deal with.

The functionality is part of the application Social KPI that I am building.

What are we trying to achieve here?

Story for Stripe Payment

An administrator comes on the billing page and pays the bill for that month. Once the bill is paid, the billing page will show that the bill has been paid for that month. So the option to enter credit card details will only be shown if the bill has not been paid.

As part of payment service, we will be using Stripe . Once the user enters credit card details and she can enter Pay Now button which will contact Stripe API to get token, this token will be used to create a charge on Stripe and Stripe will respond with success or failure of the charge.

Flow

To summarize the flow

  1. User clicks Pay Now to pay the charges
  2. Frontend Stripe javascript API contacts Stripe to create token using enter billing details
  3. Frontend Stripe javascript API sends this token to server to handle billing on server side
  4. On server side, controller uses the token and amount to create charge for that customer for application usage.
  5. For paid bills, the status is marked as paid for the customer for that month.

Frontend Implementation

To use Stripe APIs, we must first create account on stripe.com as a developer and get the keys. Good thing is Stripe offers API keys for test and live environments. For this post and demo, we will be using test keys only. Once we have API keys, we will use them in our frontend and backend implementation.

In following screenshot, you will see how the billing page will look:

Billing Page

Once the user clicks on Pay Now, the javascript function from Stripe for mounting card and creating token will be called. Once the token is available, the same function will pass it server by submitting a POST request. Sample of this code will look like below:


            var form = document.getElementById('payment-form');
            form.addEventListener('submit',function(event){
                event.preventDefault();
                payTheBill();
            });

            function payTheBill(){
                stripe.createToken(card).then(function(result){
                    if(result.error){
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = result.error.message;
                    } else {
                        var token = result.token.id;
                        var email = $('#email').val();
                        var companyid = $('#companyid').val();
                        var amount = $('#amount').val();
                        $.get(
                            "/createcharge",
                            {email:email,token:token,companyid : companyid, amount:amount},
                            function(data){
                                alert(data.details);
                            },'json');
                    }
                })
            }

Backend Implementation

As part of the application Social KPI, I have a database table billing to track customer’s paid bills. The PaymentController is a REST controller which will have a POST request mapping for creating a charge and storing in the database table and mark the bill as paid. As shown above in javascript code, once the token is available it will be sent to server side to controller to handle the charge. This will be a REST call, so the controller is also RestController.


 @RequestMapping(value="/createcharge",method = RequestMethod.GET)
    @ResponseBody
    public Response createCharge(String email, String token, String companyid, double amount)
    {
        LOGGER.info("Enter >> createCharge() ");

        if(token == null)
        {
            throw new RuntimeException("Can't create a charge, try again");
        }

        Billing billing = billingRepository.findByCompanyId(Integer.parseInt(companyid));

        double billedAmount = amount * 100;

        String chargeId = paymentService.createCharge(email,token,billedAmount);

        if(chargeId != null && !chargeId.equals(""))
        {
            LOGGER.info("bill has been charged on consumer's account");
            billing.setStatus(true);
            billing.setPaiddate(new Date());
            billingRepository.save(billing);
        }

        LOGGER.info("Exit << createCharge() ");
        return new Response(true,"Congratulations, your card has been charged, chargeId= "+chargeId);
    }

As shown above, Service called paymentService will create a charge on Stripe. To implement paymentService, you will need to include stripe java library in your implementation.

compile('com.stripe:stripe-java:10.5.0')

So the service class PaymentService will look like below to create charge:


    public String createCharge(String email, String token, double amount)
    {
        String id = null;
        try
        {
            Stripe.apiKey = API_SECRET_KEY;
            Map chargeParams = new HashMap<>();
            chargeParams.put("amount", (int)(amount*100));
            chargeParams.put("currency", "USD");
            chargeParams.put("description", "Charge for " + email);
            chargeParams.put("source", token);
            Charge charge = Charge.create(chargeParams);
            id = charge.getId();
        }
        catch(StripeException e)
        {
            throw new RuntimeException("Unable to process the charge", e);
        }
        return id;
    }

Once the bill is paid, administrator will see this as the bill paid for that month.

Conclusion

In this post, we showed how to integrate Spring boot application with Stripe payment gateway.

References

  1. Stripe API reference - https://stripe.com/docs/api/charges
  2. Integrate Stripe with Spring boot - Stripe with Spring boot