Home » How - To / Tutorial » How to Integrate Payments with Stripe API

How to Integrate Payments with Stripe API

E-Commerce is huge, and everywhere, no retailer from before the time of the web hasn’t either felt its impact or been gobbled up by web-born goliaths that have adopted their business models for the internet era. E-commerce is also hard, sure, you pay for things online all of the time, but the credit card details aren’t going straight from us to the service you’re paying, often a payment gateway service is used somewhere along the line to process your credit card and pass along the information to the retailer that you just made a purchase from.

Stripe-API-payment-gate How to Integrate Payments with Stripe API

If you’re the owner of a small web store, or just want to take payments for some reason or another on your own website, integrating with one of these payment gateways can be tough and complicated.

Fortunately for us, there’s Stripe, a simple but powerful API that allows us to process and receive monies from card payments without too much hassle. In this tutorial, you’re going to implement Stripe.js and the Stripe API into a simple webstore.

1. Get a Stripe account

Before you starting this project , you’re gonna need to get ourselves a Stripe account. Head on over to stripe.com and follow the on-screen instructions in order to get a Stripe account set up. Once you’ve received a confirmation email from Stripe come back here.

2. Prepare your web store.

We’re not going to build a web store from scratch because that’s not what this tutorial is about.You should prepare a simple webstore which can handle all things needed for basic ordering process.

3. Install Node.js dependancies

Now go ahead and open up terminal (or command prompt if you’re on Windows) and you will need to change directory to the location where you just stored all the project resources. Enter code/start and then run npm install to begin installing the Stripe Node.js library

4. Get the Stripe JS library

Using Stripe has been made even simpler by the lovely developers over at Stripe who have put together a ton of neat libraries for us to use. You’re going to grab the Stripe.js library that will let us build what’s known as a custom forms which is a form like any other, but with Stripe integrated into it. Open ‘index.html’ and just after where you import jQuery at the bottom of the HTML document add:

5. A home for the JavaScript

All of the code that the store uses to keep a track of an order is in the storeUI.js file in the scripts folder. You don’t need to do anything with this, it’s a helper library for the store, but you do need to initialise it, and you need a place to do that from. Add the following just after where you import the storeUI.js file into ‘index.html’ and then open core.js for editing.

6. Initialise the store

Our demo store is made up of a couple of forms and inventory items. You don’t want to concern ourselves with binding events and handling callbacks in core.js, so all of the logic is in storeUI.js – but it hasn’t been initialised yet. In the init() function of your core.js file add the following code:

This will create all of the event listeners you’ll need.

7. Find the publishable Stripe key

In order to interact with the Stripe API, you need to get what’s called the “publishable key”. By including this key with each request you make to Stripe, the API can identify us and handle payments appropriately. You can find your publishable keys at dashboard.stripe.com/account/apikeys. Use the TEST key for this tutorial and never share your secret keys with anyone.

8. Back to core.js

Once you’ve got your TEST publishable Stripe key, head back to core.js and just after where you initialised the store events, add Stripe.setPublishableKey();

9. Create a card payment form

You may have noticed that although you have some code to make a shopping cart, you don’t have any markup to take the users card details when they try to checkout. Let’s do that now. In index.html, just after the <button> element with the id of “false_purchase” add the following markup to your code:

10. Work with data-stripe

Right now, the #card_creds form doesn’t do anything special with Stripe. In order to make Stripe recognise the form, you need to add data-stripe attributes to the elements that contain specific parts of the cards details so that they can be passed on to Stripe.

For the credit card number you add data-stripe=” number” to the input where you expect the user to add the card number, for the CVC (3 numbers on the back of the card) you add data-stripe=”cvc” and so on and so forth.

11. Set user’s security and liability

Using the data-stripe attributes allows Stripe to strip out all sensitive data about the user before it ever hits the server. Cyber-crime is on the rise and you can’t all af ord to have a security team working to ensure that all of the servers are impenetrable. By allowing Stripe to take sensitive payment data of of our hands before it ever hits the server, you never have to worry about the security of the users or the liability if ever you were to have a data breach.

12. Test the cart

Right now, if you add some items to the cart and enter your card details into the form, the page will reload. you need to prevent the submit event and work some AJAX magic with Stripe to get the card details of in a usable way. Add the following code to the addEvents function of core.js. Using the Stripe.js library, send of the card details the user has entered to the Stripe API to be processed. Once those details have been validated a one-time-use token will be returned to us. To test the code out, you can use any of the card details from stripe.com/docs/testing, so long as you’re using the TEST publishable API key.

13. The order token

We don’t want the users card details to go anywhere near the server because that opens up to a world of potential trouble, but how is a payment processed? Simple, you can use the token you just received in the response from the Stripe API. Along with the customers order, you send the order token to the own server, where you can request Stripe deduct a credit from the users balance. Before you do that, you need to sort out the customers order.

14. Tally up the order

Before you send to the order to the server, you need to create a payload describing what they actually ordered that you can process server-side. In the empty submitOrder function of core.js add the following. First, it takes all of the items out of the cart and puts them into an array, then it gets the price of those items and creates a total in pence (assuming you’re using GBP) which you will ultimately charge to the user. This isn’t the most tamper-proof way of calculating price, but it’s good for demoing the power of Stripe.

15. Send the order to the server

Now that you have the payload containing the total price and the items in the cart, as well as the stripe token we’ve acquired, it’s time to send it to the server. you can do this using a basic jQuery AJAX request. Add the following code just after the last bit of code you added to submitOrder();

16. Receive the order

In the root of your project folder, open stripeServer.js. On lines 69-100 define a single endpoint, /order. This is where you will handle the data that has been sent from the demo store. On lines 37-67 you will have the sortOrder function which tallies up the amount of each item purchased by the customer and returns an organised list.

17. Parse the request

On lines 71 and 72 of stripeServer.js,, parse the body of the AJAX request sent to the server to retrieve the order payload and Stripe token for the customer. Now that you have a Stripe token, you can charge the customers card (stored on the Stripe servers) using this token. you do this with stripe.charges.create();

This function takes two arguments. An option argument, which needs to contain the amount of monies being charged (in pennies, a currency and a payment source (our card token). The second argument is a callback to handle the response from the Stripe API.

18. Handle the Stripe response

If something goes wrong, Stripe will pass an error back to the server, but if there is no error, everything has gone great, you’ve been paid! (although it may take up to 7 days for you to receive the money); Now you need to inform the user, which you do here with res.json. It’s at this point that you would write logic to set up a delivery or store the order in a database somewhere or maybe send a confirmation email, but that implementation is up to you and your (or your customers) needs.

19. Generate a receipt

On the client-side, the form will still be waiting for a response from the server. Once payment has been confirmed by Stripe the Node server sends a JSON encoded itemised list in its response. the helper library that’s been handling all of the store logic kicks in here again. Once that the confirmation has finally been received, it will reset and close the card details overlay and if you pass the itemised list that the server sends back, then it will generate a receipt to show the customer what they have ordered. This will happen in the callback you passed as part of the submitOrder function call, as we have shown below:

20. Tidying Up

So that’s the order process complete. Now you can show the customer what they’ve ordered and then you can let them continue on their way. In this case, you can now reset everything when they close the receipt dialog, but on a real store, we would let them browse around the website or you can even view all of their orders in a dashboard somewhere if that’s what you want.

21. Time to start your web store

When you’re ready to take your new web store live, don’t forget to change the TEST publishable API key to the LIVE one. Otherwise, all of the orders that you end up taking won’t actually charge the people for any of the purchases that they make, regardless of the validity of their payment method.

One thought on “How to Integrate Payments with Stripe API

  1. AnnaMJ says:

    Hello! My name is AnnaMarkova, our company need to advertise on your website. What is your prices? Thank you. Best regards, Mary.

Leave a Reply

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

Name *
Email *
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.