使用 Stripe Mongoose API 实现 API 货币化
我们生活在一个高度数字化的世界,一个 Web API 就能创造百万美元的生意。在本文中,我将向您展示如何使用名为Stripe Mongoose Api 的库来实现 API 的货币化。
设置您的项目
要求
- MongoDB 可以安装在您的计算机上,也可以连接到在线的 MongoDB 集群。
- Stripe账户
首先我们需要安装所有依赖项:
npm install stripe-mongoose-api stripe mongoose express ejs
现在我们可以开始构建自己的项目了,我会一步一步地指导你:
- 创建 app.js 和 userModel.js
- 在 userModel.js 中创建一个模型
- 添加 Mongoose 连接
- 快速设置
- 基本路由
- 添加 Stripe Mongoose API 功能
您可以在这里找到源代码。
1. 创建 user.js 和 userModel.js
使用以下命令创建文件夹:
mkdir <folderName>
在文件夹中创建新文件:app.js 和 userModel.js(您可以随意命名此文件,但建议这样命名)。
2. 在 userModel.js 中创建一个模型
为了简化工作,我们将创建一个非常简单的模式,其中不包含任何模式字段,但您可以根据需要添加任何字段。
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)
<options>您必须在此字段中提供一个包含以下内容的对象:
{
stripeSecret: 'your stripe secret key',
webhookSign: 'your stripe webhook sign key',
priceId: 'the price id of your product'
}
这些是“必须提供”的选项,但您可以查看文档并选择要添加的其他选项。
3. 添加 Mongoose 连接
接下来我们打开 app.js 文件,将以下代码添加到该文件中:
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');
现在,如果您尝试运行该文件并且一切顺利,您将在控制台中看到:“数据库已连接”。
4. 快速设置
安装并运行 express:
const express = require('express');
const app = express();
app.use(express.json({verify: (req, res, buffer) => (req['rawBody'] = buffer)}));
express.json 是本项目必不可少的中间件,因为如果没有它,Stripe Mongoose API 将无法理解 webhook 请求。
添加视图:
const path = require('path');
const ejs = require('ejs');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
创建一个名为“views”的文件夹,并使用以下命令:
mkdir views
将此.ejs 文件复制到文件夹内,它是一个简单的 html 页面,可为您提供 Stripe Mongoose API 提供的所有功能。
5. 基本路由
路由器对于 API 的正常运行至关重要,因为它们能够接收和处理用户发出的请求。
// 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}`);
})
现在,您可以运行node app.js并查看您的应用程序是否正常工作了。现在您知道使用 Stripe Mongoose API 创建 API 并将其货币化是多么简单了。
结论
Stripe Mongoose API 是我开发的一个项目,我投入了大量心血。Stripe Mongoose API 会持续更新,请关注GitHub 代码库以获取最新内容。希望您喜欢这篇教程,如果喜欢,请给我点个赞,也欢迎在 GitHub 上关注我。下次见!
文章来源:https://dev.to/marcomoscatelli/monetize-your-api-using-stripe-mongoose-api-4k1o