Tag Archives: Microservice

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

Where are we?

Hold on to it. This is going to be a rant about what I am thinking about ideas to post, but also an update about the web application Social KPI.

I am working on a few ideas that I would like to write about. But I am not sure. Lately I have been working on microservice architecture project and that had helped me to design Social KPI application. I would like to hear from my followers if they are interested in any particular topic that I should cover. Currently most of the interests are around Spring boot and microservices. That is too specific, but also equally too big of a topic to cover. I have covered bits and pieces of Spring boot.

Here are a few ideas that I have in mind that I would like to post about:

  1. Spring boot in android applications.
  2. How to use Spring boot and deploy in cloud infrastructure
  3. What is chaos engineering?
  4. Android application and details
  5. Microservices and Service-to-Service authentication
  6. Udemy course for Spring boot and microservices.

Please leave a comment if you want me to cover something new.

Where are we with Social KPI application?

So last, I posted about this application was back in May Twitter Client. After that there had been some progress as I did figure out how to use social login for authentication purposes, but it had not been added in the application. I will be reviving the work on this project and will try to contribute daily for 30-60 minutes. As part of my planning process, I will add here the tasks that need to be finished:

  1. Add Social login UI for the application
  2. Add UI Pages for displaying Social KPI reports and user navigation
  3. Connecting front-end to back-end REST APIs through clients.
  4. Use of Jasper reports for graphical reports.

These are the 4 big stories I am planning to finish by the end of October. Once I have all the code completed, I will launch the application through Heroku.