Skip to navigation

TypeScript SDK API reference

Every public function and type in @mitulabs/payments, with what each one does and when.

View as Markdown

The package is split into a core and a set of framework adapters. The core, imported from @mitulabs/payments, contains the client and the shared types. Each adapter lives in its own subpath, such as @mitulabs/payments/express, so your application only loads the code for the framework you use. Every adapter is built on the same core method, mitu.admit(), which means they all behave identically.

For the options you can pass when creating a client, see Configuration. For the failures you may need to handle, see Errors.

Import pathWhat it provides
@mitulabs/paymentsThe client, the error classes and all of the shared types
@mitulabs/payments/expressMiddleware for Express
@mitulabs/payments/honoMiddleware for Hono
@mitulabs/payments/nextA route handler wrapper for the Next.js App Router
@mitulabs/payments/elysiaHooks for Elysia
@mitulabs/payments/fetchA handler wrapper for Fetch API runtimes such as Cloudflare Workers, Deno and Bun

Every adapter also re-exports the price and payment types, so you can import them from whichever path you are already using.

The client

createMitu

function createMitu(options: CreateMituOptions): Mitu

Creates a Mitu client from your options. The function validates the key and the default currency immediately and throws a MituConfigError if either is invalid. It does not make any network calls. Create a single client when your application starts and pass it to every route that charges.

mitu.admit

admit(request: Request, price: Price<Request>): Promise<Admission>

Decides whether a single request may go through. This is the method every adapter calls internally, and it is also how you add payments to a framework that has no adapter. It takes a standard Fetch API Request and the price for the route, and it returns an Admission describing what to do next.

  • The request carries no payment.
    The method asks Mitu to create one and returns admitted: false with a 402 Payment Required response. Send that response to the caller as it is.
  • The request carries a valid payment.
    The payment is for this route and price, so Mitu settles it and the method returns admitted: true with the payment and a set of receipt headers. Serve the request, then copy those headers onto your response.
  • The price is null.
    The request is treated as free. The method returns admitted: true with no payment and does not contact Mitu.

The example below shows the complete pattern for a custom integration.

const admission = await mitu.admit(request, { amount: '0.05' })
if (!admission.admitted) return admission.response
const response = await handle(request, admission.payment)
for (const [name, value] of admission.headers) response.headers.set(name, value)
return response

mitu.defaultCurrency

readonly defaultCurrency: string

The default currency the client was created with, always in upper case.

Adapters

Each adapter provides a charge function that puts a route behind a payment. When you register a route with a fixed price, charge checks the price immediately, so an invalid amount stops your server at startup rather than failing on a live request.

Express

function charge(mitu: Mitu, price: Price<express.Request>): RequestHandler

Returns Express middleware. Place it before your handler. Once the payment has settled, the middleware calls the next handler and makes the payment available on req.mitu.payment.

import { charge } from '@mitulabs/payments/express'
app.get('/v1/search', charge(mitu, { amount: '0.05' }), (req, res) => {
res.json(search(req.query, req.mitu?.payment))
})

Hono

function charge(mitu: Mitu, price: Price<Context<MituEnv>>): MiddlewareHandler<MituEnv>

Returns Hono middleware. Type your application with MituEnv so that TypeScript knows about the payment, which your handler reads with c.get('mitu').payment.

import { charge, type MituEnv } from '@mitulabs/payments/hono'
const app = new Hono<MituEnv>()
app.get('/v1/search', charge(mitu, { amount: '0.05' }), (c) => c.json(search(c.req.query(), c.get('mitu').payment)))

Next.js App Router

function charge(mitu: Mitu, price: Price<Request>): (handler: PaidRouteHandler) => RouteHandler

Wraps a route handler. Your handler receives the request in the usual way, and its second argument contains the route params together with the settled payment.

import { charge } from '@mitulabs/payments/next'
export const POST = charge(mitu, { amount: '0.50' })(async (request, { payment }) =>
Response.json(await summarize(await request.json(), payment)),
)

Elysia

function charge(mitu: Mitu, price: Price<Request>): ChargeHooks
function mituOf(request: Request): PaymentContext | undefined

Returns hooks to pass to .guard(). Every route defined inside that guard is charged at the given price. Inside a handler, call mituOf(request) to read the payment.

import { charge, mituOf } from '@mitulabs/payments/elysia'
new Elysia().guard(charge(mitu, { amount: '0.05' }), (app) =>
app.get('/v1/search', ({ request }) => search(request, mituOf(request)?.payment)),
)

Fetch API runtimes

function charge(mitu: Mitu, price: Price<Request>): (handler: FetchHandler) => FetchHandler

Wraps a standard Fetch API handler, which makes it suitable for Cloudflare Workers, Deno and Bun. Your handler receives the request, then an object containing the payment, then any further arguments the runtime provides, such as env and ctx on Cloudflare Workers.

import { charge } from '@mitulabs/payments/fetch'
export default {
fetch: charge(mitu, { amount: '0.05' })((request, { payment }) => Response.json(search(request, payment))),
}

Prices

A price tells the SDK how much a route costs. You can give a fixed set of terms, null for a free route, or a function that decides the price for each request.

interface PriceTerms {
amount: string
currency?: string
description?: string
}
type Price<Input> = PriceTerms | null | ((input: Input) => PriceTerms | null | Promise<PriceTerms | null>)
FieldDescription
amountThe price as a decimal string, such as '0.05' or '2500'. It must be greater than zero and can have at most two decimal places.
currencyThe currency code for this price. If you leave it out, the client’s default currency is used.
descriptionA short label shown to the caller in the payment challenge. If you leave it out, the SDK uses the request method and path.

The examples below cover the common cases.

// A fixed price in the default currency
charge(mitu, { amount: '0.05' })
// A fixed price in a named currency, with a description
charge(mitu, { amount: '2500', currency: 'NGN', description: 'Search' })
// A price that depends on the caller's plan
charge(mitu, (req) => (isPremium(req) ? { amount: '1.00' } : { amount: '0.10' }))
// A route that is free for some callers
charge(mitu, (req) => (isFree(req) ? null : { amount: '0.05' }))

When you use a function, keep three rules in mind.

  • It must return the same price twice.
    The SDK calls the function on the first, unpaid request and again when the caller retries with payment. If the two answers differ, the payment will not match and the caller will be asked to pay again.
  • It can make a request free.
    Returning null serves that request without creating a payment.
  • It must never trust the request body.
    Base the price on information you control, such as the caller’s plan or a stored order total.

Payment

When a request has been paid, your handler receives a Payment describing it. For a free request the payment is null.

interface Payment {
id: string
reference: string
txHash: string | null
amountPaid: string
currency: string
network: string | null
paymentMethod: string | null
}
interface PaymentContext {
payment: Payment | null
}
FieldDescription
idMitu’s identifier for the payment. It matches the identifier in the payment.completed webhook, so you can link the two.
referenceA unique reference the SDK gave the payment when it was created.
txHashThe hash of the settlement transaction. It is null when the payment method does not settle onchain.
amountPaidThe amount the caller paid, as a decimal string.
currencyThe currency of amountPaid.
networkThe network the payment settled on, such as base, tempo or solana.
paymentMethodThe payment method the caller used, as Mitu names it.

Admission

type Admission =
| { admitted: true; payment: Payment | null; headers: Headers }
| { admitted: false; response: Response }

The result of mitu.admit(). When admitted is true, serve the request and add the headers to your response, because they carry the payment receipt. When admitted is false, send the response to the caller unchanged. It will be a payment challenge, a refusal from Mitu, or a 503 while Mitu is unavailable.