Node.js and Stripe Easy Integration đ„ł
In the world of server-side JavaScript development, Node.js is a popular and powerful platform for building flexible and scalable applications. On the other hand, Stripe is the payment infrastructure preferred by millions of businesses around the world to perform secure and efficient payment transactions. In this article, we will delve deeper into the technical aspects of Node.js and Stripe integration. Take your payment management skills to the next level thanks to the powerful combination of Node.js and Stripe integration!
- Install the required packages
npm init
npm install express body-parser stripe
2. Import the required modules and initialize the app in app.js
(or index.js
, depending on your project structure):
const express = require(âexpressâ);
const bodyParser = require(âbody-parserâ);
const stripe = require(âstripeâ)(âyour_stripe_secret_keyâ);
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
3. Set up a route to create a charge:
- First, it creates a token with payment card information. This is done by sending an object containing card details like card number, expiry month, expiry year, and CVC to the
stripe.tokens.create()
function. In this example, a test card number is used.
const token = await stripe.tokens.create({
card: {
number: '4242424242424242',
exp_month: 5,
exp_year: 2024,
cvc: '314',
},
});
- The payment amount and currency are extracted from the request body
req.body()
. These values will be determined by a request coming from the frontend.
const { amount, currency } = req.body;
- Next, a payment transaction is created using the
stripe.charges.create()
function. An object containing the generated token, amount, currency, and a description of the transaction is sent.
const charge = await stripe.charges.create({
amount,
currency,
source: token.id,
description: 'Example charge',
});
- If the payment transaction is created successfully, the handler returns a JSON response with an HTTP status code of 200. This response includes the success status, a message, and details about the payment transaction.
res.status(200).json({ success: true, message: 'Charge created successfully', charge });
- If there is an error during the creation of the payment transaction, the handler returns a JSON response with an HTTP status code of 500. This response includes the success status, an error message, and error details.
res.status(500).json({ success: false, message: 'Charge creation failed', error });
4. And all the code :
app.post('/charge', async (req, res) => {
try {
const token = await stripe.tokens.create({
card: {
number: '4242424242424242',
exp_month: 5,
exp_year: 2024,
cvc: '314',
},
});
const { amount, currency } = req.body;
const charge = await stripe.charges.create({
amount,
currency,
source: token.id,
description: 'Example charge',
});
res.status(200).json({ success: true, message: 'Charge created successfully', charge });
} catch (error) {
res.status(500).json({ success: false, message: 'Charge creation failed', error });
}
});
5. Start server
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on port ${port}`));
6. To test the API endpoint with Postman, follow these steps:
- Open Postman and create a new request by clicking the â+â button on the top bar.
- Set the request method to âPOSTâ using the dropdown menu next to the URL input field.
- Enter the URL of the API endpoint that you want to test (e.g.,
http://localhost:3000/charge
in the URL input field. - Click on the âBodyâ tab below the URL input field, and choose the ârawâ option. Then, select âJSONâ from the dropdown menu on the right.
- In the input area below, enter the request object as a JSON string. For example:
{
"amount": 400,
"currency": "eur"
}
7. Click the âSendâ button to send the request to your API endpoint.
If the payment transaction is successful, the response object should look like this:
{
"success": true,
"message": "Charge created successfully",
...
}
This response object indicates that the charge was created successfully. It contains the âsuccessâ field set to true
, a "message" field with the text "Charge created successfully", and additional fields with more details about the payment transaction (represented by the "..." in the example).
By using Postman, you can easily test the API endpoints of your application and ensure that the payment transaction processing using the Stripe API is working correctly.