Skip to content

PayrePay API

Constructor

ts
import { PayrePay } from '@payre/pay';

const payre = new PayrePay({
  secretKey: string,      // Required. Your pyr_sk_live_xxx key
  baseUrl?: string,       // Optional. Default: 'https://api.payre.dev'
  timeout?: number,       // Optional. Default: 5000 (5s)
});

Throws if secretKey doesn't start with pyr_sk_.

charge()

The core method. Validates the consumer, checks balance, deducts amount, and returns a signed receipt.

ts
const receipt = await payre.charge({
  apiKey: string,    // Consumer's pyr_ck_live_xxx key
  tool: string,      // Tool name (e.g. 'search')
  amount: number,    // USD amount (e.g. 0.005)
});

Returns:

ts
{
  chargeId: string;      // Unique charge ID
  receipt: string;       // HMAC-SHA256 signed receipt
  balance: number;       // Consumer's remaining balance
}

Throws:

err.codeMeaning
'insufficient_balance'Consumer balance < amount
'invalid_api_key'Consumer key is invalid or missing
'payre_unavailable'Could not reach api.payre.dev (timeout or network error)

Example:

ts
try {
  const receipt = await payre.charge({
    apiKey: req.headers['x-payre-key'],
    tool: 'search',
    amount: 0.005,
  });
  // Payment succeeded -- execute tool
} catch (err) {
  if (err.code === 'insufficient_balance') {
    return { error: 'Please top up at console.payre.dev' };
  }
  if (err.code === 'payre_unavailable') {
    // Graceful degradation: allow free access when Payre is down
    return doSearchForFree(params);
  }
  throw err;
}

pricing()

Helper for servers with multiple tools at different prices.

ts
const pricing = payre.pricing({
  'search':   0.005,
  'generate': 0.02,
  'analyze':  0.01,
});

Returns: A PayrePricing object with one method:

PayrePricing.charge()

ts
const receipt = await pricing.charge({
  apiKey: string,    // Consumer's key
  tool: string,      // Must match a key in the price map
});

The amount is looked up from the price map. Throws Error('Unknown tool: xxx') if the tool name isn't in the map.

Example:

ts
const pricing = payre.pricing({
  'search': 0.005,
  'generate': 0.02,
});

// In your search handler:
const receipt = await pricing.charge({
  apiKey: req.headers['x-payre-key'],
  tool: 'search',  // Automatically charges $0.005
});

// In your generate handler:
const receipt = await pricing.charge({
  apiKey: req.headers['x-payre-key'],
  tool: 'generate',  // Automatically charges $0.02
});