Payment routing SDK · Solana

Route smarter.
Settle faster.

A TypeScript SDK that auto-selects the optimal payment region for every transaction — by cost, success rate, and latency — through a single Layer-403 gateway.

MIT licensed TypeScript · ESM + CJS npm i github:matthewhron/primeflow
client.quote() · $99.99 EUR · card routing
EU €1.65 fee · 98.7% · 185ms BEST
UK €1.78 fee · 99.1% · 150ms
US €3.21 fee · 99.4% · 120ms
SG €3.90 fee · 98.2% · 220ms
selected route EU · router_eu_a1b2c3
Live response from POST /api/quote

The Hidden Cost of Payments

Every cross-border transaction burns money. Prime Flow fixes it — your payment, best path, every time.

Smart Routing

Weighted scoring on price, success rate, and latency picks the prime region for each payment — automatically.

Auto Fallback

Transaction failed? Prime Flow instantly retries through the next best region — up to 3 tries. Your user never sees an error.

Global Coverage

Access 23 regions immediately — US, EU, UK, Singapore, Japan and more — without spinning up new entities.

Fraud Detection

Built-in risk scoring (0–100) with allow / review / block actions on every intent before it routes.

Subscriptions & Batch

Full recurring-payment lifecycle plus parallel batch processing with concurrency control and retries.

PCI Compliant

Tokens only — Prime Flow never touches raw card data. Circuit breakers guard against cascading failures.

How It Works

  • 1. Get real-time quotes from all regions
  • 2. Weighted scoring selects the prime path
  • 3. Execute payment securely — with fallback

Ship in 5 Minutes

Type-safe SDK. Full TypeScript support. ESM + CJS.

Read Full Docs
import { PrimeFlow } from "prime-flow";

const client = new PrimeFlow({
  layer403: {
    apiKey: process.env.PRIMEFLOW_API_KEY,
    apiSecret: process.env.PRIMEFLOW_API_SECRET,
  },
  routing: {
    mode: "auto",
    weights: { price: 0.7, success: 0.25, latency: 0.05 },
    fallback: { enabled: true, maxTries: 3 }
  }
});

// Automatic routing optimization with fallback
const result = await client.pay({
  id: "order_123",
  amount: 99.99,
  currency: "EUR",
  paymentMethod: "card",
  cardToken: "tok_visa_4242",
  userCountry: "DE"
});

console.log(`Payment ${result.status} via ${result.regionUsed}`);
Live & Ready

REST API Reference

Complete REST API for integrating Prime Flow payment routing in any language. Built for developers who demand speed, reliability, and global coverage.

Quick Start

Base URL

https://api.primeflowprotocol.xyz

These endpoints are live on this server — test them in Try It Live below.

Authentication

All API requests require authentication via headers. Include these with every request:

X-PrimeFlow-Key: pf_live_xxxxx
X-PrimeFlow-Timestamp: 2024-01-15T12:00:00.000Z
X-PrimeFlow-Nonce: unique_random_string
X-PrimeFlow-Signature: hmac_sha256_signature

Test Credentials

// Sandbox API Key (no real charges)
API Key: pf_live_test123456789
Secret:  sk_test_secret

Response Format

{
  "success": true,
  "data": { ... },
  "requestId": "req_abc123",
  "timestamp": "2024-01-15T12:00:00Z"
}
GET /api/regions

Returns a list of all available payment regions with their supported currencies, payment methods, fee structures, and current health metrics.

Query Parameters

ParameterTypeDescription
activebooleanFilter by active status. Default: true

Response

{
  "success": true,
  "data": [
    {
      "code": "EU",
      "name": "European Union",
      "countries": ["DE", "FR", "ES", "IT", ...],
      "currencies": ["EUR"],
      "methods": ["card", "sepa", "apple_pay", "google_pay"],
      "active": true,
      "limits": {
        "min": 0.50,
        "max": 100000,
        "perTransaction": 50000
      },
      "baseFees": {
        "percentFee": 1.4,
        "fixedFee": 0.25,
        "fxFee": 0
      },
      "successRate": 0.987,
      "avgLatencyMs": 180
    }
  ],
  "requestId": "req_abc123",
  "timestamp": "2024-01-15T12:00:00.000Z"
}
GET /api/regions/:code

Returns detailed information for a specific region by its code (e.g., EU, US, UK).

POST /api/quote

Get optimized payment quotes across all regions. Returns fee breakdowns, success rates, and the recommended route for your payment intent.

Request Body

{
  "intent": {
    "amount": 99.99,
    "currency": "EUR",
    "paymentMethod": "card",
    "userCountry": "DE",         // optional
    "cardToken": "tok_visa_4242", // optional
    "customerEmail": "user@example.com"
  },
  "regions": ["EU", "US"],      // optional filter
  "includeUnavailable": false  // optional
}

Payment Intent Fields

FieldTypeRequiredDescription
amountnumberYesPayment amount in specified currency
currencystringYesISO 4217 currency code (EUR, USD, GBP...)
paymentMethodstringYesOne of: card, sepa, ach, pix, boleto, apple_pay, google_pay, bank_transfer, wallet
userCountrystringNoISO 3166-1 alpha-2 country code
cardTokenstringNoTokenized card from your PSP
customerEmailstringNoCustomer email for receipts
metadataobjectNoCustom key-value pairs

Response

{
  "success": true,
  "data": {
    "quotes": [
      {
        "region": "EU",
        "routerId": "router_eu_a1b2c3",
        "routerName": "European Union Gateway",
        "totalCost": 1.65,
        "feeBreakdown": {
          "percentFee": 1.4,
          "fixedFee": 0.25,
          "fxFee": 0,
          "crossBorderFee": 0
        },
        "successRate": 0.987,
        "latencyMs": 185,
        "score": 98.2,
        "available": true,
        "validForSec": 300
      }
    ],
    "recommended": { ... },
    "totalRegions": 5
  }
}
POST /api/pay

Execute a payment through the specified region. Supports idempotency keys for safe retries.

Required Headers

HeaderDescription
X-PrimeFlow-RegionTarget region code (e.g., EU, US)
X-Idempotency-KeyUnique key for request deduplication

Request Body

{
  "intent": {
    "amount": 99.99,
    "currency": "EUR",
    "paymentMethod": "card",
    "cardToken": "tok_visa_4242",
    "customerEmail": "customer@example.com",
    "description": "Order #12345",
    "returnUrl": "https://yoursite.com/success",
    "webhookUrl": "https://yoursite.com/webhooks/primeflow"
  },
  "region": "EU",
  "routerId": "router_eu_a1b2c3",
  "idempotencyKey": "order_12345_attempt_1"
}

Response

{
  "success": true,
  "data": {
    "intentId": "pi_abc123def456",
    "status": "succeeded",
    "regionUsed": "EU",
    "routerId": "router_eu_a1b2c3",
    "providerPaymentId": "ch_xyz789",
    "costApplied": 1.65,
    "amountCharged": 99.99,
    "currencyCharged": "EUR",
    "processedAt": "2024-01-15T12:00:00.000Z",
    "receiptUrl": "https://api.primeflowprotocol.xyz/receipts/pi_abc123",
    "authCode": "A1B2C3"
  }
}

Payment Status Values

StatusDescription
succeededPayment completed successfully
failedPayment was declined
pendingPayment is being processed asynchronously
requires_action3D Secure or redirect required
processingPayment is in progress
cancelledPayment was cancelled

3D Secure Handling

For payments over €100, the API may return requires_action with a nextAction object containing a redirect URL. Your customer must complete 3DS authentication before the payment can proceed.

POST /api/refund

Process a full or partial refund for a completed payment. Supports idempotency for safe retries.

Request Body

{
  "refundIntent": {
    "paymentIntentId": "pi_abc123def456",
    "providerPaymentId": "ch_xyz789",
    "amount": 50.00,  // optional, full refund if omitted
    "reason": "requested_by_customer",
    "metadata": {
      "refund_ticket": "TICKET-789"
    }
  },
  "region": "EU",
  "idempotencyKey": "refund_pi_abc123_1"
}

Refund Reason Codes

CodeDescription
requested_by_customerCustomer requested the refund
duplicateDuplicate charge
fraudulentFraudulent transaction
product_not_receivedProduct was not delivered
product_unacceptableProduct quality issues
otherOther reason

Response

{
  "success": true,
  "data": {
    "paymentIntentId": "pi_abc123def456",
    "refundId": "re_xyz789",
    "status": "succeeded",
    "amount": 50.00,
    "currency": "EUR",
    "regionUsed": "EU",
    "processedAt": "2024-01-15T14:00:00.000Z"
  }
}

Webhook Events

Prime Flow sends webhook events to notify your application about payment status changes. All webhooks are signed with HMAC-SHA256 for security.

Webhook Payload Structure

{
  "id": "evt_abc123",
  "type": "payment.succeeded",
  "created": "2024-01-15T12:00:00.000Z",
  "data": {
    "intentId": "pi_abc123def456",
    "providerPaymentId": "ch_xyz789",
    "amount": 99.99,
    "currency": "EUR",
    "region": "EU",
    "routerId": "router_eu_a1b2c3",
    "metadata": {}
  }
}

Event Types

EventDescription
payment.succeededPayment completed successfully
payment.failedPayment was declined or failed
payment.pendingPayment is processing asynchronously
payment.refundedPayment was refunded
refund.succeededRefund completed successfully
refund.failedRefund processing failed

Verifying Webhooks

const crypto = require('crypto');

function verifyWebhook(payload, signature, timestamp, secret) {
  const signedPayload = `${timestamp}.${payload}`;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

Error Codes

All errors follow a consistent format with machine-readable codes and human-readable messages.

Error Response Format

{
  "success": false,
  "error": {
    "code": "PAYMENT_DECLINED",
    "message": "The payment was declined by the processor",
    "details": {
      "decline_code": "insufficient_funds"
    }
  },
  "requestId": "req_abc123",
  "timestamp": "2024-01-15T12:00:00.000Z"
}

Payment Error Codes

CodeHTTPDescription
PAYMENT_DECLINED400Payment was declined by processor
INSUFFICIENT_FUNDS400Card has insufficient funds
CARD_EXPIRED400Card has expired
INVALID_CARD400Card number is invalid
FRAUD_DETECTED400Transaction flagged as fraudulent
AUTHENTICATION_REQUIRED4003DS authentication needed
AUTHENTICATION_FAILED4003DS authentication failed

Region Error Codes

CodeHTTPDescription
REGION_NOT_FOUND404Specified region does not exist
REGION_NOT_ALLOWED403Region is not available for your account
NO_AVAILABLE_REGIONS400No regions support this payment
REGION_LIMIT_EXCEEDED400Amount exceeds region limits
METHOD_NOT_SUPPORTED400Payment method not supported in region

System Error Codes

CodeHTTPDescription
AUTHENTICATION_ERROR401Invalid API credentials
RATE_LIMITED429Too many requests
TIMEOUT504Request timed out
SERVICE_UNAVAILABLE503Service temporarily unavailable
INTERNAL_ERROR500Internal server error

Code Examples

const { PrimeFlow } = require('prime-flow');

const client = new PrimeFlow({
  layer403: {
    apiKey: 'pf_live_test123456789',
    apiSecret: 'sk_test_secret',
    baseUrl: 'https://api.primeflowprotocol.xyz'
  }
});

// Get optimized quotes
const quotes = await client.quote({
  amount: 99.99,
  currency: 'EUR',
  paymentMethod: 'card',
  userCountry: 'DE'
});

// Execute payment with best route
const payment = await client.pay({
  id: 'order_123',
  amount: 99.99,
  currency: 'EUR',
  paymentMethod: 'card',
  cardToken: 'tok_visa_4242'
});

console.log(`Payment ${payment.status}: ${payment.intentId}`);
import requests

BASE_URL = "https://api.primeflowprotocol.xyz"
API_KEY = "pf_live_test123456789"

headers = {
    "Content-Type": "application/json",
    "X-PrimeFlow-Key": API_KEY
}

# Get optimized quotes
quote_resp = requests.post(
    f"{BASE_URL}/api/quote",
    headers=headers,
    json={
        "intent": {
            "amount": 99.99,
            "currency": "EUR",
            "paymentMethod": "card",
            "userCountry": "DE"
        }
    }
)
quotes = quote_resp.json()

# Execute payment
pay_resp = requests.post(
    f"{BASE_URL}/api/pay",
    headers={**headers, "X-PrimeFlow-Region": "EU"},
    json={
        "intent": {
            "amount": 99.99,
            "currency": "EUR",
            "paymentMethod": "card",
            "cardToken": "tok_visa_4242"
        },
        "region": quotes["data"]["recommended"]["region"]
    }
)
print(pay_resp.json())
# Get payment quotes
curl -X POST https://api.primeflowprotocol.xyz/api/quote \
  -H "Content-Type: application/json" \
  -H "X-PrimeFlow-Key: pf_live_test123456789" \
  -d '{
    "intent": {
      "amount": 99.99,
      "currency": "EUR",
      "paymentMethod": "card",
      "userCountry": "DE"
    }
  }'

# Execute payment
curl -X POST https://api.primeflowprotocol.xyz/api/pay \
  -H "Content-Type: application/json" \
  -H "X-PrimeFlow-Key: pf_live_test123456789" \
  -H "X-PrimeFlow-Region: EU" \
  -H "X-Idempotency-Key: order_12345" \
  -d '{
    "intent": {
      "amount": 99.99,
      "currency": "EUR",
      "paymentMethod": "card",
      "cardToken": "tok_visa_4242"
    },
    "region": "EU",
    "routerId": "router_eu_a1b2c3"
  }'

Rate Limits

1,000
requests/minute
Sandbox
10,000
requests/minute
Production
100,000
requests/minute
Enterprise

Try It Live

Test the API directly from your browser. Results are displayed in real-time.

Click "Send Request" to test...

Get in Touch

We are building Prime Flow for you. Feature requests and feedback are welcome.

FAQ

Common questions about Prime Flow

How does smart routing reduce fees?
Prime Flow scores every region on price, success rate, and latency, then routes through the prime local processor — avoiding cross-border interchange fees that typically add 1-2% to each transaction.
Is it PCI compliant?
Yes. Prime Flow never touches raw card data. You pass tokenized cards from your existing PSP, and we route the transaction securely.
What happens if a route fails?
Auto-fallback kicks in instantly — up to 3 tries through the next best region. Your customer never sees an error.
How long does integration take?
Most developers integrate in under 30 minutes. It's one NPM package — prime-flow — and about 10 lines of TypeScript.
What is $FLOW and the Solana angle?
$FLOW is Prime Flow's ecosystem token. The v1 SDK ships smart routing today; v2 adds direct USDC/SOL settlement on Solana via SPL with on-chain verification through an Anchor vault.
Do you support subscriptions?
Yes. The SDK includes a full subscription manager with automatic retries, dunning, and smart routing for recurring payments.