Integrate with Express
Add billing and payments to your Express application.
Install the Commet Skill so your coding agent can integrate the current SDK and verify its work against the live API contract.
npx skills add commet-labs/skills --skill commetInstall
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!,
})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.checkoutUrl ?? null })
})
export default routerCheck Access
router.get('/subscription/:customerId', async (req, res) => {
const subscription = await commet.subscriptions.getActive({ customerId: req.params.customerId })
if (!subscription) {
return res.status(404).json({ error: 'no_active_subscription' })
}
res.json({ status: subscription.status })
})
router.get('/features/:feature/:customerId', async (req, res) => {
const access = await commet.featureAccess.get({
code: req.params.feature,
customerId: req.params.customerId,
})
res.json({ allowed: access.allowed })
})Track Usage
router.post('/usage', async (req, res) => {
await commet.usage.track({
customerId: req.body.customerId,
featureCode: '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 portal = await commet.portal.getUrl({
customerId: req.user.customerId,
})
res.redirect(portal.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?