Need help?

Stripe – The Payment Solution

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?

Why To Choose Stripe?

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?

When To Use?

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.

Best Practices To Integrate Stripe For Future Payments

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.

Step 1 : Set Up Stripe

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.

  • Server-side:
    For spring boot project add the following dependency into your pom.xml file
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
<version>{VERSION}</version>
</dependency>

 

  • Client side:
    Stripe provide Stripe.js library which you can add to your project by using script tag like,
<script src="https://js.stripe.com/v3/"></script>

Step 2 : Get Secret API Key And Publishable Key

Before accessing any Stripe API you need a secret API key which you can get from the stripe dashboard.

  1. Open stripe dashboard
  2. Expand developers menu from left hand menu
  3. Select API keys option.
  4. On the right side, under the standard keys click on the reveal key token button and copy the API key.

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.

Example : sk_test_4W************************* (Test Secret API key)

pk_test_E************************** (Test publishable key)

Step 3 : Create Customer

  • Server side:

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.

Step 4: Create Setup Intent

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.

  • Create stripe object by providing publishable key as follows,
var stripe = ('pk_test_***********');

  • Create element to accept card details, first create object of element and than use it to create card element in DOM
var element = stripe.elements();
var cardElement = element.create("card");


  • Mount card element in DOM
<label for="card-element">Card</label>
<div id="card-element"></div>

<script>
  cardElement.mount('#card-element');
</script>

  • Confirm the setup intent
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.

Step 6: Pay Using Saved Cards.

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.

Actual payment should be done from the server side as follows,
  • Server-side:
    • First, you need to create PaymentIntent
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.

Step 7: Capture Actual Payment

When you are ready to capture the payment you just need Payment Intent id to that.

PaymentIntent paymentIntent = PaymentIntent.retrieve("paymentIntentId");
paymentIntent = paymentIntent.confirm();



Retrieve the payment intent by id and confirm it, To capture the amount which is held by that payment intent.

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();

Step 8: Testing

Stripe provides some test cards suitable to different test cases. Here are the some samples from them,

Subscribe To Our Newsletter

Content Team

This blog is from Mindbowser‘s content team – a group of individuals coming together to create pieces that you may like. If you have feedback, please drop us a message on contact@mindbowser.com
We do publish often and our blogs are often accompanied by research and surveys. If you would like to be the first to receive an update on whenever we publish, subscribe to our newsletter.

Leave a Reply

Your email address will not be published. Required fields are marked *