X

Node.js

Stripe Api Create A One Time Charge

July 29, 2021

/*

Stripe Create A One Time Charge


*/

In the last stripe article, I went over how to style a stripe element as well as covering the elements.create() method, element.mount() method & events for stripe elements. This article, I'm going to create a one time credit card charge with stripe. I'm not going to use the user's info, I just want the credit card info to make the charge.

/*

Creating A Stripe Token


*/

I'm going to use the stripe.createToken() method to make a one time use token that can be passed to the server & referenced by the stripe api. The token id will be passed to a hidden input element & submitted with the form. Important, the token id only will be submitted, if the token is submitted you will get the [object Object] string on the server.

/*

Stripe.createToken() parameters


*/

This method takes 3 parameters, the stripe element you want to use data from, a data object which takes info like name & address, this info can be used to verify the card, lastly, a promise that resolves with a token or an error.

Code for stripe.createToken() method

/*

Making the Charge


*/

On the server, I'm going to grab the token id that was submitted & use the stripe.charges.create() method to charge the user's card. This is a one time charge, if the same user wants to buy something else they will have to enter their card info in again.

/*

Stripe.charges.create() parameters


*/

This method only takes 1 parameter, that is a data object, that requires certain properties be filled out to return successfully. The amount property takes a number that is the total amount of the purchase, the currency property takes a string which is the ISO currency code. If your in the U.S. it would be "usd". The source property is the payment source & is required if your using tokens to make a charge. Every other property is optional. This method returns a charge object when successful, it will return an error if unsuccessful.

Code for stripe.charges.create() method

This is the complete project.

<code-div></code-div>

The final result is here.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.