SDK Examples

Beta

Complete examples for integrating Orvion payment protection into your applications using the Python and Node.js SDKs.


Quick Reference

| Operation | Python | Node.js | |-----------|--------|---------| | Create charge | client.create_charge() | client.createCharge() | | Verify payment | client.verify_charge() | client.verifyCharge() | | Confirm wallet payment | client.confirm_payment() | client.confirmPayment() | | Cancel charge | client.cancel_charge() | client.cancelCharge() | | Get charge state | client.get_charge_state() | client.getChargeState() | | Health check | client.health_check() | client.healthCheck() |


Installation

Node.js

npm install @orvion/sdk

Python

pip install orvion

Minimal Example (Pre-built Router)

The easiest way to integrate Orvion - use the pre-built payment router!

Node.js

Node.js
import express from 'express'
import { OrvionClient } from '@orvion/sdk'
import { orvionInit, requirePayment, createPaymentRouter } from '@orvion/sdk/express'
const app = express()
app.use(express.json())
const client = new OrvionClient({ apiKey: process.env.ORVION_API_KEY! })
orvionInit({ apiKey: process.env.ORVION_API_KEY! })
// Add all payment endpoints with one line!
app.use('/api/payments', createPaymentRouter(client))
// Protected endpoint
app.get('/api/premium',
requirePayment({ amount: '0.01', currency: 'USDC' }),
(req, res) => {
res.json({ message: 'Premium content!', paid: req.payment.amount })
}
)
app.listen(3000)

Python

Python
from fastapi import FastAPI, Request
from orvion import OrvionClient
from orvion.fastapi import OrvionMiddleware, require_payment, create_payment_router
import os
app = FastAPI()
client = OrvionClient(api_key=os.environ["ORVION_API_KEY"])
app.add_middleware(OrvionMiddleware, api_key=os.environ["ORVION_API_KEY"])
# Add all payment endpoints with one line!
app.include_router(create_payment_router(client), prefix="/api/payments")
# Protected endpoint
@app.get("/api/premium")
@require_payment(amount="0.01", currency="USDC")
async def premium(request: Request):
return {"message": "Premium content!", "paid": request.state.payment.amount}

Health Check & API Validation

Verify your API key and get organization info on startup.

Node.js

Node.js
import { OrvionClient } from '@orvion/sdk'
const client = new OrvionClient({ apiKey: process.env.ORVION_API_KEY! })
async function validateConfig() {
const health = await client.healthCheck()
if (health.apiKeyValid) {
console.log('✓ API Key valid')
console.log(` Organization: ${health.organizationId}`)
console.log(` Environment: ${health.environment}`)
} else {
console.error('✗ Invalid API key!')
process.exit(1)
}
}
validateConfig()

Python

Python
from orvion import OrvionClient
import os
async def validate_config():
client = OrvionClient(api_key=os.environ["ORVION_API_KEY"])
health = await client.health_check()
if health.api_key_valid:
print("✓ API Key valid")
print(f" Organization: {health.organization_id}")
print(f" Environment: {health.environment}")
else:
print("✗ Invalid API key!")
exit(1)
await client.close()

Payment Confirmation (Wallet Payments)

Confirm a payment after the user completes a wallet transaction.

Node.js

Node.js
import { OrvionClient } from '@orvion/sdk'
const client = new OrvionClient({ apiKey: process.env.ORVION_API_KEY! })
async function confirmWalletPayment(chargeId: string, txHash: string) {
const result = await client.confirmPayment({
transactionId: chargeId,
txHash: txHash,
})
if (result.success) {
console.log('Payment confirmed!')
console.log(` Amount: ${result.amount} ${result.currency}`)
console.log(` TX Hash: ${result.txHash}`)
return { success: true, payment: result }
} else {
console.log('Confirmation failed:', result.error)
return { success: false, error: result.error }
}
}
// Usage
confirmWalletPayment('charge_123', '5abc...xyz')

Python

Python
from orvion import OrvionClient
import os
async def confirm_wallet_payment(charge_id: str, tx_hash: str):
async with OrvionClient(api_key=os.environ["ORVION_API_KEY"]) as client:
result = await client.confirm_payment(
transaction_id=charge_id,
tx_hash=tx_hash,
)
if result.success:
print("Payment confirmed!")
print(f" Amount: {result.amount} {result.currency}")
print(f" TX Hash: {result.tx_hash}")
return {"success": True, "payment": result}
else:
print(f"Confirmation failed: {result.error}")
return {"success": False, "error": result.error}
# Usage
import asyncio
asyncio.run(confirm_wallet_payment("charge_123", "5abc...xyz"))

Get Charge State (For Payment UI)

Get optimized charge state for rendering payment widgets.

Node.js

Node.js
import { OrvionClient } from '@orvion/sdk'
const client = new OrvionClient({ apiKey: process.env.ORVION_API_KEY! })
async function getPaymentUI(chargeId: string) {
const state = await client.getChargeState(chargeId)
return {
status: state.status,
amount: state.displayAmount || state.amount,
currency: state.currency,
// For wallet payments
recipientAddress: state.recipientAddress,
tokenAddress: state.tokenAddress,
network: state.network,
// Status checks
isPending: state.status === 'pending',
isSucceeded: state.status === 'succeeded',
isFailed: state.status === 'failed',
}
}
// Usage in Express route
app.get('/api/payment-status/:id', async (req, res) => {
const ui = await getPaymentUI(req.params.id)
res.json(ui)
})

Python

Python
from orvion import OrvionClient
import os
async def get_payment_ui(charge_id: str):
async with OrvionClient(api_key=os.environ["ORVION_API_KEY"]) as client:
state = await client.get_charge_state(charge_id)
return {
"status": state.status,
"amount": state.display_amount or state.amount,
"currency": state.currency,
# For wallet payments
"recipient_address": state.recipient_address,
"token_address": state.token_address,
"network": state.network,
# Status checks
"is_pending": state.status == "pending",
"is_succeeded": state.status == "succeeded",
"is_failed": state.status == "failed",
}
# Usage in FastAPI route
@app.get("/api/payment-status/{charge_id}")
async def payment_status(charge_id: str):
return await get_payment_ui(charge_id)

Cancel Pending Charge

Cancel a charge when user abandons payment.

Node.js

Node.js
import { OrvionClient } from '@orvion/sdk'
const client = new OrvionClient({ apiKey: process.env.ORVION_API_KEY! })
async function cancelPayment(chargeId: string) {
const cancelled = await client.cancelCharge(chargeId)
if (cancelled) {
console.log(`Charge ${chargeId} cancelled`)
} else {
console.log('Could not cancel charge (may already be completed)')
}
return cancelled
}
// Usage - e.g., when user closes payment modal
app.post('/api/payments/abandon/:id', async (req, res) => {
const cancelled = await cancelPayment(req.params.id)
res.json({ cancelled })
})

Python

Python
from orvion import OrvionClient
import os
async def cancel_payment(charge_id: str) -> bool:
async with OrvionClient(api_key=os.environ["ORVION_API_KEY"]) as client:
cancelled = await client.cancel_charge(charge_id)
if cancelled:
print(f"Charge {charge_id} cancelled")
else:
print("Could not cancel charge (may already be completed)")
return cancelled
# Usage - e.g., when user closes payment modal
@app.post("/api/payments/abandon/{charge_id}")
async def abandon_payment(charge_id: str):
cancelled = await cancel_payment(charge_id)
return {"cancelled": cancelled}

Payment Verification

Verify a payment before granting access.

Node.js

Node.js
import { OrvionClient } from '@orvion/sdk'
const client = new OrvionClient({ apiKey: process.env.ORVION_API_KEY! })
async function verifyAccess(transactionId: string, resourceId: string) {
try {
const result = await client.verifyCharge({
transactionId,
resourceRef: resourceId,
})
if (result.verified) {
console.log('Payment verified!')
return { access: true, payment: result }
} else {
console.log('Verification failed:', result.reason)
return { access: false, reason: result.reason }
}
} catch (error: any) {
if (error.statusCode === 404) {
return { access: false, reason: 'Transaction not found' }
}
throw error
}
}
// Usage in Express middleware
function requireVerifiedPayment(resourceId: string) {
return async (req: any, res: any, next: any) => {
const txId = req.headers['x-transaction-id']
if (!txId) {
return res.status(402).json({ error: 'Payment required' })
}
const result = await verifyAccess(txId, resourceId)
if (result.access) {
req.payment = result.payment
return next()
}
return res.status(402).json({ error: result.reason })
}
}

Python

Python
from orvion import OrvionClient, OrvionAPIError
import os
async def verify_access(transaction_id: str, resource_id: str):
async with OrvionClient(api_key=os.environ["ORVION_API_KEY"]) as client:
try:
result = await client.verify_charge(
transaction_id=transaction_id,
resource_ref=resource_id,
)
if result.verified:
print("Payment verified!")
return {"access": True, "payment": result}
else:
print(f"Verification failed: {result.reason}")
return {"access": False, "reason": result.reason}
except OrvionAPIError as e:
if e.status_code == 404:
return {"access": False, "reason": "Transaction not found"}
raise

Error Handling

Node.js

Node.js
import { OrvionClient, OrvionAPIError, OrvionAuthError, OrvionTimeoutError } from '@orvion/sdk'
async function safeOperation() {
const client = new OrvionClient({ apiKey: process.env.ORVION_API_KEY! })
try {
const charge = await client.createCharge({
amount: '0.10',
currency: 'USDC',
})
return { success: true, charge }
} catch (error) {
if (error instanceof OrvionAuthError) {
console.error('Authentication failed - check your API key')
} else if (error instanceof OrvionTimeoutError) {
console.error('Request timed out - try again')
} else if (error instanceof OrvionAPIError) {
console.error(`API Error ${error.statusCode}: ${error.message}`)
} else {
console.error('Unexpected error:', error)
}
return { success: false, error }
}
}

Python

Python
from orvion import (
OrvionClient,
OrvionAPIError,
OrvionAuthError,
OrvionTimeoutError,
)
import os
async def safe_operation():
client = OrvionClient(api_key=os.environ["ORVION_API_KEY"])
try:
charge = await client.create_charge(
amount="0.10",
currency="USDC",
)
return {"success": True, "charge": charge}
except OrvionAuthError:
print("Authentication failed - check your API key")
except OrvionTimeoutError:
print("Request timed out - try again")
except OrvionAPIError as e:
print(f"API Error {e.status_code}: {e.message}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
await client.close()
return {"success": False}

Best Practices

  1. Store API keys securely - Use environment variables, never commit keys to version control
  2. Use pre-built routers - Save time with create_payment_router() / createPaymentRouter()
  3. Validate on startup - Use health_check() / healthCheck() to catch config issues early
  4. Handle cancellations - Cancel charges when users abandon payment to keep data clean
  5. Use charge state for UI - get_charge_state() returns optimized data for payment widgets
  6. Implement proper error handling - Catch and handle specific error types

Related Documentation