Integrate with Express
Add billing and payments to your Express application.
Use this pre-built prompt to integrate Commet faster with AI assistants.
Install
pnpm add @commet/node expressnpm install @commet/node expressyarn add @commet/node expressConfigure
COMMET_API_KEY=ck_sandbox_xxximport { Commet } from '@commet/node'
export const commet = new Commet({
apiKey: process.env.COMMET_API_KEY!,
environment: 'sandbox',
})Subscribe
import { Router } from 'express'
import { commet } from '../commet'
const router = Router()
router.post('/subscribe', async (req, res) => {
const { customerId, email } = req.body
await commet.customers.create({ email, id: customerId })
const subscription = await commet.subscriptions.create({
customerId,
planCode: 'pro',
})
res.json({ checkoutUrl: subscription.data.checkoutUrl })
})
export default routerCheck Access
router.get('/subscription/:customerId', async (req, res) => {
const { data } = await commet.subscriptions.get(req.params.customerId)
res.json({ status: data.status })
})
router.get('/features/:feature/:customerId', async (req, res) => {
const { data } = await commet.features.check({
code: req.params.feature,
customerId: req.params.customerId,
})
res.json({ allowed: data.allowed })
})Track Usage
router.post('/usage', async (req, res) => {
await commet.usage.track({
customerId: req.body.customerId,
feature: 'api_calls',
value: 1,
})
res.json({ tracked: true })
})Usage is aggregated and billed at end of period.
Customer Portal
router.get('/portal', async (req, res) => {
const { data } = await commet.portal.getUrl({
customerId: req.user.customerId,
})
res.redirect(data.portalUrl)
})Start Server
import express from 'express'
import billingRoutes from './routes/billing'
const app = express()
app.use(express.json())
app.use('/billing', billingRoutes)
app.listen(3000)Related
How is this guide?