Content
# paygate-402





> Turn any API or MCP server into a paid service
## table of contents
- [install](#install)
- [usage](#usage)
- [api](#api)
- [configuration](#configuration)
- [payment providers](#payment-providers)
- [http 402](#http-402)
- [contributing](#contributing)
- [license](#license)
## install
```bash
npm install paygate-402
```
## usage
### wrap an existing API
```typescript
import { PayGate } from 'paygate-402';
const paygate = new PayGate({
provider: 'stripe',
apiKey: process.env.STRIPE_KEY,
pricing: {
perRequest: 0.01,
perToken: 0.0001
}
});
// wrap your express app
app.use(paygate.middleware());
// or wrap specific routes
app.get('/api/premium', paygate.protect(), (req, res) => {
res.json({ data: 'premium content' });
});
```
### wrap an MCP server
```typescript
import { MCPPayGate } from 'paygate-402/mcp';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
const server = new Server({
name: 'my-mcp-server',
version: '1.0.0'
});
const paygate = new MCPPayGate({
provider: 'stripe',
apiKey: process.env.STRIPE_KEY,
pricing: {
perTool: {
'expensive_tool': 0.10,
'cheap_tool': 0.01
}
}
});
paygate.wrap(server);
```
### client usage
```typescript
import axios from 'axios';
const response = await axios.get('https://api.example.com/premium', {
headers: {
'Authorization': 'Bearer YOUR_PAYMENT_TOKEN'
}
});
// handle 402 Payment Required
if (response.status === 402) {
const paymentUrl = response.headers['payment-url'];
console.log('Payment required:', paymentUrl);
}
```
## api
### `PayGate(options)`
Creates a new payment gateway instance.
**Options:**
| Option | Type | Description |
|--------|------|-------------|
| `provider` | `string` | Payment provider (`'stripe'`, `'paypal'`, `'lightning'`) |
| `apiKey` | `string` | Provider API key |
| `pricing` | `PricingConfig` | Pricing configuration |
| `allowCredits` | `boolean` | Allow prepaid credits (default: `true`) |
| `quotaLimits` | `QuotaConfig` | Optional rate limits per user |
### `paygate.middleware()`
Returns Express middleware that intercepts requests and enforces payment.
### `paygate.protect(options?)`
Returns middleware for protecting specific routes.
**Options:**
| Option | Type | Description |
|--------|------|-------------|
| `price` | `number` | Override default price for this route |
| `creditsRequired` | `number` | Require specific credit amount |
### `paygate.createPaymentToken(userId, credits)`
Generates a payment token for a user with prepaid credits.
**Returns:** `Promise<string>`
### `paygate.checkBalance(token)`
Checks remaining balance for a payment token.
**Returns:** `Promise<{ credits: number, spent: number }>`
## configuration
### pricing models
```typescript
// per-request pricing
{
pricing: {
perRequest: 0.05
}
}
// token-based pricing (for LLM APIs)
{
pricing: {
perToken: 0.0001,
perInputToken: 0.00005,
perOutputToken: 0.00015
}
}
// route-specific pricing
{
pricing: {
routes: {
'/api/basic': 0.01,
'/api/premium': 0.10,
'/api/enterprise': 1.00
}
}
}
// credit bundles
{
pricing: {
bundles: [
{ credits: 100, price: 9.99 },
{ credits: 500, price: 44.99 },
{ credits: 1000, price: 79.99 }
]
}
}
```
## payment providers
### stripe
```typescript
{
provider: 'stripe',
apiKey: process.env.STRIPE_SECRET_KEY,
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET
}
```
### paypal
```typescript
{
provider: 'paypal',
clientId: process.env.PAYPAL_CLIENT_ID,
clientSecret: process.env.PAYPAL_CLIENT_SECRET,
sandbox: true
}
```
### lightning network
```typescript
{
provider: 'lightning',
lndHost: process.env.LND_HOST,
macaroon: process.env.LND_MACAROON,
cert: process.env.LND_CERT
}
```
## http 402
This project uses HTTP status code 402 (Payment Required) as defined in RFC 7231. When a request requires payment, the server responds with:
```http
HTTP/1.1 402 Payment Required
Payment-URL: https://pay.example.com/checkout/xyz123
Payment-Amount: 0.05
Payment-Currency: USD
Content-Type: application/json
{
"error": "payment_required",
"amount": 0.05,
"currency": "USD",
"payment_url": "https://pay.example.com/checkout/xyz123"
}
```
## contributing
PRs welcome. Open an issue first for big changes.
Run tests:
```bash
npm test
```
## license
MIT
Connection Info
You Might Also Like
Vibe-Trading
Vibe-Trading: Your Personal Trading Agent
ai-berkshire
Berkshire in the AI Era: A Value Investment Research Framework Based on...
hexstrike-ai
HexStrike AI is an AI-powered MCP cybersecurity automation platform with 150+ tools.
valuecell
Valuecell is a Python project for efficient data management.
tradingview-mcp
AI-assisted TradingView chart analysis — connect Claude Code to your...
tradingview-mcp
TradingView MCP Server offers real-time market analysis for crypto and stocks.