SDK Reference - alxspiker/Pi-Network-Developer-Docs GitHub Wiki

โšก Pi Network SDK Reference

Complete JavaScript SDK for Pi Network integration

Build powerful Pi Network apps with authentication, payments, and native device features

๐Ÿ“‹ Table of Contents


๐Ÿš€ Quick Start

๐ŸŽฏ 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

๐Ÿ“ฆ Installation

Method 1: CDN (Recommended)

Add the SDK script to your HTML document:

<script src="https://sdk.minepi.com/pi-sdk.js"></script>

Method 2: Self-hosted

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


๐Ÿ”ง Initialization

Basic Setup

Initialize the Pi SDK in your application:

// Initialize Pi SDK
Pi.init({ 
  version: "2.0", 
  sandbox: false  // Set to true for development/testing
});

๐ŸŒ Hybrid App Setup (Recommended)

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


๐Ÿงช Sandbox Environment

๐Ÿ”ฌ Perfect your app before going live

๐ŸŽฏ Development Mode
Use sandbox mode to test your Pi Network integration without real transactions or user impact.

๐Ÿ› ๏ธ Setup & Configuration

1. Enable Sandbox Mode

Pi.init({ 
  version: "2.0", 
  sandbox: true  // โœ… Enable for development
});

2. Get Sandbox Credentials

  1. Open Pi Mining App on your mobile device
  2. Navigate to Pi Utilities section
  3. Select "Authorize Sandbox"
  4. Follow the authorization instructions
  5. Copy your sandbox URL from Developer Portal

3. Test Environment Benefits

๐ŸŽฏ 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

Functions and Methods

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);
  • Pi.Error.auth(errorMessage): Reports an authentication error to the Pi Network platform.
    • Parameters:
      • errorMessage: The error message to report.
  • Pi.Error.unknown(errorMessage): Reports an unknown error to the Pi Network platform.
    • Parameters:
      • errorMessage: The error message to report.

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.
  • 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.
  • Pi.Payments.preparePaymentFlow(paymentData): Prepares a payment flow.
    • Parameters:
      • paymentData: The payment data.
    • Returns: A promise that resolves to the payment ID.
  • 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.
  • Pi.Payments.waitForTransaction(paymentId): Waits for a transaction to complete.
    • Parameters:
      • paymentId: The payment ID.
    • Returns: A promise that resolves to the transaction details.
  • Pi.Payments.showPrePaymentError(errorMessage): Shows a pre-payment error.
    • Parameters:
      • errorMessage: The error message to show.

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

Initialization

  • Pi.init(options): Initializes the SDK.
    • Parameters:
      • options: The initialization options.
    • Returns: A promise that resolves when the SDK has been initialized.

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.
  • 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.
  • 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.
  • 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.
  • Pi.scanQrCode(config): Scans a QR code.
    • Parameters:
      • config: The configuration object.
    • Returns: A promise that resolves to the scanned data.

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.
  • Pi.SDK.decideCallbackRetrial(callbackId, shouldRetry): Decides whether to retry a callback.
    • Parameters:
      • callbackId: The callback ID.
      • shouldRetry: Whether to retry the callback.
  • 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.
  • 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.
  • Pi.SDK.requestAd(type): Requests an ad.
    • Parameters:
      • type: The type of ad.
    • Returns: A promise that resolves to an ad object.
  • Pi.SDK.showAd(type): Shows an ad.
    • Parameters:
      • type: The type of ad.

Code Examples

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
    }
});
โš ๏ธ **GitHub.com Fallback** โš ๏ธ