Skip to content

ojaydev/usestripe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


UseStripe - Stripe Service Boilerplate for Node.js

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.

Table of Contents

Features

  • 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.

Installation

  1. Clone the repository:

    git clone https://github.com/ojaydev/usestripe.git
    cd usestripe
  2. Install the required dependencies:

    npm install
  3. Set up your environment variables by creating a .env file in the root directory:

    STRIPE_SECRET_KEY=your_stripe_secret_key

Setup

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

Usage

Customer Operations

Example: Creating a Customer

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

Example: Retrieving a Customer

const customerId = 'cus_Jt85EFV9G6rKQa';

StripeService.retrieveCustomer(customerId)
    .then(customer => console.log('Customer Retrieved:', customer))
    .catch(error => console.error('Error retrieving customer:', error));

Payment Intent Operations

Example: Creating a Payment Intent

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

Example: Confirming a Payment Intent

const paymentIntentId = 'pi_1JXSl2FZ8Kr1z';

StripeService.confirmPaymentIntent(paymentIntentId)
    .then(paymentIntent => console.log('Payment Intent Confirmed:', paymentIntent))
    .catch(error => console.error('Error confirming payment intent:', error));

Charge Operations

Example: Creating a Charge

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

Example: Capturing a Charge

const chargeId = 'ch_1JXSl2FZ8Kr1z';

StripeService.captureCharge(chargeId)
    .then(charge => console.log('Charge Captured:', charge))
    .catch(error => console.error('Error capturing charge:', error));

Refund Operations

Example: Creating a Refund

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

Product Operations

Example: Creating a Product

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

Subscription Operations

Example: Creating a Subscription

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

Webhook Handling

Example: Handling a Webhook

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');
});

Available Functions

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)

Extending the Boilerplate

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;

Contributing

Contributions are welcome! If you have ideas for improvements or additional features, feel free to fork the repository and submit a pull request.

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/new-feature).
  3. Make your changes.
  4. Commit your changes (git commit -m 'Add new feature').
  5. Push to the branch (git push origin feature/new-feature).
  6. Open a pull request.

About

UseStripe - Stripe Service Boilerplate for Node.js: Simplify Your Stripe Integrations.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published