Package Exports
- payflow-sdk
Readme
@payflow/sdk
TypeScript SDK for PayFlow — pay for any AI service per request via the Machine Payments Protocol.
One SDK, 54+ services. No API keys to manage per service. Just connect and pay.
Install
npm install @payflow/sdk
# or
pnpm add @payflow/sdkQuick Start
import { PayFlow } from '@payflow/sdk'
const pf = new PayFlow({
apiKey: 'payflow_ak_xxxxx', // from Settings → Agents
baseUrl: 'http://46.62.246.59:8080', // PayFlow API server
})
const results = await pf.search('AI agent payments')
console.log(results) // { results: [{ title, url, ... }] }Five lines. Auto-paid via Tempo micropayments.
Core API
pf.request(opts) — Call any MPP service
const result = await pf.request({
service: 'exa', // service ID
path: '/search', // endpoint path
method: 'POST', // default: 'POST'
payload: { query: 'AI agents', numResults: 5 },
})
// result: { success: true, data: {...}, cost: '~$0.001-0.01', duration: 342 }pf.fetch(url, opts?) — Direct URL request
const result = await pf.fetch('https://exa.mpp.tempo.xyz/search', {
method: 'POST',
body: { query: 'hello' },
})pf.getBalance() — Wallet balance
const balance = await pf.getBalance()
// { total: '15.00', available: '10.44', locked: '4.56', activeSessions: 3, symbol: 'USDC' }pf.getSpendingLimits() — Active spending limits
const limits = await pf.getSpendingLimits()
// [{ id, type: 'global'|'per_service', amountUsd, currentSpent, serviceId }]pf.getTransactions(opts?) — Transaction history
const txs = await pf.getTransactions({ limit: 10 })
// [{ id, serviceName, method, amount, duration, status, timestamp, responsePreview }]pf.getServices() — List all services
const services = await pf.getServices()
// [{ id: 'exa', name: 'Exa', endpoint: 'https://exa.mpp.tempo.xyz', category: 'search', ... }]Service list is cached per instance. Call pf.clearServiceCache() to refresh.
Shortcut Methods
pf.chat(message, opts?) — LLM call
// Simple string
const response = await pf.chat('Explain micropayments in 2 sentences', {
provider: 'openrouter', // openai | anthropic | openrouter | gemini
model: 'openai/gpt-4o-mini',
maxTokens: 200,
})
console.log(response.choices[0].message.content)
// Multi-turn conversation
const response2 = await pf.chat([
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'What is MPP?' },
])Default provider: openrouter. Default model: openai/gpt-4o-mini.
pf.search(query, opts?) — Web search
const { results } = await pf.search('AI payments 2025', {
provider: 'exa', // exa | stableenrich
numResults: 5,
})
results.forEach(r => console.log(r.title, r.url))pf.generateImage(prompt, opts?) — Image generation
const image = await pf.generateImage('a blue cat in space', {
provider: 'fal', // fal | stability-ai | replicate
model: 'flux-schnell',
})pf.scrape(url, opts?) — Web scraping
const page = await pf.scrape('https://example.com', {
provider: 'firecrawl', // firecrawl | oxylabs
})Error Handling
All errors throw PayFlowError with structured code, message, and status:
import { PayFlow, PayFlowError } from '@payflow/sdk'
try {
await pf.search('test')
} catch (err) {
if (err instanceof PayFlowError) {
console.error(err.code) // 'INVALID_API_KEY', 'UNKNOWN_SERVICE', 'SPENDING_LIMIT_EXCEEDED', ...
console.error(err.message) // Human-readable description
console.error(err.status) // HTTP status (401, 403, 500) or 0 for network errors
}
}| Code | Meaning |
|---|---|
MISSING_API_KEY |
No apiKey provided in constructor |
INVALID_API_KEY |
API key rejected (401) |
UNKNOWN_SERVICE |
Service ID not found |
UNKNOWN_PROVIDER |
Shortcut method provider not recognized |
SPENDING_LIMIT_EXCEEDED |
Agent hit spending limit |
AGENT_PAUSED |
Agent is paused in settings |
TIMEOUT |
Request exceeded timeout |
NETWORK_ERROR |
Cannot reach PayFlow API |
API_ERROR |
Generic server error |
Examples
Research Agent
import { PayFlow } from '@payflow/sdk'
const pf = new PayFlow({ apiKey: process.env.PAYFLOW_KEY! })
// Search → summarize pipeline
const { results } = await pf.search('quantum computing breakthroughs 2025', { numResults: 3 })
const summary = await pf.chat(
`Summarize these sources:\n${results.map(r => `- ${r.title}: ${r.url}`).join('\n')}`,
{ model: 'openai/gpt-4o-mini' },
)
console.log(summary.choices[0].message.content)Content Agent
const pf = new PayFlow({ apiKey: process.env.PAYFLOW_KEY! })
// Generate image + caption in parallel
const [image, caption] = await Promise.all([
pf.generateImage('minimalist logo for an AI startup', { provider: 'fal' }),
pf.chat('Write a tweet about launching an AI startup', { maxTokens: 100 }),
])
console.log(caption.choices[0].message.content)Data Agent
const pf = new PayFlow({ apiKey: process.env.PAYFLOW_KEY! })
// Scrape → extract → check budget
const page = await pf.scrape('https://techcrunch.com', { provider: 'firecrawl' })
const analysis = await pf.chat(
`Extract the top 3 headlines from this page: ${JSON.stringify(page).slice(0, 2000)}`,
)
const balance = await pf.getBalance()
console.log(`Remaining: ${balance.available} ${balance.symbol}`)
const txs = await pf.getTransactions({ limit: 5 })
console.log(`Last 5 costs: ${txs.map(t => t.amount).join(', ')}`)Configuration
const pf = new PayFlow({
apiKey: 'payflow_ak_xxxxx', // required — agent API key
baseUrl: 'http://46.62.246.59:8080', // optional — API server URL
timeout: 30_000, // optional — request timeout in ms (default: 60s)
})Authentication
The SDK authenticates via agent API keys created in Settings → Agents. Each key is scoped to one agent with its own spending limits and transaction history.
Authorization: Bearer payflow_ak_xxxxxPublishing
cd packages/sdk
pnpm build # generates dist/ with ESM + CJS + types
npm login # authenticate with npm
npm publish --access publicLicense
MIT