This repository provides a comprehensive and easy-to-use boilerplate for integrating Stripe with Node.js applications. The stripeService.js
file encapsulates all major functionalities of the Stripe API, allowing developers to quickly and efficiently perform common operations like creating customers, managing payments, handling subscriptions, and more. The goal is to streamline Stripe integrations, letting you focus on building your application.
- Features
- Installation
- Setup
- Usage
- Available Functions
- Extending the Boilerplate
- Contributing
- License
- Comprehensive Coverage: Includes methods for managing customers, payments, charges, subscriptions, products, and more.
- Easy Integration: Set up and start using Stripe in minutes with simple function calls.
- Extensible: Easily add more functionality by extending the service.
- Well-Documented: Clear comments and instructions throughout the code, along with this detailed README.
-
Clone the repository:
git clone https://github.com/ojaydev/usestripe.git cd usestripe
-
Install the required dependencies:
npm install
-
Set up your environment variables by creating a
.env
file in the root directory:STRIPE_SECRET_KEY=your_stripe_secret_key
Import the StripeService
in your project:
const StripeService = require('./stripeService');
Make sure your .env
file contains the correct Stripe secret key:
STRIPE_SECRET_KEY=your_stripe_secret_key
const customerData = {
email: 'customer@example.com',
name: 'John Doe',
description: 'A sample customer',
};
StripeService.createCustomer(customerData)
.then(customer => console.log('Customer Created:', customer))
.catch(error => console.error('Error creating customer:', error));
const customerId = 'cus_Jt85EFV9G6rKQa';
StripeService.retrieveCustomer(customerId)
.then(customer => console.log('Customer Retrieved:', customer))
.catch(error => console.error('Error retrieving customer:', error));
const paymentData = {
amount: 2000,
currency: 'usd',
payment_method_types: ['card'],
};
StripeService.createPaymentIntent(paymentData)
.then(paymentIntent => console.log('Payment Intent Created:', paymentIntent))
.catch(error => console.error('Error creating payment intent:', error));
const paymentIntentId = 'pi_1JXSl2FZ8Kr1z';
StripeService.confirmPaymentIntent(paymentIntentId)
.then(paymentIntent => console.log('Payment Intent Confirmed:', paymentIntent))
.catch(error => console.error('Error confirming payment intent:', error));
const chargeData = {
amount: 1500,
currency: 'usd',
source: 'tok_visa', // A token generated from Stripe's frontend SDK
description: 'Sample Charge',
};
StripeService.createCharge(chargeData)
.then(charge => console.log('Charge Created:', charge))
.catch(error => console.error('Error creating charge:', error));
const chargeId = 'ch_1JXSl2FZ8Kr1z';
StripeService.captureCharge(chargeId)
.then(charge => console.log('Charge Captured:', charge))
.catch(error => console.error('Error capturing charge:', error));
const refundData = {
charge: 'ch_1JXSl2FZ8Kr1z',
amount: 1500,
};
StripeService.createRefund(refundData)
.then(refund => console.log('Refund Created:', refund))
.catch(error => console.error('Error creating refund:', error));
const productData = {
name: 'Sample Product',
description: 'This is a sample product',
};
StripeService.createProduct(productData)
.then(product => console.log('Product Created:', product))
.catch(error => console.error('Error creating product:', error));
const subscriptionData = {
customer: 'cus_Jt85EFV9G6rKQa',
items: [{ price: 'price_1JXSl2FZ8Kr1z' }],
};
StripeService.createSubscription(subscriptionData)
.then(subscription => console.log('Subscription Created:', subscription))
.catch(error => console.error('Error creating subscription:', error));
const express = require('express');
const StripeService = require('./stripeService');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
const stripeSignature = req.headers['stripe-signature'];
const webhookSecret = 'whsec_...'; // Your webhook secret
StripeService.handleWebhook(req, stripeSignature, webhookSecret, (err, event) => {
if (err) {
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log('PaymentIntent was successful!');
break;
// Other event types
default:
console.log(`Unhandled event type ${event.type}`);
}
res.json({ received: true });
});
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
The boilerplate covers a wide range of Stripe API operations. Here’s a list of all the available functions:
-
Customer Operations
createCustomer(customerData)
retrieveCustomer(customerId)
updateCustomer(customerId, updateData)
deleteCustomer(customerId)
listCustomers(listParams)
-
Payment Intent Operations
createPaymentIntent(paymentData)
retrievePaymentIntent(paymentIntentId)
confirmPaymentIntent(paymentIntentId, confirmParams)
cancelPaymentIntent(paymentIntentId)
listPaymentIntents(listParams)
-
Charge Operations
createCharge(chargeData)
retrieveCharge(chargeId)
updateCharge(chargeId, updateData)
captureCharge(chargeId)
listCharges(listParams)
-
Refund Operations
createRefund(refundData)
retrieveRefund(refundId)
listRefunds(listParams)
-
Product Operations
createProduct(productData)
retrieveProduct(productId)
updateProduct(productId, updateData)
deleteProduct(productId)
listProducts(listParams)
-
Price Operations
createPrice(priceData)
retrievePrice(priceId)
updatePrice(priceId, updateData)
listPrices(listParams)
-
Subscription Operations
createSubscription(subscriptionData)
retrieveSubscription(subscriptionId)
updateSubscription(subscriptionId, updateData)
cancelSubscription(subscriptionId)
listSubscriptions(listParams)
-
Webhook Handling
handleWebhook(request, stripeSignature, webhookSecret, callback)
This boilerplate is designed to be easily extendable. If you need to add more functionality, simply add a new method to the StripeService
object in stripeService.js
:
const StripeService = {
// Existing methods...
// New method
createSomethingNew: async (data) => {
return await stripe.something.create(data);
},
};
module.exports = StripeService;
Contributions are welcome! If you have ideas for improvements or additional features, feel free to fork the repository and submit a pull request.
- Fork the repository.
- Create a new branch (
git checkout -b feature/new-feature
). - Make your changes.
- Commit your changes (
git commit -m 'Add new feature'
). - Push to the branch (
git push origin feature/new-feature
). - Open a pull request.