Nowadays, businesses over the internet are growing rapidly. Accepting online payments is the most crucial part of all these businesses. There are lots of payment gateways available in the market, but there is always one question raised in the mind while integrating a payment gateway, Which one to choose? So today we are going to see how Stripe is the best solution as a payment gateway? And how can you integrate it with your application?
The Stripe payment gateway allows individuals and businesses to accept payments over the internet. Stripe believes that payment is a problem rooted in code, not in finance (Developers First). It provides APIs that developers can use to integrate payment processing in their web applications and mobile applications. Stripe eliminates needless complexity so that developers can start with Stripe in just a couple of minutes.
From the security, perspective stripe provides fraud prevention to make payment processing more secure and robust. Stripe has its console to manage and track the payments. So maybe these are good enough points to justify, Why to choose Stripe?
Stripe can be used with multiple types of payment scenarios like, If your project has a subscription model, i.e. after a certain period you want to charge the user, then you can prefer Stripe.
In some cases, we need to set up future payments. In such a case, stripe can hold the amount that you need to charge and confirm the charge after some events. Last but not least if you want to charge immediately, you can do that as well with the help of Stripe.
From the above cases, the subscription model and charge immediately are very straightforward. In the subscription model, you can store user card details and charge it after some time intervals and while paying at the time of checkout, i.e. fast paying you can accept card or other payment methods from the user and charge it immediately. Stripe itself handles most of these cases, but the problem arises when you have set up future payment requirements.
So what do you mean by Set up future payments, let’s try to understand with an example of online telemedicine platform:
Suppose a patient is consulting with a doctor on an online meeting, the patient has to pay some fees to the doctor after the meeting if the session is completed successfully, but the patient should have enough balance to join the meeting. So what we will do in such a case will hold some amount, i.e. fees when the patient enters the meeting but we do not charge it immediately. We save that payment info called Payment Intent and confirm charge after successful completion of the meeting.
Integration of stripe is syntactically different in different client and server technologies, here we are going to use web (Javascript) as our client and spring boot (Java) as a server.
Before setting up all you need to do is create a stripe account.
For starting using a stripe first you need to add stripe’s official library into your project. This library allows you to access all Stripe API.
<dependency> <groupId>com.stripe</groupId> <artifactId>stripe-java</artifactId> <version>{VERSION}</version> </dependency>
<script src="https://js.stripe.com/v3/"></script>
Before accessing any Stripe API you need a secret API key which you can get from the stripe dashboard.
We need a Publishable key for web clients. You can get that by following the same steps given above but instead of a secret key you need to copy the publishable key.
pk_test_E************************** (Test publishable key)
We need a customer because a card added while setting up future payment needs to be attached with the customer object. For best practice, always create customers from the server-side.
While creating a customer you can pass two things with object, name and email. Email is an optional field but the name is mandatory.
Stripe.apiKey = "sk_test_4***************";
Map<String, Object> customerParams = new HashMap<>(); customerParams.put("email", "john@example.com"); customerParams.put("name", "John S"); // creating customer on stripe Customer customer = Customer.create(customerParams);
After creating a customer you are able to add a card. Adding a card is needed to be done from the client side but before that you need a client secret that is present in the setup intent object, so first we need to create Setup Intent which should be created at server side.
Setup Intent object contains client secret that you need to pass to Stripe.js while creating a card from the web.
Stripe.apiKey = "sk_test_4***************"; Map<String, Object> params = new HashMap<>(); params.put("customer", id); SetupIntent intent = SetupIntent.create(params);
You can get client secrets from the above setup intent by calling getClientSecret() method.
Add card is should be done from client side because we can’t expose user card details by using our server API. If you want to check the added card on the server side, Stripe provides web hooks that we can catch at our server and get the card details which are added.
var stripe = ('pk_test_***********');
var element = stripe.elements(); var cardElement = element.create("card");
<label for="card-element">Card</label> <div id="card-element"></div> <script> cardElement.mount('#card-element'); </script>
var cardholderName = document.getElementById('cardholder-name'); var cardButton = document.getElementById('card-button'); var clientSecret = cardButton.dataset.secret;
cardButton.addEventListener('click', function(ev) { stripe.confirmCardSetup( clientSecret, { payment_method: { card: cardElement, billing_details: { name: cardholderName.value, }, }, } ).then(function(result) { if (result.error) { // Display error.message in your UI. } else { // The setup has succeeded. Display a success message. } }); });
After successful execution you will get payment method id in the result.setupIntent.payment_method field. This id is useful in the further process of payment.
Now, when we want to pay some amount with a selected payment method i.e. card, we can pass payment method id and customer id from client to server with our internal API and calculate amount at server side based on conditions or you can pass that through the same api where you are passing payment method id.
Long amount = (long) ((100-50) * 100); //Your amount calculation PaymentIntentCreateParams createParams = PaymentIntentCreateParams.builder() .setAmount(amount).setCurrency("usd") .setPaymentMethod("paymentMethodId") .setCustomer(customerId) .setDescription("About payment") .setConfirmationMethod(PaymentIntentCreateParams .ConfirmationMethod.MANUAL).build(); PaymentIntent intent = PaymentIntent.create(createParams);
In the above code snippet, first we created parameters for payment intent where you need currency, amount and customer id as mandatory fields.
**Note:-Main thing we need to keep in mind here is the Confirmation Method that should be manual for future payments. If you put it as an auto then payment will get captured immediately.
After successful execution you can save this payment intent id in the database.
When you are ready to capture the payment you just need Payment Intent id to that.
PaymentIntent paymentIntent = PaymentIntent.retrieve("paymentIntentId"); paymentIntent = paymentIntent.confirm();
If you need a receipt of payment you can retrieve from charges object which is present in above payment intent as follows,
Charge charge = paymentIntent.getCharges().getData().iterator().next(); String url = charge.getReceiptUrl();
What’s on your mind? Tell us a little bit about yourself and your question, and we will be in touch with you within 12 hours
Free eBook on Telemedicine Platform Development: All About Telemedicine
Download Free eBook Now!