App Integration Guide
Connect your web application to Paddii Single Sign-On (SSO), token billing, and subscription passes on your dedicated appname.paddii.com subdomain.
Architecture Requirement: Any application that consumes user tokens or verifies subscriptions requires a backend to hold your App Secret Key (
PADDII_APP_SECRET_KEY) and authorize charges. Client-only static applications can use Paddii sign-in and free features.
1. Quickstart
Step 1: Register in the Developer Portal
In the Paddii Developer Portal:
- Set your Subdomain: Choose a unique slug (e.g.
sample-appyieldshttps://sample-app.paddii.com). - Set your Production Origin: Enter where your application is hosted (e.g.
https://my-app-origin.com). Paddii routes incoming requests on your subdomain to this origin. - Configure Pricing:
- Access Plans: Subscriptions or passes (e.g.
Pro Pass,2500centsUSD/ month). - Token Charges: Pay-as-you-go per feature (e.g.
process_document: 5 tokens). - Or leave both empty to list as a free app.
- Access Plans: Subscriptions or passes (e.g.
- Copy your App Secret Key: Store your
pad_sec_...key in your backend environment variables (PADDII_APP_SECRET_KEY). This key is only displayed once upon creation or rotation.
Step 2: Add the Frontend Client (services/paddiiClient.ts)
Add this client helper to your frontend application:
// services/paddiiClient.ts
export interface PriceAmount {
amount: number; // Smallest currency unit (e.g. cents)
currency: string; // ISO-4217 code (e.g. "USD")
}
export interface PaddiiSession {
authenticated: boolean;
user: {
id: string;
name: string;
tokens: number;
} | null;
userToken: string | null; // Scoped token passed to your backend
app: {
id: string;
name: string;
slug: string;
monthlyPrice?: PriceAmount | null;
featurePricing?: Record<string, number>;
};
subscription: {
hasActiveSubscription: boolean;
expiresAt: string | null;
};
}
export class PaddiiClient {
private baseUrl = "https://www.paddii.com";
private appId: string;
constructor(appId: string) {
this.appId = appId;
}
// 1. Fetch current session, user wallet tokens, and subscription status
async getSession(): Promise<PaddiiSession> {
try {
const res = await fetch(`${this.baseUrl}/api/apps/auth/session?appId=${this.appId}`, {
credentials: "include",
});
return await res.json();
} catch {
return {
authenticated: false,
user: null,
userToken: null,
app: { id: this.appId, name: this.appId, slug: this.appId },
subscription: { hasActiveSubscription: false, expiresAt: null },
};
}
}
// 2. Redirect to Paddii sign-in
login(returnPath: string = "/"): void {
if (typeof window !== "undefined") {
const returnUrl = window.location.origin + returnPath;
window.location.href = `${this.baseUrl}/login?appId=${this.appId}&callbackUrl=${encodeURIComponent(returnUrl)}`;
}
}
// 3. Open token top-up in the user's wallet
openTokenTopUp(plan?: string): void {
if (typeof window !== "undefined") {
const planParam = plan ? `&plan=${encodeURIComponent(plan)}` : "";
window.open(`${this.baseUrl}/dashboard/wallet?tab=tokens${planParam}`, "_blank");
}
}
// 4. Fetch dynamic pricing catalog configured on Paddii
async getPricingCatalog() {
try {
const res = await fetch(`${this.baseUrl}/api/apps/pricing?appId=${this.appId}`, {
credentials: "include",
});
return await res.json();
} catch {
return { success: false, featurePricing: {}, plans: [] };
}
}
}
export const paddii = new PaddiiClient("sample-app");Note: Sign-in callback URLs must match your registered application origin or subdomain. External redirect destinations are rejected.
Step 3: Trigger Features from the Frontend
import { paddii } from "@/services/paddiiClient";
async function onProcessDocument(documentId: string) {
const session = await paddii.getSession();
// 1. Require authentication
if (!session.authenticated || !session.userToken) {
paddii.login();
return;
}
// 2. Call your backend with the scoped user token
try {
const res = await fetch("/api/process-document", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-User-Token": session.userToken,
},
body: JSON.stringify({ documentId }),
});
const data = await res.json();
if (res.status === 401) {
// Session expired or invalid; prompt sign-in
paddii.login();
return;
}
if (res.status === 402 || data.insufficientTokens) {
// User needs more tokens
paddii.openTokenTopUp();
return;
}
if (!res.ok || !data.success) {
console.error("Processing failed:", data.error || res.statusText);
return;
}
// Success
console.log("Document processed successfully:", data.resultUrl);
} catch (error) {
console.error("Network error communicating with backend:", error);
}
}Step 4: Enforce Token Charges on Your Backend
Enforce token deduction on your backend using your PADDII_APP_SECRET_KEY:
// app/api/process-document/route.ts (Next.js / Node.js backend)
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const userToken = req.headers.get("x-user-token");
if (!userToken) {
return NextResponse.json({ error: "Missing user token" }, { status: 401 });
}
const { documentId } = await req.json();
// 1. Charge tokens server-to-server
const chargeRes = await fetch("https://www.paddii.com/api/apps/charges/create", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.PADDII_APP_SECRET_KEY}`,
"X-User-Token": userToken,
},
body: JSON.stringify({
feature: "process_document", // Feature key defined in Developer Portal
quantity: 1, // Number of units consumed
idempotencyKey: `doc_${documentId}`, // Prevents duplicate charges on retries
}),
});
const chargeData = await chargeRes.json();
if (!chargeRes.ok || !chargeData.success) {
return NextResponse.json(
{
error: chargeData.error || "Payment failed",
insufficientTokens: chargeRes.status === 402,
},
{ status: chargeRes.status }
);
}
// 2. Execute protected work
const resultUrl = await executeDocumentProcessing(documentId);
return NextResponse.json({
success: true,
resultUrl,
remainingTokens: chargeData.userBalance,
isSubscriber: chargeData.isSubscriber,
});
}Step 5: Two-Phase Reserve & Capture (Asynchronous Jobs)
For long-running tasks, reserve tokens before starting work so users are not charged if execution fails:
// 1. Reserve tokens
const reserveRes = await fetch("https://www.paddii.com/api/apps/charges/reserve", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.PADDII_APP_SECRET_KEY}`,
"X-User-Token": userToken,
},
body: JSON.stringify({
feature: "process_document",
quantity: 1,
ttlSeconds: 600, // Reservation expires in 10 minutes
idempotencyKey: jobId,
}),
});
const reserveData = await reserveRes.json();
if (!reserveRes.ok || !reserveData.success) {
// If reservation fails (insufficient tokens or invalid token), stop immediately
return { success: false, error: reserveData.error || "Failed to reserve tokens" };
}
const { reservationId } = reserveData;
// 2. Execute the work in a try-catch block
let output;
try {
output = await runLongJob(jobId);
} catch (workError) {
// Release reserved tokens if the work failed or threw an error
await fetch("https://www.paddii.com/api/apps/charges/release", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.PADDII_APP_SECRET_KEY}`,
},
body: JSON.stringify({ reservationId, reason: "work_failed" }),
});
throw workError;
}
// 3. Capture runs after work completes; if capture fails, retry with the same reservationId, then log for review
const captureRes = await fetch("https://www.paddii.com/api/apps/charges/capture", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.PADDII_APP_SECRET_KEY}`,
},
body: JSON.stringify({ reservationId }),
});
const captureData = await captureRes.json();
if (!captureRes.ok || !captureData.success) {
console.error("Capture failed for completed work; retry or log for review:", reservationId, captureData.error);
}
return { success: true, output };2. Key Management & Rotation
If you need to rotate your PADDII_APP_SECRET_KEY:
- In the Developer Portal, select Rotate Secret Key from your app's menu.
- A new secret key is generated.
- Your previous key remains active for a 24-hour grace period so existing deployments continue running while you update backend environment variables. You can also select Revoke now to invalidate the old key immediately.
3. API Reference
All backend requests require Authorization: Bearer <PADDII_APP_SECRET_KEY>.
Check User Session
GET https://www.paddii.com/api/apps/auth/session?appId=<appSlug>
Called from the client browser to inspect authentication status, token balance, and active subscriptions.
Headers:
credentials: "include"
Response (HTTP 200):
{
"authenticated": true,
"user": {
"id": "usr_sample_12345",
"name": "Jane Doe",
"tokens": 50
},
"userToken": "pad_usr_sample_token_98765",
"app": {
"id": "sample-app",
"name": "Sample App",
"slug": "sample-app"
},
"subscription": {
"hasActiveSubscription": false,
"expiresAt": null
}
}Direct Charge
POST https://www.paddii.com/api/apps/charges/create
Called from your backend to deduct tokens immediately.
Headers:
Authorization: Bearer <PADDII_APP_SECRET_KEY>X-User-Token: <userToken>Content-Type: application/json
Request Body:
{
"feature": "process_document",
"quantity": 1,
"idempotencyKey": "req_unique_id_12345"
}Response (HTTP 200):
{
"success": true,
"chargeId": "chg_sample_78901",
"tokensCharged": 5,
"isSubscriber": false,
"userBalance": 45
}Reserve Tokens
POST https://www.paddii.com/api/apps/charges/reserve
Called from your backend before beginning long-running operations.
Headers:
Authorization: Bearer <PADDII_APP_SECRET_KEY>X-User-Token: <userToken>Content-Type: application/json
Request Body:
{
"feature": "process_document",
"quantity": 1,
"ttlSeconds": 600,
"idempotencyKey": "req_unique_id_67890"
}Response (HTTP 200):
{
"success": true,
"reservationId": "res_sample_45678",
"tokensReserved": 5,
"expiresAt": "2026-11-08T18:00:00Z"
}Capture Reserved Tokens
POST https://www.paddii.com/api/apps/charges/capture
Called from your backend after work successfully finishes.
Headers:
Authorization: Bearer <PADDII_APP_SECRET_KEY>Content-Type: application/json
Request Body:
{
"reservationId": "res_sample_45678"
}Response (HTTP 200):
{
"success": true,
"status": "captured",
"chargeId": "chg_sample_78902"
}Release Reserved Tokens
POST https://www.paddii.com/api/apps/charges/release
Called from your backend if execution fails or is cancelled.
Headers:
Authorization: Bearer <PADDII_APP_SECRET_KEY>Content-Type: application/json
Request Body:
{
"reservationId": "res_sample_45678",
"reason": "work_failed"
}Response (HTTP 200):
{
"success": true,
"status": "released",
"tokensRestored": 5
}Initialize Subscription
POST https://www.paddii.com/api/apps/subscriptions/initialize
Initiates a subscription pass for the authenticated user. Called from the client browser using session cookies, or from your backend using X-User-Token.
Headers:
Content-Type: application/jsoncredentials: "include"(when called from browser) orX-User-Token: <userToken>(when called from backend)
Request Body:
{
"appId": "sample-app",
"paymentMethod": "wallet",
"returnUrl": "https://sample-app.paddii.com"
}Response (HTTP 200):
{
"success": true,
"subscriptionId": "sub_4410ab",
"status": "active",
"expiresAt": "2026-12-08T18:00:00Z"
}Fetch Live Pricing Catalog
GET https://www.paddii.com/api/apps/pricing?appId=<appSlug>
Retrieves configured feature token rates and access plans.
Response (HTTP 200):
{
"success": true,
"app": {
"id": "sample-app",
"name": "Sample App",
"slug": "sample-app",
"featurePricing": {
"process_document": 5,
"generate_report": 10
},
"plans": [
{
"id": "plan_pro",
"name": "Pro Pass",
"amount": 2500,
"currency": "USD",
"interval": "monthly"
}
]
}
}4. Platform Fees & Payouts
- Platform Fee: Paddii deducts a platform fee from paid transactions. The current fee rate and your net earnings are displayed on your Developer Dashboard under the Earnings & Usage tab.
- Payouts: Net earnings are automatically transferred to your saved bank account configured in your dashboard settings.
Single-Page Apps (SPAs): If your frontend uses client-side routing, configure rewrite rules on your hosting provider so non-API routes resolve to
index.html.
