### Install Pi SDK and Initialize Source: https://github.com/pi-apps/pi-platform-docs/blob/master/README.md Includes script tags to load the Pi Network JS SDK and initializes it with a specified version. This makes the SDK available globally as `window.Pi`. ```html ``` -------------------------------- ### Show Interstitial Ad Source: https://github.com/pi-apps/pi-platform-docs/blob/master/ads.md Demonstrates the basic integration of interstitial ads, typically displayed during application transitions. This example shows how to trigger an ad display after completing a level, specifically when the current level is a multiple of three. ```typescript completeLevel(); if (currentLevel % 3 === 0) { await Pi.Ads.showAd("interstitial"); } startNewLevel(); ``` -------------------------------- ### Advanced Interstitial Ad Flow Source: https://github.com/pi-apps/pi-platform-docs/blob/master/ads.md Provides an advanced example for interstitial ads, showing how to proactively check ad readiness, request an ad if not ready, and then display it. It also includes error handling for cases where the ad cannot be loaded or displayed. ```typescript const isAdReadyResponse = await Pi.Ads.isAdReady("interstitial"); if (isAdReadyResponse.ready === true) { return Pi.Ads.showAd("interstitial"); } const requestAdResponse = await Pi.Ads.requestAd("interstitial"); if (requestAdResponse.result !== "AD_LOADED") { // indicate to user that ad could not be loaded return; } const showAdResponse = await Pi.Ads.showAd("interstitial"); if (showAdResponse.result !== "AD_CLOSED") { // indicate to user that ad could not be displayed return; } ``` -------------------------------- ### Verify User with Pi API /me Endpoint Source: https://github.com/pi-apps/pi-platform-docs/blob/master/authentication.md Make a GET request to the `/me` Pi API endpoint using the obtained access token in the Authorization header for verification. A valid token returns user data, while an invalid one results in a 401 Unauthorized response. ```javascript const me = await axios.get('https://api.minepi.com/v2/me', { headers: { 'Authorization': `Bearer ${accessToken}` } }); ``` -------------------------------- ### PiNet Backend Metadata API Source: https://github.com/pi-apps/pi-platform-docs/blob/master/pinet.md Details the API endpoint PiNet uses to fetch metadata from a custom backend. PiNet sends a GET request to your specified backend URL with the pathname, expecting a PiNetMetadataDTO response. ```APIDOC Endpoint: /pinet/meta Method: GET Parameters: pathname (string, required): The encoded pathname of the URL being accessed. Example: ?pathname=%2Ffaq%2F1 Request: PiNet sends a GET request to your configured backend URL, appending the /pinet/meta endpoint and the pathname parameter. Example: GET https://your-backend.com/pinet/meta?pathname=%2Ffaq%2F1 Response: On success (HTTP status code 200), PiNet expects a response body conforming to the PiNetMetadataDTO shape. Any other status code or malformed response will result in metadata not being exposed. PiNetMetadataDTO: description: Data Transfer Object for PiNet metadata. properties: title (string, optional): The title for the metadata. description (string, optional): The description for the metadata. image (string, optional): URL for the metadata image. type (string, optional): The type of metadata (e.g., 'website', 'article'). url (string, optional): The canonical URL for the metadata. twitter_card (string, optional): Specifies the Twitter card type (e.g., 'summary', 'summary_large_image'). twitter_site (string, optional): The Twitter handle of the website owner. twitter_creator (string, optional): The Twitter handle of the content creator. og_locale (string, optional): The locale of the content. og_site_name (string, optional): The name of the website. og_type (string, optional): The type of object described (e.g., 'article', 'website'). og_title (string, optional): The title of the content. og_description (string, optional): The description of the content. og_image (string | array, optional): An image representing the content. og_url (string, optional): The canonical URL of the content. Example PiNetMetadataDTO Response: { "title": "My Awesome App", "description": "Discover the best features of my app.", "image": "https://example.com/images/preview.png", "twitter_card": "summary_large_image", "og_type": "website" } Error Conditions: - Non-200 HTTP status codes from the backend. - Response body does not conform to the PiNetMetadataDTO schema. - Backend URL is invalid or unreachable. ``` -------------------------------- ### Pi SDK Initialization Configuration Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Details the configuration options for Pi.init, including version and sandbox mode. ```APIDOC Pi.init(config: { version: string; // Required: SDK version for compatibility sandbox?: boolean; // Optional: Enables sandbox mode }): void; // Configuration object keys: // - version (string, required): Ensures compatibility with SDK versions. Higher version numbers indicate potential breaking changes. // - sandbox (boolean, optional): If true, configures the SDK to run in the sandbox environment. Useful for development and testing. ``` -------------------------------- ### Create Pi Payment Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Demonstrates how to initiate a payment flow using the Pi SDK, including defining payment data and handling callbacks. ```typescript type PaymentData = { amount: number, memo: string, metadata: Object, }; type PaymentCallbacks = { onReadyForServerApproval: (paymentId: string) => void, onReadyForServerCompletion: (paymentId: string, txid: string) => void, onCancel: (paymentId: string) => void, onError: (error: Error, payment?: PaymentDTO) => void, }; Pi.createPayment(paymentData: PaymentData, callbacks: PaymentCallbacks): void; ``` -------------------------------- ### Initialize Pi SDK Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Includes the Pi SDK script and initializes the SDK with a version. Essential for using Pi Apps functionalities. ```html ``` -------------------------------- ### Initialize Pi SDK in Sandbox Mode Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Initializes the Pi SDK with version and sandbox mode enabled for testing in the sandbox environment. ```html ``` -------------------------------- ### Pi SDK API Reference Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Provides documentation for core Pi SDK functionalities, including retrieving a list of supported native features and opening the native share dialog. ```APIDOC Pi.nativeFeaturesList() - Description: Retrieves a list of native features available for the user's current Pi Browser version. This is crucial for ensuring SDK features function correctly. - Returns: A Promise that resolves to an Array of NativeFeature strings. - NativeFeature Type: type NativeFeature = "inline_media" | "request_permission" | "ad_network"; Pi.openShareDialog(title: string, message: string) - Description: Opens the native operating system's share dialog, allowing users to share content from the app. The dialog is provided by the phone's OS. - Parameters: - title: The title of the message being shared. - message: The content that will be sent when the user selects a target app. - Returns: void ``` -------------------------------- ### Pi SDK Payment API Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Details the `Pi.createPayment` method for initiating payment flows, its parameters, and callback functions for handling payment lifecycle events. ```APIDOC Pi.createPayment(paymentData: PaymentData, callbacks: PaymentCallbacks): void Adds a description for the Pi.createPayment method. This method initiates the payment flow, opening an interface for the user to review and submit the transaction. Parameters: paymentData: Object The data required for the payment. - amount: number (required) - The amount the user is requested to pay. - memo: string (optional) - A memo visible to the user, explaining the payment. - metadata: Object (optional) - An arbitrary JavaScript object for internal use, linking payments to business logic. callbacks: Object Functions to handle different stages of the payment lifecycle. - onReadyForServerApproval: (paymentId: string) => void Called when a payment identifier is obtained from Pi Servers. Invoked multiple times during the approval period if initial attempts fail. Use to send paymentId to your backend for Server-Side Approval. - onReadyForServerCompletion: (paymentId: string, txid: string) => void Called when the user submits the transaction to the Pi Blockchain. Invoked multiple times during the completion period if initial attempts fail. Use to send the transaction identifier (txid) and paymentId to your backend for Server-Side Completion. - onCancel: (paymentId: string) => void Called when the payment is cancelled, either by user action or programmatically (e.g., insufficient funds, concurrent payment). - onError: (error: Error, payment?: PaymentDTO) => void Called when an error occurs and the payment cannot be made. The optional 'payment' argument provides details if the payment was created. Concurrent Payments Warning: If an open payment exists for the current user: - If the user hasn't made the blockchain transaction, the open payment is cancelled. - If the user has made the blockchain transaction, the new payment is rejected, and `onError` is called. The `onIncompletePaymentFound` callback from `authenticate` should be used to resolve such situations. Related Methods: - Pi.authenticate: Used to authenticate the user before initiating payments. ``` -------------------------------- ### Pi SDK Authentication Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Authenticates the user and retrieves necessary information. Handles incomplete payments via a callback. ```APIDOC Pi.authenticate(scopes: Array, onIncompletePaymentFound: Function): Promise; // Parameters: // - scopes (Array): An array of permissions to request from the user. Available scopes include 'username', 'payments', 'wallet_address'. // - onIncompletePaymentFound (Function): A callback function invoked if an incomplete payment is detected for the user. It receives a PaymentDTO object. // Return Value: // - Promise: A promise that resolves with an AuthResult object containing the access token and user information. // AuthResult Type: // type AuthResult = { // accessToken: string; // user: { // uid: string; // App-local identifier for the user, specific to the app and user. // username: string; // The user's Pi username (requires 'username' scope). // // Other user properties might be available based on requested scopes. // }; // }; // onIncompletePaymentFound Callback: // Signature: (payment: PaymentDTO) => void // This callback is triggered when an ongoing payment is found where the developer has not yet called the '/complete' endpoint. // The developer is responsible for processing this payment (e.g., sending to backend) before requesting a new payment. // Scope Breakdown: // | Field | Description | Required Scope | // |------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------| // | user.uid | An app-local identifier for the user. Specific to this user and app. Changes if user revokes permissions. | (none) | // | user.username | The user's Pi username. | 'username' | // | user.payments | Required if the app needs to make payments between the app and users. | 'payments' | // | user.wallet_address | The wallet address of the user authenticating on the app. | 'wallet_address' | // Warning: User information obtained via this method should only be used for presentation logic and not passed to the backend. Use the Platform API as the source of truth for backend operations. ``` -------------------------------- ### Platform API Authentication Methods Source: https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md Details on how to authenticate requests to the Pi Platform API using either user access tokens or server API keys. ```APIDOC Authorization Header Formats: 1. Access Token Authorization (for user-specific data): Header: Authorization: Bearer Usage: Access user's data (e.g., /me endpoint). Applicable from: Backend/Server App, Frontend/Client App. 2. Server API Key Authorization (for server-only operations): Header: Authorization: Key Usage: Access endpoints requiring server-side operations (e.g., POST /payments). Warning: Server API Keys must be kept secret on the server and never exposed to clients. Applicable from: Backend/Server App ONLY. ``` -------------------------------- ### Pi Ads API: showAd, isAdReady, requestAd Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Manages ad display, checks ad availability, and requests new ads. Supports interstitial and rewarded ad types, detailing response codes for various ad states and network conditions. Includes notes on ad verification for rewarded ads. ```APIDOC Pi Ads API This module provides functionalities for displaying and managing advertisements within the Pi Browser. --- **1. showAd** Displays an ad to the user. * **Signature:** `Pi.Ads.showAd(adType: "interstitial" | "rewarded"): Promise` * **Parameters:** * `adType`: The type of ad to display. Accepts either `"interstitial"` or `"rewarded"`. * **Returns:** A `Promise` that resolves with a `ShowAdResponse` object. * **`ShowAdResponse` Type:** ```typescript type ShowAdResponse = | { type: "interstitial"; result: "AD_CLOSED" | "AD_DISPLAY_ERROR" | "AD_NETWORK_ERROR" | "AD_NOT_AVAILABLE"; } | { type: "rewarded"; result: "AD_REWARDED" | "AD_CLOSED" | "AD_DISPLAY_ERROR" | "AD_NETWORK_ERROR" | "AD_NOT_AVAILABLE" | "ADS_NOT_SUPPORTED" | "USER_UNAUTHENTICATED"; adId?: string; }; ``` * **Result Codes:** * `"AD_CLOSED"`: Ad was successfully displayed and closed. * `"AD_REWARDED"`: Ad was successfully displayed and rewarded (only for `rewarded` ads). * `"AD_DISPLAY_ERROR"`: Ad loaded but failed to display. * `"AD_NETWORK_ERROR"`: Potential network connection issues encountered. * `"AD_NOT_AVAILABLE"`: Ad failed to load. * `"ADS_NOT_SUPPORTED"`: User's app version does not support ads. * `"USER_UNAUTHENTICATED"`: User not authenticated for rewarded ads. * **Notes:** * The `adId` field is present in `rewarded` ad responses if the application is approved for the Pi Developer Ad Network, allowing for status verification via the Pi Platform API. * For unapproved applications, `adId` will be missing; rewards should not be granted without verification. --- **2. isAdReady** Checks if an ad of a specific type is available for display. * **Signature:** `Pi.Ads.isAdReady(adType: "interstitial" | "rewarded"): Promise` * **Parameters:** * `adType`: The type of ad to check. Accepts either `"interstitial"` or `"rewarded"`. * **Returns:** A `Promise` that resolves with an `IsAdReadyResponse` object. * **`IsAdReadyResponse` Type:** ```typescript type IsAdReadyResponse = { type: "interstitial" | "rewarded"; ready: boolean; }; ``` * **Usage:** Useful for proactively checking ad availability before calling `showAd`. --- **3. requestAd** Manually requests an ad to be pre-loaded. * **Signature:** `Pi.Ads.requestAd(adType: "interstitial" | "rewarded"): Promise` * **Parameters:** * `adType`: The type of ad to request. Accepts either `"interstitial"` or `"rewarded"`. * **Returns:** A `Promise` that resolves with a `RequestAdResponse` object. * **`RequestAdResponse` Type:** ```typescript type RequestAdResponse = { type: "interstitial" | "rewarded"; result: "AD_LOADED" | "AD_FAILED_TO_LOAD" | "AD_NOT_AVAILABLE"; }; ``` * **Usage:** Can be used to retry ad requests if `isAdReady()` returns `false`. --- **Internal Management:** The Pi Browser automatically manages ad loading and reloading to ensure ads are ready. However, `requestAd()` provides a manual override for developers to handle cases where ads might be interrupted or requested too rapidly. ``` ```typescript type AdType = "interstitial" | "rewarded"; type ShowAdResponse = | { type: "interstitial"; result: "AD_CLOSED" | "AD_DISPLAY_ERROR" | "AD_NETWORK_ERROR" | "AD_NOT_AVAILABLE"; } | { type: "rewarded"; result: "AD_REWARDED" | "AD_CLOSED" | "AD_DISPLAY_ERROR" | "AD_NETWORK_ERROR" | "AD_NOT_AVAILABLE" | "ADS_NOT_SUPPORTED" | "USER_UNAUTHENTICATED"; adId?: string; }; type IsAdReadyResponse = { type: "interstitial" | "rewarded"; ready: boolean; }; type RequestAdResponse = { type: "interstitial" | "rewarded"; result: "AD_LOADED" | "AD_FAILED_TO_LOAD" | "AD_NOT_AVAILABLE"; }; // Example usage: // Pi.Ads.showAd('interstitial').then(response => console.log(response)); // Pi.Ads.isAdReady('rewarded').then(response => console.log(response)); // Pi.Ads.requestAd('interstitial').then(response => console.log(response)); ``` -------------------------------- ### Show Rewarded Ad with Pi SDK Source: https://github.com/pi-apps/pi-platform-docs/blob/master/ads.md Demonstrates the process of showing a rewarded ad using the Pi SDK. It includes checking ad readiness, requesting an ad if not ready, displaying the ad, and handling the reward callback. It also highlights the need for backend verification of the adId against the Pi Platform API before granting rewards. ```typescript const showRewardedAd = async () => { try { const isAdReadyResponse = await Pi.Ads.isAdReady("rewarded"); if (isAdReadyResponse.ready === false) { const requestAdResponse = await Pi.Ads.requestAd("rewarded"); if (requestAdResponse.result === "ADS_NOT_SUPPORTED") { // display modal to update Pi Browser return showAdsNotSupportedModal(); } if (requestAdResponse.result !== "AD_LOADED") { // display modal ads are temporarily unavailable and user should try again later return showAdUnavailableModal(); } } const showAdResponse = await Pi.Ads.showAd("rewarded"); if (showAdResponse.result === "AD_REWARDED") { // reward user logic: // usually delegate rewarding user to your backend which would // firstly verify `adId` against Pi Platform API, then decide whether to // reward the user and rewarded user if the rewarded ad status is confirmed // e.g.: const result = await rewardUserForWatchingRewardedAd(adId); if (result.rewarded === true) { showRewardedModal(result.reward); } else { showRewardFailModal(result.error); } } else { // fallback logic showAdErrorModal(); } } catch (err) { // good practice to handle any potential errors } }; ``` -------------------------------- ### Open URL in System Browser Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Opens a specified URL in the user's default system browser, bypassing the Pi Browser. Handles potential errors during the opening process. ```APIDOC Open URL in System Browser Opens a given URL using the device's default system browser. * **Signature:** `Pi.openUrlInSystemBrowser(url: string): Promise` * **Parameters:** * `url`: The URL string to open in the system browser. * **Returns:** A `Promise` that resolves when the URL is successfully opened or rejects with an `Error` if an issue occurs. * **Possible Errors:** * `"Failed to open URL"`: The URL could not be opened, possibly due to an invalid URL format. * `"No minimal requirements"`: The user's Pi Browser version is too old to support this method. * `"Unexpected error"`: An unhandled error occurred during the operation. * **Recommendation:** If `"No minimal requirements"` is received, encourage users to update their Pi Browser. ``` ```typescript // Example usage: // Pi.openUrlInSystemBrowser('https://www.example.com').catch(error => console.error(error)); ``` -------------------------------- ### Platform API Payments Management Source: https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md Comprehensive reference for managing payments, including creating, retrieving, approving, completing, cancelling, and listing incomplete server payments. ```APIDOC Payment Types: - U2A (User-To-App): Initiated via client-side SDK (e.g., Javascript SDK's createPayment method). - A2U (App-To-User): Initiated via server-side API. Endpoints: 1. Create Payment (A2U): Method: POST Path: /payments Authorization Method: Server API Key Request Body Example: { "payment": { "amount": 1, "memo": "From app to user test", "metadata": {"test": "test metadata"}, "uid": "a1111111-aaaa-bbbb-2222-ccccccc3333d" } } Response Type: [PaymentDTO](#PaymentDTO) 2. Get Payment: Method: GET Path: /payments/{payment_id} Authorization Method: Server API Key Response Type: [PaymentDTO](#PaymentDTO) 3. Approve Payment (Server-side): Method: POST Path: /payments/{payment_id}/approve Description: Marks a payment as approved, allowing the user to submit the transaction to the blockchain. Authorization Method: Server API Key Response Type: [PaymentDTO](#PaymentDTO) 4. Complete Payment (Server-side): Method: POST Path: /payments/{payment_id}/complete Description: Marks a payment as completed by confirming the app has obtained the payment's txid. Authorization Method: Server API Key Request Body Example: { "txid": "7a7ed20d3d72c365b9019baf8dc4c4e3cce4c08114d866e47ae157e3a796e9e7" } Response Type: [PaymentDTO](#PaymentDTO) 5. Cancel Payment: Method: POST Path: /payments/{payment_id}/cancel Description: Marks the payment as cancelled. Authorization Method: Server API Key Response Type: [PaymentDTO](#PaymentDTO) 6. Get Incomplete Server Payments: Method: GET Path: /payments/incomplete_server_payments Description: Returns a list of A2U payments that are either created but not yet transacted, or transacted but not yet completed. Authorization Method: Server API Key Response Type: { "incomplete_server_payments": Array<[PaymentDTO](#PaymentDTO)> } ``` -------------------------------- ### Show Rewarded Ad and Verify Source: https://github.com/pi-apps/pi-platform-docs/blob/master/ads.md Illustrates how to display rewarded ads, offering users in-app rewards for watching. It highlights the critical security step of verifying the ad's validity using the returned `adId` against the Pi Platform API to ensure users are legitimately rewarded. ```typescript const showAdResponse = await Pi.Ads.showAd("rewarded"); if (showAdResponse.result === "AD_REWARDED") { // delegate rewarding user to your backend // e.g.: const result = await rewardUserForWatchingRewardedAd(showAdResponse.adId); if (result.rewarded === true) { grantUserAdditionalLive(); } } ``` -------------------------------- ### Pi Payment Flow API and SDK Interactions Source: https://github.com/pi-apps/pi-platform-docs/blob/master/payments.md Details the sequence of API calls and SDK callbacks involved in processing a payment within the Pi Platform. This includes initiating a payment, server-side approval, user transaction, and server-side completion. ```javascript /** * Initiates a payment process. * This function is called from your app's frontend. */ piSDK.createPayment(); /** * Callback function invoked by the Pi SDK when a payment is ready for server approval. * Your app's server should then make an API request to approve the payment. * @param {string} paymentId - The unique identifier for the payment. */ function onReadyForServerApproval(paymentId) { console.log("Payment ready for server approval. PaymentID:", paymentId); // Send paymentId to your app's server for approval sendPaymentIdToServer(paymentId); } /** * Callback function invoked by the Pi SDK when a payment is ready for server completion. * Your app's server should then make an API request to complete the payment. * @param {string} txId - The blockchain transaction identifier. */ function onReadyForServerCompletion(txId) { console.log("Payment ready for server completion. TxID:", txId); // Send txId to your app's server for completion sendTxIdToServer(txId); } ``` ```APIDOC /** * API Endpoint for Server-Side Approval * * POST /approve * * Description: * This endpoint is called by your app's server to approve a payment initiated by the user. * Upon successful approval, the user is enabled to submit the blockchain transaction. * * Request Body: * { * "paymentId": "string" // The unique identifier for the payment, obtained from the SDK. * } * * Responses: * 200 OK: * Description: Payment successfully approved. * Body: * { * "status": "approved" * } * 400 Bad Request: * Description: Invalid paymentId or payment already processed. * 500 Internal Server Error: * Description: Server-side error during approval. * * Related Methods: * - POST /complete: Used for server-side completion after the blockchain transaction. */ /** * API Endpoint for Server-Side Completion * * POST /complete * * Description: * This endpoint is called by your app's server to acknowledge a completed payment. * It verifies the blockchain transaction and signals to Pi Servers that the payment is complete. * Crucially, if this API call returns a non-200 error, the payment should NOT be marked as complete on your side, and goods/services should not be delivered. * * Request Body: * { * "paymentId": "string", // The unique identifier for the payment. * "txId": "string" // The blockchain transaction identifier. * } * * Responses: * 200 OK: * Description: Payment successfully completed and verified. * Body: * { * "status": "completed" * } * 400 Bad Request: * Description: Invalid paymentId, txId, or payment already completed. * 402 Payment Required: * Description: The blockchain transaction associated with the txId has not been confirmed or is invalid. Do NOT deliver goods. * 500 Internal Server Error: * Description: Server-side error during completion. * * Related Methods: * - POST /approve: Used for server-side approval before the user interacts with the blockchain. */ ``` -------------------------------- ### Authenticate User for Payments Source: https://github.com/pi-apps/pi-platform-docs/blob/master/README.md Authenticates the user and requests permission for specific scopes, such as payments. It handles user consent and returns a promise that resolves upon successful authentication or rejects on error. ```javascript // 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); }); ``` -------------------------------- ### Pi Platform Data Types Source: https://github.com/pi-apps/pi-platform-docs/blob/master/SDK_reference.md Defines essential data structures used within the Pi Platform SDK for handling payments and user scopes. Includes PaymentDTO for payment details, Direction for transaction flow, AppNetwork for network identification, and Scope for permission requests. ```typescript type PaymentDTO = { // Payment data: identifier: string; // payment identifier user_uid: string; // user's app-specific ID amount: number; // payment amount memo: string; // a string provided by the developer, shown to the user metadata: Object; // an object provided by the developer for their own usage from_address: string; // sender address of the blockchain transaction to_address: string; // recipient address of the blockchain transaction direction: Direction; // direction of the payment created_at: string; // payment's creation timestamp network: AppNetwork; // a network of the payment // Status flags representing the current state of this payment status: { developer_approved: boolean; // Server-Side Approval transaction_verified: boolean; // blockchain transaction verified developer_completed: boolean; // server-Side Completion cancelled: boolean; // cancelled by the developer or by Pi Network user_cancelled: boolean; // cancelled by the user }; // Blockchain transaction data: transaction: null | { // This is null if no transaction has been made yet txid: string; // id of the blockchain transaction verified: boolean; // true if the transaction matches the payment, false otherwise _link: string; // a link to the operation on the Blockchain API }; }; type Direction = "user_to_app" | "app_to_user"; type AppNetwork = "Pi Network" | "Pi Testnet"; type Scope = "username" | "payments" | "wallet_address"; ``` -------------------------------- ### Request User-to-App Payment Source: https://github.com/pi-apps/pi-platform-docs/blob/master/README.md Requests a payment from the current user to the app's account. The user is prompted with a Pi Wallet modal to sign and submit the transaction. This method requires implementing specific callbacks for payment lifecycle events. ```javascript Pi.createPayment({ // Amount of π to be paid: amount: 3.14, // An explanation of the payment - will be shown to the user: memo: "...", // e.g: "Digital kitten #1234", // An arbitrary developer-provided metadata object - for your own usage: metadata: { /* ... */ }, // e.g: { kittenId: 1234 } }, { // Callbacks you need to implement - read more about those in the detailed docs linked below: onReadyForServerApproval: function(paymentId) { /* ... */ }, onReadyForServerCompletion: function(paymentId, txid) { /* ... */ }, onCancel: function(paymentId) { /* ... */ }, onError: function(error, payment) { /* ... */ }, }); ``` -------------------------------- ### Call Pi SDK authenticate() Source: https://github.com/pi-apps/pi-platform-docs/blob/master/authentication.md Using the Pi SDK `authenticate()` method, you can obtain user information along with the access token. This function is typically called within the client-side application. ```javascript const authRes = await window.Pi.authenticate(scopes, onIncompletePaymentFound); ``` -------------------------------- ### Platform API User Resource Access Source: https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md Endpoint for retrieving user information, accessible with an access token. Verifies token validity and user identity. ```APIDOC GET /me Description: Retrieves user information, limited to data the user has consented to share with the app. Authorization Method: Access token (Authorization: Bearer ) Response Type: [UserDTO](#UserDTO) Notes: - Verify data obtained from frontend SDKs by sending the user's access token to your backend. - The request fails with a 401 HTTP error code if the token is tampered with or invalid. ``` -------------------------------- ### Verify Rewarded Ad Status API Endpoint Source: https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md API endpoint to verify the status of a rewarded ad using its unique identifier. Requires server-side API key authentication. Returns a RewardedAdStatusDTO object. ```APIDOC GET /ads_network/status/:adId - Authorization method: Server API Key - Response type: RewardedAdStatusDTO ``` -------------------------------- ### Payment Data Structure (PaymentDTO) Source: https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md Details the structure for payment information, encompassing transaction specifics, user identifiers, amounts, memo, metadata, addresses, status flags, and blockchain transaction data. Includes fields for developer approval, transaction verification, completion, cancellation, and blockchain transaction details. ```typescript { // Payment data: identifier: string, // payment identifier user_uid: string, // user's app-specific ID amount: number, // payment amount memo: string, // a string provided by the developer, shown to the user metadata: Object, // an object provided by the developer for their own usage from_address: string, // sender address of the blockchain transaction to_address: string, // recipient address of the blockchain transaction direction: Direction, // direction of the payment created_at: string, // the payment's creation timestamp network: AppNetwork, // a network of the payment // Status flags representing the current state of this payment status: { developer_approved: boolean, // Server-Side Approval transaction_verified: boolean, // blockchain transaction verified developer_completed: boolean, // Server-Side Completion cancelled: boolean, // cancelled by the developer or by Pi Network user_cancelled: boolean, // cancelled by the user }, // Blockchain transaction data: transaction: null | { txid: string, // id of the blockchain transaction verified: boolean, // true if the transaction matches the payment, false otherwise _link: string, // a link to the operation on the Blockchain API }, }; ``` -------------------------------- ### OpenGraph Helper Types Source: https://github.com/pi-apps/pi-platform-docs/blob/master/pinet.md Provides supporting type aliases for OpenGraph metadata, including descriptors for images, videos, audio, and specific entities like actors, songs, and albums. These types are reused across various `OGMetadata` union members. ```typescript type OGImageDescriptor = { url: string; secureUrl?: string; alt?: string; type?: string; width?: string | number; height?: string | number; }; type OGImage = string | OGImageDescriptor; type OGVideoDescriptor = { url: string; secureUrl?: string; alt?: string; type?: string; width?: string | number; height?: string | number; }; type OGVideo = string | OGVideoDescriptor; type OGAudioDescriptor = { url: string; secureUrl?: string; alt?: string; }; type OGAudio = string | OGAudioDescriptor; type OGActor = { url: string; role?: string; }; type OGSong = { url: string; disc?: number; track?: number; }; type OGAlbum = { url: string; disc?: number; track?: number; }; ``` -------------------------------- ### Check Pi Browser Ad Network Support Source: https://github.com/pi-apps/pi-platform-docs/blob/master/ads.md This TypeScript snippet demonstrates how to check if the Pi Browser supports the ad network feature using the `Pi.nativeFeaturesList()` SDK method. It's crucial for ensuring ads can run properly for users by verifying the presence of 'ad_network' in the returned list. ```typescript async () => { await Pi.init({ version: "2.0" }); const nativeFeaturesList = await Pi.nativeFeaturesList(); const adNetworkSupported = nativeFeaturesList.includes("ad_network"); // store adNetworkSupported for later use } ``` -------------------------------- ### Define Twitter Metadata Helper Types Source: https://github.com/pi-apps/pi-platform-docs/blob/master/pinet.md Provides reusable TypeScript type definitions for image descriptors (including secure URLs and alt text) and player descriptors (with URL, width, and height) used within Twitter card metadata. ```typescript type TwitterImageDescriptor = { \ url: string; \ secureUrl?: string; \ alt?: string; \ type?: string; \ width?: string | number; \ height?: string | number; \ }; type TwitterImage = string | TwitterImageDescriptor; type TwitterPlayerDescriptor = { \ url: string; \ width: number; \ height: number; \ }; ``` -------------------------------- ### Rewarded Ad Status Structure (RewardedAdStatusDTO) Source: https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md Defines the structure for the status of a rewarded ad, including its identifier, mediator acknowledgment status, and timestamps for when the reward was granted or revoked. The identifier corresponds to the adId token from the Pi SDK's displayAd('rewarded') method. ```typescript { "identifier": string; // the adId token returned from the Pi SDK displayAd("rewarded") method "mediator_ack_status": "granted" | "revoked" | "failed" | null; "mediator_granted_at": string | null; // ISO 8601 date string "mediator_revoked_at": string | null; // ISO 8601 date string } ``` -------------------------------- ### User Data Structure (UserDTO) Source: https://github.com/pi-apps/pi-platform-docs/blob/master/platform_API.md Defines the structure for user data, including their unique identifier, credentials with scopes and validity, and optional username. Requires the 'username' scope to access the username field. ```typescript { uid: string, // An app-specific user identifier credentials: { scopes: Array, // a list of granted scopes valid_until: { timestamp: number, iso8601: string } }, username?: string, // The user's Pi username. Requires the `username` scope. } ``` -------------------------------- ### PiNetMetadataDTO and Related Types Source: https://github.com/pi-apps/pi-platform-docs/blob/master/pinet.md Defines the PiNetMetadataDTO structure for metadata, including optional fields and nested types like Author, FormatDetection, IconDescriptor, Icon, and Icons. All fields within PiNetMetadataDTO are optional, but nested types may have mandatory fields if provided. ```typescript type PiNetMetadataDTO = { title?: string; description?: string; authors?: null | Author | Array; keywords?: null | string | Array; creator?: null | string; publisher?: null | string; formatDetection?: null | FormatDetection; abstract?: null | string; archives?: null | string | Array; category?: null | string; classification?: null | string; openGraph?: null | OGMetadata; twitter?: null | TwitterMetadata; icons?: null | string | Array | Icons; }; type Author = { url?: string; name?: string; }; type FormatDetection = { telephone?: boolean; date?: boolean; address?: boolean; email?: boolean; url?: boolean; }; type IconDescriptor = { url: string; type?: string; sizes?: string; color?: string; rel?: string; media?: string; fetchPriority?: "high" | "low" | "auto"; }; type Icon = string | IconDescriptor; type Icons = { icon?: Icon | Array; shortcut?: Icon | Array; apple?: Icon | Array; other?: IconDescriptor | Array; }; ``` -------------------------------- ### Define OpenGraph Metadata Union Source: https://github.com/pi-apps/pi-platform-docs/blob/master/pinet.md Defines the main `OGMetadata` discriminated union, which allows specifying OpenGraph metadata for different content types like websites, articles, music, and videos. It uses a `type` field as a discriminant. ```typescript type OGMetadata = | OGMetadataWebsite | OGMetadataArticle | OGMetadataBook | OGMetadataProfile | OGMetadataMusicSong | OGMetadataMusicAlbum | OGMetadataMusicPlaylist | OGMetadataMusicRadioStation | OGMetadataVideoMovie | OGMetadataVideoEpisode | OGMetadataVideoTVShow | OGMetadataVideoOther; type OGMetadataBase = { title?: string; description?: string; emails?: Array; phoneNumbers?: Array; faxNumbers?: Array; locale?: string; alternateLocale?: Array; images?: OGImage | Array; audio?: Array; videos?: Array; countryName?: string; }; type OGMetadataWebsite = OGMetadataBase & { type: "website"; }; type OGMetadataArticle = OGMetadataBase & { type: "article"; publishedTime?: string; modifiedTime?: string; expirationTime?: string; authors?: null | string | Array; section?: null | string; tags?: null | string | Array; }; type OGMetadataBook = OGMetadataBase & { type: "book"; isbn?: null | string; releaseDate?: null | string; authors?: null | string | Array; }; type OGMetadataProfile = OGMetadataBase & { type: "profile"; firstName?: null | string; lastName?: null | string; username?: null | string; gender?: null | string; }; type OGMetadataMusicSong = OGMetadataBase & { type: "music.song"; duration?: null | number; albums?: null | string | OGAlbum | Array; musicians?: null | string | Array; }; type OGMetadataMusicAlbum = OGMetadataBase & { type: "music.album"; songs?: null | string | OGSong | Array; musicians?: null | string | Array; releaseDate?: null | string; }; type OGMetadataMusicPlaylist = OGMetadataBase & { type: "music.playlist"; songs?: null | string | OGSong | Array; creators?: null | string | Array; }; type OGMetadataMusicRadioStation = OGMetadataBase & { type: "music.radio_station"; creators?: null | string | Array; }; type OGMetadataVideoMovie = OGMetadataBase & { type: "video.movie"; actors?: null | string | OGActor | Array; directors?: null | string | Array; writers?: null | string | Array; duration?: null | number; releaseDate?: null | string; tags?: null | string | Array; }; type OGMetadataVideoEpisode = OGMetadataBase & { type: "video.episode"; actors?: null | string | OGActor | Array; directors?: null | string | Array; writers?: null | string | Array; duration?: null | number; releaseDate?: null | string; tags?: null | string | Array; series?: null | string; }; type OGMetadataVideoTVShow = OGMetadataBase & { type: "video.tv_show"; }; type OGMetadataVideoOther = OGMetadataBase & { type: "video.other"; }; ``` -------------------------------- ### Define Twitter Card Metadata Types Source: https://github.com/pi-apps/pi-platform-docs/blob/master/pinet.md Defines TypeScript type aliases for various Twitter card metadata structures, including base properties and specific card types like 'summary', 'summary_large_image', 'player', and 'app'. The 'card' field acts as a discriminant for the union. ```typescript type TwitterMetadata = \ | TwitterMetadataBase \ | TwitterMetadataCardSummary \ | TwitterMetadataCardSummaryLargeImage \ | TwitterMetadataCardPlayer \ | TwitterMetadataCardApp; type TwitterMetadataBase = { \ title?: string; \ description?: string; \ creator?: string; \ creatorId?: string; \ images?: TwitterImage | Array; \ }; type TwitterMetadataCardSummary = TwitterMetadataBase & { \ card: "summary"; \ }; type TwitterMetadataCardSummaryLargeImage = TwitterMetadataBase & { \ card: "summary_large_image"; \ }; type TwitterMetadataCardPlayer = TwitterMetadataBase & { \ card: "player"; \ players: TwitterPlayerDescriptor | Array; \ }; type TwitterMetadataCardApp = TwitterMetadataBase & { \ card: "app"; \ }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.