Often when building an e-commerce application or billing system, you want to add a payment processor to your application. One of the most common payment processors to use is Stripe. Stripe API is well documented and accepts payment methods from several dozen countries. In this tutorial, we’ll go over how to add customers to your Stripe account using the API. You can look at the repo here or review some of our video tutorials here.

Stripe API Project Setup

Stripe comes with a Node.JS package that allows for users to make requests to its API. We’ll be using NestJS so not only will we be using the node package, we’ll also be using the @typings package for better Typescript integration in our IDE.

Inside of your NestJS application add the following packages. This will add Stripe to your application.

npm install stripe --save
npm install @types/stripe –save-dev

Once that is finished, we’ll want to add our domain for managing our customers. We’ll add a controller, a service and a module.

nest generate module customers 
nest generate controller customers
nest generate service customers

We can also add a DTO called CreateCustomerDTO in order to represent the customers that we will create later on.

The final step is creating a configuration file. Create a folder called stripe and then export your stripe instance with your secret key.

import * as Stripe from 'stripe';
export const stripe = new Stripe('sk_test_....');

Creating the Stripe Customer Service

We’ll first create the Customer Service. This is an injectable class that we can later reference inside of our Controller. We’ll create basic CRUD functions as well as import our configuration. We will not create interfaces for the return values because those are already included in the Stripe package.

import { Injectable } from '@nestjs/common';
import Stripe from 'stripe';
import { stripe } from '../stripe/stripe';
@Injectable()
export class CustomersService {
  private readonly stripe: Stripe = stripe;

  async findAllCustomers(): Promise<Stripe.IList<Stripe.customers.ICustomer>>{
    const customers = await this.stripe.customers.list();
    return customers;
  }

  async findCustomer(id: string): Promise<Stripe.customers.ICustomer> {
    const customer = await this.stripe.customers.retrieve(id);
    return await customer;
  }

  async createCustomer(customerInfo: Stripe.customers.ICustomerCreationOptions ): Promise<Stripe.customers.ICustomer> {
    const customer = await this.stripe.customers.create(customerInfo);
    return customer;
  }

  async updateCustomer(id: string, customerInfo: Stripe.customers.ICustomerUpdateOptions): Promise<Stripe.customers.ICustomer> {
    const customer = await this.stripe.customers.update(id, customerInfo);
    return customer;

  }

  async deleteCustomer(id: string): Promise<Stripe.IDeleteConfirmation> {
    const deletetionConfirmation = await this.stripe.customers.del(id);
    return deletetionConfirmation;
  }
}

As you can see the main interfaces that we use are Stripe.customers.ICustomer , Stripe.customers.ICustomerCreationOptions, Stripe.customers.ICustomerUpdateOptions, and Stripe.IDeleteConfirmation. These represent the parameters that we will accept into our service as well as the payload that we can expect. Many of the Interfaces have optional parameters that align with the Stripe API spec.

Stripe Customer DTO and Controller

We’ll want to modify our DTO to implement Stripe.customers.ICustomerCreationOptions. That way we accept all of the optional parameters for creating a customer.

import { ApiModelProperty } from '@nestjs/swagger';
import Stripe from 'stripe';

export class CreateCustomerDto implements Stripe.customers.ICustomerCreationOptions {
}

Next, in our controller, we will want to implement routes that return that data from our service.

import {
  Controller,
  Get,
  Response,
  HttpStatus,
  Param,
  Body,
  Post,
  Request,
  Patch,
  Delete,
} from '@nestjs/common';
import { CustomersService } from './customers.service';
import { CreateCustomerDto } from './dto/createCustomer.dto';

@Controller('customers')
export class CustomersController {
  constructor(private readonly customersService: CustomersService) {}

  @Get()
  public async getCustomers(@Response() res) {
    const customers = await this.customersService.findAllCustomers();
    return res.status(HttpStatus.OK).json(customers);
  }

  @Get('/:id')
  public async getCustomer(@Response() res, @Param() param) {
    const customer = await this.customersService.findCustomer(param.id);
    return res.status(HttpStatus.OK).json(customer);
  }

  @Post()
  public async createCustomer(
    @Response() res,
    @Body() createCustomerDTO: CreateCustomerDto,
  ) {
    const customer = await this.customersService.createCustomer(
      createCustomerDTO,
    );
    return res.status(HttpStatus.OK).json(customer);
  }

  @Patch('/:id')
  public async updateCustomer(@Param() param, @Response() res, @Body() body) {
    const customer = await this.customersService.updateCustomer(param.id, body);
    return res.status(HttpStatus.OK).json(customer);
  }

  @Delete('/:id')
  public async deleteCustomer(@Param() param, @Response() res){
      const confirmation = await this.customersService.deleteCustomer(param.id);
      return res.status(HttpStatus.OK).json(confirmation);
  }
}

Now that our controller is setup, we can successfully run CRUD operations on our Stripe API customer endpoints.

Return All Customers Stripe API Node.js

Return All Customers Stripe API Node.js

 

Create Customer Node Stripe API

Create Customer Node Stripe API

Conclusion

Integrating the Stripe API with Node.js is extremely simple. The documentation, as well as the video tutorials that go over Stripe integration, allow for easy development of your next project. Feel free to review any of our videos and let us know what you think. If you’re interested in posts on NestJS, check out our article on NestJS JWT Authentication.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit