Stripe Payment
Stripe Payment is an online payment processing platform that allows you to perform transactions using a debit or a credit card. Stripe Payment is one of the most popular payment platform that provides secure transactions with security checks:
Implementation of Stripe Payment Gateway in Spring-boot Application
To integrate Stripe Payment in Spring-boot Application, first you need to register to a Stripe account. Here is the link: https://dashboard.stripe.com/register
After successfully registering, you will be led to the dashboard. From the menu, choose API keys. You will get two pairs of API keys, one for testing and other is for live. Copy the keys and add to application.properties file.
Next, add a maven dependency:
<dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>${version}</version> </dependency>
There are two ways to perform transactions using stripe:
In this blog, we will perform the implementation using the second method, by saving the card details.
So for this, we first need to create a customer which returns you a Customer object. You can use the customer.getId() to fetch a unique customer id, using this id you can perform futher operations like to save the card details or make payment
Stripe.apiKey = environment.getProperty("stripe_key"); Map<String, Object> map = new HashMap<>(); map.put("email", user.getEmail()); Customer customer = Customer.create(map); String customerId = customer.getId();
By saving the card, we wouldn't need to enter the details everytime.
Map<String, Object> map = new HashMap<>(); map.put("number", xxxxxxxxxxxxxxxx); map.put("exp_month", 03); map.put("exp_year", 2030); map.put("cvc", 123); map.put("name", "John Doe"); Map<String, Object> cardMap = new HashMap<>(); cardMap.put("card", map); Token token = Token.create(cardMap); Customer customer = Customer.retrieve(customerId); Map<String, Object> source = new HashMap<>(); source.put("source", token.getId()); customer.update(source);
Finally, to make a payment, Stripe provide a Class "Charge" with method create().
stripeCustomer = Customer.retrieve(stripeCustomerId); Map<String, Object> map = new HashMap<>(); map.put("amount", amount * 100); map.put("currency", "USD"); map.put("description", "payment description"); map.put("customer", customerId); Charge charge = Charge.create(map);
And that's it. You can track the transaction statements and customers details in your stripe dashboard.
Note: Here, i have multiplied the amount by 100 because it considers the amount to be in cents (for USD currency) and i want the result in dollars.
Stripe also provides dummy card details for testing: https://stripe.com/docs/testing