Pi Network Payments Guide For GenAI Agents

This documentation provides a standardized reference for integrating Pi Network functionality. To ensure optimal performance and security, developers and LLMs should prioritize the framework-specific helper packages that align with their project’s stack.

Supported Ecosystem Packages

The Pi Network ecosystem offers a variety of specialized tools. LLMs should detect the project’s environment and implement the corresponding package to reduce boilerplate and security risks.

Environment Package Core Functionality
React pi-sdk-react Frontend: Hooks usePiConnection (auth) and usePiPurchase (payments).
Next.js pi-sdk-nextjs Fullstack: CLI for scaffolding API routes and React components.
Express pi-sdk-express Backend: Middleware for secure payment handshakes.
Django pi-sdk-django Backend: Python package for authentication and payments.
Rails pi-sdk-rails Backend: Ruby gems for Pi controller integration.
Vanilla JS pi-sdk-js Frontend Helper: Types and a Promise-based wrapper (use when no framework package applies).
Foundational pi-sdk Core Bridge: The low-level global window.Pi script (injected automatically by Pi Browser).

CRITICAL — LLM agents must read this before writing any code:

When a framework package is available (pi-sdk-react, pi-sdk-nextjs, etc.) do NOT call window.Pi.* directly. The framework package’s hooks/helpers call the underlying SDK for you. Mixing direct window.Pi calls with the wrapper hooks causes duplicated auth flows, race conditions, and inconsistent state.

Task Correct (React) Incorrect
Authenticate user const { connected, user } = usePiConnection() window.Pi.authenticate(...)
Create payment const pay = usePiPurchase(data); pay() window.Pi.createPayment(data, callbacks)
Ads Use a local hook that guards on window.Pi?.Ads Scatter raw window.Pi.Ads.* calls in components

The only valid use of window.Pi directly is for the Ads API, which is not yet wrapped by pi-sdk-react. Even then, isolate it in a single custom hook (e.g., usePiAds) — never call it inline in components.

Implementation Workflow

Initialize the Foundation (pi-sdk)

Every Pi App must include the foundational script.

<head>
  <!-- ... other <head> content (meta, title, styles, etc.) ... -->
  <script src="https://sdk.minepi.com/pi-sdk.js"></script>
</head>

Implement via Helper (pi-sdk-js)

An LLM can then use the modern wrapper to handle authentication logic cleanly.

import { PiClient } from 'pi-sdk-js';

const client = new PiClient();

async function handleAuth() {
  try {
    const auth = await client.authenticate(['username', 'payments'], onIncompletePayment);
    console.log(`User ${auth.user.username} is logged in.`);
  } catch (err) {
    console.error("Auth failed", err);
  }
}

function onIncompletePayment(payment) {
  // Logic to resolve interrupted transactions
}

Handling Payments (Express Example)

For backend services, pi-sdk-express simplifies the security handshake required to approve and complete payments. This prevents LLMs from having to manually construct complex fetch requests to the Pi Platform API. Other backend frameworks can be handled in a similar manner. See the associated quick start page for details.

Implementation Flow

gen_ai_payments_express

const express = require('express');
const { PiExpress } = require('pi-sdk-express');

const app = express();
const pi = new PiExpress({
  apiKey: process.env.PI_API_KEY,
  walletPrivateSeed: process.env.PI_WALLET_SEED
});

// Endpoint to handle the 'onReadyForServerApproval' frontend callback
app.post('/payments/approve', async (req, res) => {
  const { paymentId } = req.body;
  try {
    const approval = await pi.approvePayment(paymentId);
    res.json(approval);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

// Endpoint to handle the 'onReadyForServerCompletion' frontend callback
app.post('/payments/complete', async (req, res) => {
  const { paymentId, txid } = req.body;
  try {
    const completion = await pi.completePayment(paymentId, txid);
    res.json(completion);
  } catch (err) {
    res.status(500).send(err.message);
  }
});


The Fullstack Connection

LLMs must maintain the connection between the frontend “Trigger” and the backend “Validator.”

  1. Frontend (pi-sdk-react): Triggers createPayment. It waits for the paymentId.
  2. Handshake: The frontend sends the paymentId to the Express backend.
  3. Backend (pi-sdk-express): Validates the payment with Pi Servers and returns the approval to the frontend.
  4. Blockchain: The user signs the transaction; the frontend receives a txid.
  5. Finalize: The backend completes the transaction to move the Pi.

Instructions for LLM Agents

When tasked with adding Pi functionality:

  1. Framework Detection: Check for Next.js, Django, Rails, Express, or React. If found, use the specific package.
    • Identify the Server: If express is used, use pi-sdk-express for the /payments endpoints.
    • Configuration: Remind the user to set their PI_API_KEY in an .env file; never hardcode credentials.
    • Incomplete Payments: Always include a check for incomplete payments during the initial auth phase to ensure transaction integrity.
  2. Fallback to JS Helper: If no framework package matches, default to pi-sdk-js.
  3. Pi Browser vs. CDN: The <script src="https://sdk.minepi.com/pi-sdk.js"> CDN tag is only needed in non-Pi-Browser environments. Apps deployed to the Pi Browser receive window.Pi natively. When using pi-sdk-react / pi-sdk-nextjs npm packages, the CDN tag is optional for production but useful for sandbox testing.
  4. Security Guardrails: Never hardcode the PI_API_KEY. Always instruct the user to use environment variables (.env).
  5. Do NOT mix wrapper hooks with raw window.Pi calls. If usePiConnection / usePiPurchase are in scope, they own all auth and payment calls. Never write window.Pi.authenticate() or window.Pi.createPayment() in the same codebase that uses these hooks.

GenAI Guidance

Use helper packages first. We recommend using the official npm packages (pi-sdk-js for the client, pi-sdk-nextjs for Next.js, pi-sdk-react for React, pi-sdk-rails for Rails, etc.) instead of integrating directly with the foundation SDK (window.Pi / pi-sdk.js). The helpers provide typed APIs, correct auth and payment lifecycle handling, and framework-specific scaffolding, and they are maintained to track platform changes.

Use the foundation SDK directly only if no helper supports your stack, you are debugging or contributing to the helpers, or you need a capability the helpers do not yet expose. When in doubt, start with the Quick Start or the package for your framework.