Skip to content

SDK Reference

alxspiker edited this page Jul 31, 2025 · 11 revisions

Pi Network SDK Reference

Table of Contents

Introduction

The Pi Network SDK is a JavaScript library that allows developers to integrate Pi Network features into their web applications. The SDK provides a set of methods that can be used to authenticate users, create payments, open share dialogs, and more.

Installation

To install the Pi Network SDK, add the following script tag to your HTML document:

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

Usage

Once the SDK is installed, you can initialize Pi:

Pi.init({ version: "2.0", sandbox: false }); //Set sandbox to true if deploying in a sandbox enviroment

The Pi class provides a number of methods that can be used to interact with Pi Network. For example, to authenticate a user, you can use the authenticate method:

// Authenticate the user, and get permission to request payments from them:
const scopes = ['payments'];

// Read more about this callback in the SDK reference:
function onIncompletePaymentFound(payment) { /* ... */ };

Pi.authenticate(scopes, onIncompletePaymentFound).then(function(auth) {
    console.log(`Hi there! You're ready to make payments!`);
}).catch(function(error) {
    console.error(error);
});

Sandbox Environment

(Development)

  • Purpose: The sandbox allows you to test and develop your app in a simulated environment before deploying it to production.
  • Configuration:
    • Set the sandbox: true flag in your SDK initialization.
    • Obtain your Sandbox URL from the Developer Portal.
  • Sandbox Authorization: Follow these steps:
    1. Open the Pi App on your mobile device.
    2. Navigate to Pi Utilities.
    3. Click "Authorize Sandbox" and follow the instructions.

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
    }
});

🧭 Pi Developer Navigation

πŸš€ Getting Started


πŸ“– Core References


πŸ› οΈ Implementation Guides


🌟 Platform Features


βš™οΈ Environment & Deployment


πŸ“œ Legal & Compliance


πŸ“‘ Resources & Whitepapers


πŸ’‘ Need help? Join our Discord community!

Clone this wiki locally