Monetize your API using the Stripe Mongoose API Library

Written by moscatellimarco | Published 2022/03/13
Tech Story Tags: javascript | stripe | api | express | mongoose | api-monetization | web-monetization | web-development

TLDRvia the TL;DR App

We live in a world so immersed in technology where a web API can create a million-dollar business. In this article, I will show you how to monetize your API with a library called Stripe Mongoose Api.

Set up your project

requirements

  • MongoDB installed on your computer or an online MongoDB cluster

  • A Stripe account

First we need to install all the dependencies:

npm install stripe-mongoose-api stripe mongoose crypto express ejs colors

Now we can start building our own project, I will guide you step by step:

  1. Create app.js and userModel.js
  • Create a model in userModel.js
  • Add mongoose connection
  • Express set up
  • Basic routing
  • Adding Stripe Mongoose API features

You'll find the source code here.

1. Create user.js and userModel.js

Create a folder using:

mkdir <folderName>

Create new files in the folder: app.js and userModel.js (you can name this file whatever you want but is a convention to name this file like this)

2. Create a model in userModel.js

We will create a very simple schema with no schema fields to simplify our work, but you can just add whatever field you want.

const mongoose = require('mongoose');
const apiSystem = require('stripe-mongoose-api');

const userSchema = new mongoose.Schema({})

userSchema.plugin(apiSystem, <options>);

module.exports = mongoose.model('User', userSchema)

In the <options> field you must provide an object that contains:

{
  stripeSecret: 'your stripe secret key',
  webhookSign: 'your stripe webhook sign key',
  priceId: 'the price id of your product'
}

These are the 'must provide' options but you can just check the documentation and choose what other options to add.

3. Add mongoose connection

Let's move into app.js, add this code to the file:

const mongoose = require('mongoose');
const MONGO_URI = 'Your MongoDB uri'
mongoose.connect(MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
    console.log("Database connected");
});

const User = require('./userModel');

And now if you try to run the file and all went well you will see in the console: 'Database connected'.

4. Express set up

Require and run express:

const express = require('express');
const app = express();

app.use(express.json({verify: (req, res, buffer) => (req['rawBody'] = buffer)}));

express.json is a must have middleware for this project because without this Stripe Mongoose Api cannot understand the webhook requests. Add the views:

const path = require('path');
const ejs = require('ejs');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

Create a views folder and name it views using:

mkdir views

Copy this .ejs file inside the folder, it is a simple HTML page that will give you all the functionality provided by Stripe Mongoose API.

5. Basic routing

Routers are necessary for the functioning of the API as they will be able to receive and process requests made by users.

// Just rendering the home page
app.get('/', (req, res) => {
  res.render('home');
})

// This route will redirect the user to the stripe checkout
// page, if you don't pass a user as first param, the
// method will create a new one for you
app.get('/checkout', async (req, res) => {
  User.subscribeUser({}, res)
})
  
// This route listen to all requests sent by stripe, it
// listens for completed checkout and for cancelled
// subscriptions
app.post('/webhook', async (req, res) => {
  const  user  =  await User.findOne({})
  User.webhook(req, res)
})

// This route will listen to all requests sent by the users,
// it checks if the apiKey provided is valid and if yes, will
// create a usage record and then send the data in the second
// argument
app.get('/api', (req, res) => {
  User.api(res, {italy: 'hi from italy'}, req.query.apiKey)
})

// This route will send back the customer records
app.get('/usage', async (req, res) =>{
  const  user  =  await User.findById(req.query.customer);
  user.customerRecords(res)
})

// This route create a new api key for the user and
// destroy the old one
app.get('/changeapikey', async(req, res) => {
  const  user  =  await User.findById(req.query.id);
  const  key  =  await User.changeApiKey(user);
  res.send(key)
})

const  PORT  =  process.env.PORT  ||  3000;
app.listen(PORT, () => {
  console.log(`Serving on port ${PORT}`);
})

And now you are ready to run node app.js and see your app working properly, now you know how simple can be to create an API and monetize it using Stripe Mongoose API.

Conclusion

Stripe Mongoose API is a project made by me and I put in a lot of hard work, Stripe Mongoose Api will receive continuous updates so check the github repo in case of new content, i hope you liked this tutorial, if yes please leave me a star and why not a follow on GitHub.

See you next time!


Written by moscatellimarco | Hi, i am Moscatelli Marco, i like coding fullstack websites using MERN stack.
Published by HackerNoon on 2022/03/13