-
Notifications
You must be signed in to change notification settings - Fork 1
SDK Reference
Build powerful Pi Network apps with authentication, payments, and native device features
🎯 New to Pi SDK? Get up and running in minutes
The Pi Network SDK enables seamless integration with Pi Network features in your web applications. Perfect for:
- 🔐 User Authentication - Secure Pi Network login
- 💰 Payment Processing - Pi cryptocurrency transactions
- 📱 Native Features - Device-specific functionality
- 🤝 Social Features - Conversations and sharing
Add the SDK script to your HTML document:
<script src="https://sdk.minepi.com/pi-sdk.js"></script>Download and host the SDK file on your server:
<script src="/path/to/pi-sdk.js"></script>
⚠️ Important: Always use the official CDN or verify integrity of self-hosted files
Initialize the Pi SDK in your application:
// Initialize Pi SDK
Pi.init({
version: "2.0",
sandbox: false // Set to true for development/testing
});For modern hybrid applications that work in both Web2 and Web3 environments:
// Modern hybrid initialization
async function initializePiApp() {
// 1. Initialize SDK
Pi.init({ version: "2.0", sandbox: false });
// 2. Detect Pi Browser (see Pi Browser Detection guide)
const isPiBrowser = await detectPiBrowser();
if (!isPiBrowser) {
// Show fallback UI for regular browsers
showWebFallback();
return;
}
// 3. Enable Pi features for Pi Browser users
enablePiFeatures();
}💡 Pro Tip: Check out our Pi Browser Detection Guide for complete hybrid app implementation
🔬 Perfect your app before going live
Use sandbox mode to test your Pi Network integration without real transactions or user impact.
Pi.init({
version: "2.0",
sandbox: true // ✅ Enable for development
});- Open Pi Mining App on your mobile device
- Navigate to Pi Utilities section
- Select "Authorize Sandbox"
- Follow the authorization instructions
- Copy your sandbox URL from Developer Portal
| 🎯 Feature | 📝 Description | ✅ Benefits |
|---|---|---|
| Safe Testing | Simulate all Pi features | No real Pi transactions, no user impact |
| User Authentication | Test login flows | Real Pi accounts, isolated app scope |
| Payment Flows | End-to-end payment testing | Same API, simulated blockchain |
Authentication
-
Pi.authenticate(scopes, callback): Authenticates the user and returns a promise that resolves to an object containing the user's data and an access token.-
Parameters:
-
scopes: An array of scopes to request. -
callback: A callback function that is called with the error and result of the authentication.
-
- Returns: A promise that resolves to an object containing the user's data and an access token also known as an AuthResult Object.
{"user":{"uid":"userid","credentials":{"scopes":["payments","platform"],"valid_until":{"timestamp":1709007140,"iso8601":"2024-02-27T04:12:20Z"}}},"accessToken":"accessToken"}-
⚠️ Hybrid App Best Practice: Always check if the user is in Pi Browser before calling authenticate to avoid scary popups in regular browsers:
// ✅ Good: Check Pi Browser first const isPiBrowser = await detectPiBrowser(); // See Pi Browser Detection guide if (!isPiBrowser) { // Show fallback UI instead showPiBrowserPrompt(); return; } // Only authenticate when in Pi Browser and user initiates const auth = await Pi.authenticate(['payments'], onIncompletePaymentFound); // ❌ Bad: Don't call on page load // This creates scary popups in regular browsers Pi.authenticate(['payments'], onIncompletePaymentFound);
- See Also: Pi Browser Detection Guide for complete hybrid app implementation
-
Parameters:
-
Pi.Error.auth(errorMessage): Reports an authentication error to the Pi Network platform.-
Parameters:
-
errorMessage: The error message to report.
-
-
Parameters:
-
Pi.Error.unknown(errorMessage): Reports an unknown error to the Pi Network platform.-
Parameters:
-
errorMessage: The error message to report.
-
-
Parameters:
App Presence
-
Pi.checkUserHasMiningApp(): Checks if the user has the Pi Mining App installed.- Parameters: None
- Returns: A promise that resolves to a boolean indicating whether the user has the Pi Mining App installed.
{"userHasMiningApp":true} -
Pi.checkUserHasPiBrowser(): Checks if the user has the Pi Browser installed.- Parameters: None
- Returns: A promise that resolves to a boolean indicating whether the user has the Pi Browser installed.
{"userHasPiBrowser":true}
Clipboard
-
Pi.copyText(text): Copies the specified text to the clipboard.-
Parameters:
-
text: The text to copy.
-
-
Parameters:
-
callback: A callback function that is called when the text has been copied.
Payments
-
Pi.createPayment(paymentData): Prepares a payment flow.-
Parameters:
-
paymentData: The payment data. -
callbacks: The payment data.- Callbacks you need to implement:
onReadyForServerApproval: function(paymentId) { /* ... */ }onReadyForServerCompletion: function(paymentId, txid) { /* ... */ }onCancel: function(paymentId) { /* ... */ }onError: function(error, payment) { /* ... */ }
-
- Returns: A promise that resolves to a PaymentDTO Object.
-
Parameters:
-
Pi.Payments.preparePaymentFlow(paymentData): Prepares a payment flow.-
Parameters:
-
paymentData: The payment data.
-
- Returns: A promise that resolves to the payment ID.
-
Parameters:
-
Pi.Payments.startPaymentFlow(paymentId): Starts a payment flow.-
Parameters:
-
paymentId: The payment ID.
-
- Returns: A promise that resolves when the payment flow has been started.
-
Parameters:
-
Pi.Payments.waitForTransaction(paymentId): Waits for a transaction to complete.-
Parameters:
-
paymentId: The payment ID.
-
- Returns: A promise that resolves to the transaction details.
-
Parameters:
-
Pi.Payments.showPrePaymentError(errorMessage): Shows a pre-payment error.-
Parameters:
-
errorMessage: The error message to show.
-
-
Parameters:
App Info
-
Pi.getPiHostAppName(): Gets the name of the Pi host app.- Parameters: None
- Returns: The name of the Pi host app.
-
Pi.getPiHostAppInfo(): Gets information about the Pi host app.- Parameters: None
- Returns: A promise that resolves to an object containing the information about the Pi host app.
{"hostApp":"pi-browser","appVersion":"1.8.0","os":"android","osVersion":"33","webviewVersion":"121.0"}
Pi Browser Detection
-
Pi.getPiHostAppInfo(): The primary method for detecting Pi Browser in hybrid applications.-
Use Case: Check if
result.hostApp === "pi-browser"to determine if the user is in Pi Browser - Best Practice: Use with Promise.race() and timeout for reliable detection
- Example:
const timeout = new Promise(resolve => setTimeout(() => resolve("timeout"), 3000)); try { const result = await Promise.race([window.Pi.getPiHostAppInfo(), timeout]); const isPiBrowser = result?.hostApp === "pi-browser"; } catch (e) { // Fallback to User-Agent detection const isPiBrowser = navigator.userAgent.toLowerCase().includes("pibrowser"); }
- Hybrid App Pattern: Essential for building apps that work in both Web2 and Web3 environments
- See Also: Pi Browser Detection Guide for complete implementation examples
-
Use Case: Check if
Initialization
-
Pi.init(options): Initializes the SDK.-
Parameters:
-
options: The initialization options.
-
- Returns: A promise that resolves when the SDK has been initialized.
-
Parameters:
Features
-
Pi.nativeFeaturesList(): Gets a list of the native features that are supported by the SDK.- Parameters: None
- Returns: A promise that resolves to a list of the native features that are supported by the SDK.
inline_media,request_permission,ad_network
User Actions
-
Pi.openConversation(conversationId): Opens a conversation with the specified conversation ID.-
Parameters:
-
conversationId: The conversation ID.
-
- Returns: A promise that resolves when the conversation has been opened.
-
Parameters:
-
Pi.openShareDialog(title, sharingMessage): Opens a share dialog with the specified title and sharing message.-
Parameters:
-
title: The title of the share dialog. -
sharingMessage: The sharing message.
-
- Returns: A promise that resolves when the share dialog has been opened.
-
Parameters:
-
Pi.openUrlInSystemBrowser(url): Opens the specified URL in the system browser.-
Parameters:
-
url: The URL to open.
-
- Returns: A promise that resolves when the URL has been opened.
-
Parameters:
-
Pi.requestPermission(permission): Requests the specified permission.-
Parameters:
-
permission: The permission to request.
-
- Returns: A promise that resolves to a boolean indicating whether the permission was granted.
-
Parameters:
-
Pi.scanQrCode(config): Scans a QR code.-
Parameters:
-
config: The configuration object.
-
- Returns: A promise that resolves to the scanned data.
-
Parameters:
SDK
-
Pi.SDK.communicationInformationRequest(): Requests communication information from the host app.- Parameters: None
- Returns: A promise that resolves to an object containing the communication information.
-
Pi.SDK.setThirdPartyAppUserId(userId): Sets the third-party app user ID.-
Parameters:
-
userId: The third-party app user ID.
-
-
Parameters:
-
Pi.SDK.decideCallbackRetrial(callbackId, shouldRetry): Decides whether to retry a callback.-
Parameters:
-
callbackId: The callback ID. -
shouldRetry: Whether to retry the callback.
-
-
Parameters:
-
Pi.SDK.openConsentModal(): Opens the consent modal.- Parameters: None
-
Pi.SDK.requestHostAppInfo(): Requests information about the host app.- Parameters: None
- Returns: A promise that resolves to an object containing the information about the host app.
-
Pi.SDK.checkNativeFeatures(): Checks for native features.- Parameters: None
- Returns: A promise that resolves to a list of the native features that are supported by the SDK.
-
Pi.SDK.requestNativePermission(permission): Requests a native permission.-
Parameters:
-
permission: The permission to request.
-
- Returns: A promise that resolves to a boolean indicating whether the permission was granted.
-
Parameters:
-
Pi.SDK.isAdReady(type): Checks if an ad is ready to be shown.-
Parameters:
-
type: The type of ad.
-
- Returns: A promise that resolves to a boolean indicating whether the ad is ready to be shown.
-
Parameters:
-
Pi.SDK.requestAd(type): Requests an ad.-
Parameters:
-
type: The type of ad.
-
- Returns: A promise that resolves to an ad object.
-
Parameters:
-
Pi.SDK.showAd(type): Shows an ad.-
Parameters:
-
type: The type of ad.
-
-
Parameters:
Hybrid App Authentication (Recommended):
// ✅ Modern hybrid app approach
async function initializeApp() {
// 1. Detect Pi Browser first
const isPiBrowser = await detectPiBrowser();
if (!isPiBrowser) {
// Show fallback UI for regular browsers
document.getElementById('app').innerHTML = `
<div class="fallback-message">
<h3>Pi Features Available in Pi Browser</h3>
<p>For full functionality, open this app in Pi Browser:</p>
<a href="https://pinet.com/YOUR_APP_LINK" class="pi-button">
Open in Pi Browser
</a>
</div>
`;
return;
}
// 2. Only show Pi features when in Pi Browser
showPiFeatures();
}
// User-initiated authentication (no scary popups)
async function handleLogin() {
try {
const scopes = ['payments'];
const auth = await Pi.authenticate(scopes, onIncompletePaymentFound);
console.log('Authentication successful:', auth);
updateUIForLoggedInUser(auth);
} catch (error) {
console.error('Authentication failed:', error);
}
}
// Pi Browser detection helper
async function detectPiBrowser() {
const timeout = new Promise(resolve =>
setTimeout(() => resolve("timeout"), 3000)
);
try {
if (window?.Pi?.getPiHostAppInfo) {
const result = await Promise.race([
window.Pi.getPiHostAppInfo(),
timeout,
]);
return result?.hostApp === "pi-browser";
}
} catch (e) {
console.warn("Pi SDK detection failed", e);
}
// Fallback detection
const ua = navigator?.userAgent?.toLowerCase() || "";
return ua.includes("pibrowser") || document.referrer.includes("minepi.com");
}
function onIncompletePaymentFound(payment) {
// Handle incomplete payments
console.log("Incomplete payment found:", payment);
}Legacy Authentication (Not Recommended):
// ❌ Old approach - causes popups in regular browsers
Pi.authenticate(['payments'], onIncompletePaymentFound).then(function(auth) {
console.log(`Hi there! You're ready to make payments!`);
}).catch(function(error) {
console.error(error);
});Create a payment:
Pi.Payments.createPayment({
amount: 100,
currency: 'USD',
description: 'Test payment'
}, (error, result) => {
if (error) {
// Handle the error
} else {
// The payment has been created
}
});Open a conversation:
Pi.openConversation('1234567890', (error) => {
if (error) {
// Handle the error
} else {
// The conversation has been opened
}
});Open a share dialog:
Pi.openShareDialog(
'Share this awesome content!',
'This is some great content that you should check out.'
);Open a URL in the system browser:
Pi.openUrlInSystemBrowser('https://minepi.com');Request a permission:
Pi.requestPermission('storage', (hasPermission) => {
if (hasPermission) {
// The permission has been granted
} else {
// The permission has been denied
}
});Scan a QR code:
Pi.scanQrCode((error, result) => {
if (error) {
// Handle the error
} else {
// The QR code has been scanned
}
});- 🏠 Home - Complete developer handbook
- 🆘 Community Support - Get help from Pi developers
- 🔐 Authorization - Authentication & security patterns
- 🔌 API Reference - Complete REST API documentation
- ⚡ SDK Reference - JavaScript SDK comprehensive guide
- 📋 Data Types - Object structures & schemas
- 🌐 Pi Browser Detection - Build hybrid Web2/Web3 apps
- 🔄 Migration Guide - Upgrade to hybrid architecture
- 💻 Code Examples - Production-ready samples & templates
- 🌍 What is PiNet? - Cross-platform app accessibility
- 💳 What is PiWallet? - Pi Network wallet integration
- 💰 Payments Overview - Transaction handling guide
- 💬 Chat Rooms for Apps - Community engagement features
- 🔄 Mainnet vs. Testnet - Environment selection guide
- 📋 Developer Terms - Terms of service
- ⚖️ Social Chain ToS - Platform terms
- 📄 Whitepaper - Pi Network foundations