We live in a world so immersed in digital 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 express ejs
Now we can start building our own project, I will guide you step by step:
- Create app.js and userModel.js
- Create a model in userModel.js
- Add mongoose connection
- Express set up
- Basic routing
- Adding Stripe Mongoose Api feautures
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'
}
This 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.
Conclusions
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!
Top comments (8)
Great tutorial.
Thank Andrew, glad you like it!
Look promising !! I stared it.
Thank you for the trust <3
I'll use this library in my next api!
Happy to help!
I am a newbie to javascript and I hope this will help me when I have to monetize an api
I hope so <3