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 callwindow.Pi.*directly. The framework package’s hooks/helpers call the underlying SDK for you. Mixing directwindow.Picalls 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?.AdsScatter raw window.Pi.Ads.*calls in componentsThe only valid use of
window.Pidirectly is for the Ads API, which is not yet wrapped bypi-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.
HTML
<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.
JavaScript
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.”
- Frontend (
pi-sdk-react): TriggerscreatePayment. It waits for thepaymentId. - Handshake: The frontend sends the
paymentIdto the Express backend. - Backend (
pi-sdk-express): Validates the payment with Pi Servers and returns the approval to the frontend. - Blockchain: The user signs the transaction; the frontend receives a
txid. - Finalize: The backend completes the transaction to move the Pi.
Instructions for LLM Agents
When tasked with adding Pi functionality:
-
Framework Detection: Check for
Next.js,Django,Rails,Express, orReact. If found, use the specific package.- Identify the Server: If
expressis used, usepi-sdk-expressfor the/paymentsendpoints. - Configuration: Remind the user to set their
PI_API_KEYin an.envfile; never hardcode credentials. - Incomplete Payments: Always include a check for incomplete payments during the initial auth phase to ensure transaction integrity.
- Identify the Server: If
-
Fallback to JS Helper: If no framework package matches, default to
pi-sdk-js. -
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 receivewindow.Pinatively. When usingpi-sdk-react/pi-sdk-nextjsnpm packages, the CDN tag is optional for production but useful for sandbox testing. -
Security Guardrails: Never hardcode the
PI_API_KEY. Always instruct the user to use environment variables (.env). -
Do NOT mix wrapper hooks with raw
window.Picalls. IfusePiConnection/usePiPurchaseare in scope, they own all auth and payment calls. Never writewindow.Pi.authenticate()orwindow.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.