### CLI: Install Express Route Files (Bash)
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Provides commands to install Express route files using the 'pi-sdk-express-install' CLI tool. This command generates necessary route handlers, router index files, and example app files for Pi payment integration.
```bash
# Run the CLI installer
npx pi-sdk-express-install
# Or if installed locally
yarn pi-sdk-express-install
```
--------------------------------
### Install pi-sdk-react using Yarn or npm
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/React
This command installs the pi-sdk-react package into your project. It's a prerequisite for using the Pi Network's React hooks and components in your application.
```sh
yarn add pi-sdk-react
# or
npm install pi-sdk-react
```
--------------------------------
### Get User Information (Access Token)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example shows how to make a GET request to retrieve a user's information using an access token. The response includes user details that the user has consented to share.
```http
GET /me
```
--------------------------------
### Full Stimulus Integration Example (Video Script)
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
This comprehensive bash script demonstrates the entire process of setting up the Pi SDK Rails engine for a Stimulus-based application, as shown in the 'Ten Minutes to Transactions' video. It includes creating a new Rails app, adding the gem, generating files, setting up routes, adding a buy button, configuring environment variables, and migrating the database.
```bash
# Create the app
rails new tmtt
cd tmtt
# Add the gem to the app
echo "gem 'pi-sdk-rails', git: 'https://github.com/pi-apps/pi-sdk-rails.git'" >> Gemfile
bundle install
# Generate the necessary local files
rails generate pi_sdk:install
# Set up an example button
# Create a view and controller
rails generate controller root index
# Make the root#index root for tha app
sed -i '' -e "s/# root ".*"/root to: 'root#index'/" config/routes.rb
# Add a Buy button to the end of the root#index page
cat - >> app/views/root/index.html.erb <
HTML
# Make PI_API_KEY available
source ../secrets
# Run the app
bin/dev
# Add PiTransaction model to the app
rails generate model User email
rails generate model Order description:string
rails generate pi_sdk:pi_transaction
rake db:migrate
# Run the app
bin/dev
```
--------------------------------
### Next.js Project Setup and Pi SDK Integration (Video Script)
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/NextJS
A sequence of shell commands used in a video tutorial to set up a new Next.js project, add the Pi SDK, generate components and routes, and modify layout and page files to integrate the PiButton and Pi SDK script.
```shell
# Create the app
yarn create next-app tmtt_nextjs --yes
cd tmtt_nextjs
# Add the Pi SDK package for Next.js
yarn add pi-sdk-nextjs@https://github.com/pi-apps/pi-sdk-nextjs
# Generate the routes and PiButton.tsx
yarn pi-sdk-nextjs-install
# Load Pi SDK on your pages
sed -i '' '3i\
import Script from "next/script";
' app/layout.tsx
sed -i '' '28i\
' app/layout.tsx
# Enable PiButton on the home page
sed -i '' '2i\
import { PiButton } from "@/components/PiButton";
' app/page.tsx
sed -i '' '38i\
' app/page.tsx
# Build the app
yarn build
```
--------------------------------
### Pi Apps SDK Installation
Source: https://pi-apps.github.io/pi-sdk-docs/Platform
Instructions on how to install the Pi Apps SDK by adding script tags to your HTML pages and initializing the SDK.
```APIDOC
## Pi Apps SDK Installation
Add the following `script` tags to all pages where you need to call the Pi Apps SDK:
### Pi Apps SDK
HTML
```html
```
This will load the Pi Network JS SDK as a global `window.Pi` object.
```
--------------------------------
### Install Pi SDK with Yarn or NPM
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/JavaScript
Instructions for installing the Pi SDK JavaScript package using either Yarn or NPM package managers. This is the first step in integrating the SDK into your project.
```shell
yarn add pi-sdk-js
# or
npm install pi-sdk-js
```
--------------------------------
### Full React Integration Example (Video Script - Gemfile)
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
This snippet, part of the video script for React integration, shows how to add the pi-sdk-rails gem to a new Rails application's Gemfile. It's the initial step for setting up a React-based Pi Network integration.
```bash
# Create the app
rails new tmtt
cd tmtt
# Add the gem to the app
echo "gem 'pi-sdk-rails', git: 'https://github.com/pi-apps/pi-sdk-rails.git" >> Gemfile
bundle install
```
--------------------------------
### General Pi SDK Usage Example
Source: https://pi-apps.github.io/pi-sdk-docs/Pi-SDK
This example demonstrates the basic initialization and authentication flow for the Pi SDK. It shows how to initiate the SDK, authenticate the user for specific scopes, and then proceed to create a payment request. Error handling and callbacks for different stages of the payment process are also included.
```javascript
```
--------------------------------
### Install Pi SDK Rails Engine Files
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
These commands install the pi-sdk-rails gem and generate necessary engine files for your Rails application. This includes setting up initial configurations and potentially creating new models or controllers.
```bash
bundle install
rails generate pi_sdk:install
```
--------------------------------
### Basic Express Setup with Router Factory
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Demonstrates a basic Express.js application setup using the `createPiPaymentRouter` factory function from `pi-sdk-express`. This approach quickly integrates Pi payment routes into your application.
```javascript
import express from 'express';
import { createPiPaymentRouter } from 'pi-sdk-express';
const app = express();
// Required: JSON body parser middleware
app.use(express.json());
// Mount Pi payment routes
app.use('/pi_payment', createPiPaymentRouter());
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
```
--------------------------------
### Install Pi SDK Express and Express
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Installs both the pi-sdk-express package and the Express framework. This command is typically used when setting up a new Express.js project that will handle Pi Network payments.
```bash
npm install pi-sdk-express express
# or
yarn add pi-sdk-express express
```
--------------------------------
### Run Pi SDK Next.js Installer
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/NextJS
Executes the pi-sdk-nextjs-install command to generate necessary files for Pi Network integration. This includes a React component `PiButton.tsx` and API routes for payment events.
```shell
yarn pi-sdk-nextjs-install
```
--------------------------------
### Install Pi SDK Express
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Installs the pi-sdk-express package and its dependencies using npm or yarn. This is the first step to integrate Pi Network payments into your Express.js application.
```bash
npm install pi-sdk-express
# or
yarn add pi-sdk-express
```
--------------------------------
### Basic Express Setup with Generated Routes
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Illustrates setting up an Express.js application using pre-generated route files for Pi payments. This method offers more control over the routing structure compared to the router factory.
```javascript
import express from 'express';
import piPaymentRoutes from './routes/pi_payment';
const app = express();
app.use(express.json());
app.use('/pi_payment', piPaymentRoutes);
app.listen(3000);
```
--------------------------------
### Get Payment Information (Server API Key)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example shows how to retrieve details about a specific payment using its ID. This operation requires the Server API Key for authorization.
```http
GET /payments/{payment_id}
```
--------------------------------
### Development Commands (Bash)
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Lists common development commands for the project, including dependency installation, building the project, type checking, and running tests. These commands are typically executed using Yarn.
```bash
# Install dependencies
yarn install
# Build
yarn build
# Type check
yarn typecheck
# Run tests
yarn test
# Run tests with UI
yarn test:ui
```
--------------------------------
### Initialize and Use Pi SDK in TypeScript
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/JavaScript
Demonstrates how to import and use the Pi SDK in a TypeScript project. It covers initializing the SDK, connecting to the Pi Network, and initiating a payment.
```typescript
import { PiSdkBase, PiUser, PaymentData } from 'pi-sdk-js';
const pi = new PiSdkBase();
await pi.connect();
// Now PiSdkBase.user is available (or listen for onConnection)
pi.createPayment({ amount: 1, memo: "Demo", metadata: { productId: 42 } });
```
--------------------------------
### Generate Pi Payment Route Files
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Uses the npx command to execute the pi-sdk-express-install script. This script generates essential route files for handling Pi payments within your Express.js project, including a main router and an example app setup.
```bash
npx pi-sdk-express-install
```
--------------------------------
### Get Incomplete Server Payments (Server API Key)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example demonstrates how to retrieve a list of incomplete server payments (A2U). These are payments that have been created but not yet completed or finalized on the blockchain.
```http
GET /payments/incomplete_server_payments
```
--------------------------------
### Install and Initialize Pi Apps SDK (HTML)
Source: https://pi-apps.github.io/pi-sdk-docs/Platform
This snippet shows how to include the Pi Network JS SDK in your HTML pages using script tags. It loads the SDK as a global `window.Pi` object and initializes it with a specified version. Ensure you have declared your app on the Developer Portal before using the SDK.
```html
```
--------------------------------
### Approve Payment (Server API Key)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example demonstrates how to approve a payment server-side using a POST request. Approval enables the user to submit the transaction to the blockchain.
```http
POST /payments/{payment_id}/approve
```
--------------------------------
### Check Ad Readiness and Show Rewarded Ad
Source: https://pi-apps.github.io/pi-sdk-docs/Pi-Ads
This example demonstrates how to check if a rewarded ad is ready to be shown using `Pi.Ads.isAdReady`. If ready, it proceeds to show the ad with `Pi.Ads.showAd`. If not ready, it requests the ad to be preloaded. Error handling is included for ad display failures.
```javascript
Pi.Ads.isAdReady('rewarded').then(function(ready) {
if (ready) {
Pi.Ads.showAd('rewarded').then(function(result) {
// Ad finished! Give the user a reward
grantUserBonus();
}).catch(function(err) {
// User canceled, ad failed, or unavailable
alert('Could not show ad: ' + err.message);
});
} else {
// Ad not ready; maybe preload
Pi.Ads.requestAd('rewarded');
}
});
```
--------------------------------
### Create App-to-User Payment (Server API Key)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example illustrates how to create an App-to-User (A2U) payment using a POST request. It requires the Server API Key for authorization and includes payment details in the request body.
```http
POST /payments
```
--------------------------------
### Complete Payment (Server API Key)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example shows how to complete a payment server-side by providing the transaction ID (txid). This confirms that the payment has been successfully processed on the blockchain.
```http
POST /payments/{payment_id}/complete
```
--------------------------------
### Cancel Payment (Server API Key)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example shows how to cancel a payment using a POST request. This action marks the payment as cancelled in the system.
```http
POST /payments/{payment_id}/cancel
```
--------------------------------
### Verify Rewarded Ad Status (Server API Key)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/platform_API
This example shows how to verify the status of a rewarded ad using its unique ad ID. This is typically done after a user has viewed an ad via the client-side SDK.
```http
GET /ads_network/status/:adId
```
--------------------------------
### Set Home Domain for Pi Token Issuer Account (JavaScript)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/tokens
This JavaScript code snippet demonstrates how to set the 'Home Domain' for a Pi token issuer account using the Stellar SDK. It involves loading the account, building a transaction with the `setOptions` operation, signing it, and submitting it to the server. Ensure you have the Stellar SDK installed and configured.
```javascript
const issuerAccount = await server.loadAccount(issuerKeypair.publicKey());
const setOptionsTransaction = new StellarSDK.TransactionBuilder(issuerAccount, {
fee: baseFee,
networkPassphrase: NETWORK_PASSPHRASE,
timebounds: await server.fetchTimebounds(90),
})
.addOperation(StellarSDK.Operation.setOptions({ homeDomain: "example.com" })) // replace with your actual domain
.build();
setOptionsTransaction.sign(issuerKeypair);
await server.submitTransaction(setOptionsTransaction);
console.log("Home Domain is set successfully.");
```
--------------------------------
### Run Development Server
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
Starts the development server for the Rails application. This command is used to run the application locally during development and testing.
```shell
bin/dev
```
--------------------------------
### Add Pi SDK Next.js Dependency
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/NextJS
Installs the pi-sdk-nextjs package into your Next.js project using either Yarn or npm. This is the first step to integrating Pi Network functionalities.
```shell
yarn add pi-sdk-nextjs
# or
npm install pi-sdk-nextjs
```
--------------------------------
### React Component for Pi Payments
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/React
An example React component demonstrating how to use the `usePiConnection` and `usePiPurchase` hooks from the `pi-sdk-react` library. It handles user connection and initiates the Pi payment flow.
```tsx
"use client";
import React from 'react';
import { usePiConnection, usePiPurchase } from 'pi-sdk-react';
import { PaymentData } from 'pi-sdk-js';
const defaultPaymentData: PaymentData = {
amount: 0.01,
memo: 'Example Pi Payment',
metadata: { productId: 42, description: 'Demo purchase via Pi Network' }
};
export interface PiButtonProps {
paymentData?: PaymentData;
onConnected?: () => void;
children?: React.ReactNode;
}
export function PiButton({ paymentData = defaultPaymentData, onConnected, children }: PiButtonProps) {
const { connected } = usePiConnection();
const purchase = usePiPurchase(paymentData);
React.useEffect(() => {
if (connected && onConnected) onConnected();
}, [connected, onConnected]);
return (
);
}
```
--------------------------------
### Example Pi SDK Buy Button (Stimulus)
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
This ERB snippet demonstrates how to add a 'Buy' button to your Rails view using Stimulus. The button is linked to the `pinetwork` controller and is initially disabled until activated by the Pi SDK.
```erb
```
--------------------------------
### Add Pi SDK Rails Gem to Gemfile
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
This snippet shows how to add the pi-sdk-rails gem to your application's Gemfile. It specifies using a Git repository for the gem source. Ensure you run `bundle install` after adding this line.
```ruby
gem 'pi-sdk-rails', git: 'https://github.com/pi-apps/pi-sdk-rails.git'
```
--------------------------------
### Initialize Pi SDK
Source: https://pi-apps.github.io/pi-sdk-docs/platform/SDK_reference
Include these script tags to initialize the Pi Apps SDK on your web pages. The `Pi.init` function configures the SDK, with the `version` parameter being required for compatibility.
```html
```
--------------------------------
### Initialization
Source: https://pi-apps.github.io/pi-sdk-docs/platform/SDK_reference
Include these script tags to initialize the Pi Apps SDK. The `Pi.init` function accepts a configuration object with `version` (required) and `sandbox` (optional) keys.
```APIDOC
## Initialization
Add the following `script` tags to all pages where you need to call the Pi Apps SDK:
```html
```
### Parameters
#### Request Body
- **version** (string) - Required - This is required to ensure compatibility of your app with newer SDK versions.
- **sandbox** (boolean) - Optional - This enables you to configure the SDK to run in the sandbox.
### Using the SDK in sandbox mode:
```html
```
> Typically, if you’re using a framework or a boilerplate that supports it, you should be able to set up your sandbox flag to match your development environment. For example, most good Node boilerplates will set up the value of `process.env.NODE_ENV` to either `"development"` or `"production"`, and you could do something like: `Pi.init({ version: "2.0", sandbox: <%= process.env.NODE_ENV !== 'production' %> })`. This depends on your setup, but running the Pi SDK in sandbox mode will generally happen whenever your app is running in development.
```
--------------------------------
### Authenticate User with Pi SDK
Source: https://pi-apps.github.io/pi-sdk-docs/platform/authentication
Initiates the user authentication process using the Pi SDK. It requires `scopes` and an optional `onIncompletePaymentFound` callback. The function returns authentication results, including user information and an access token.
```javascript
const authRes = await window.Pi.authenticate(scopes, onIncompletePaymentFound);
```
--------------------------------
### pi.toml File Structure and Hosting
Source: https://pi-apps.github.io/pi-sdk-docs/platform/tokens
Details the required content and hosting requirements for the `pi.toml` file, which serves as metadata verification for your token.
```APIDOC
## Hosting pi.toml
### Description
After setting the home domain, you must host a `pi.toml` file at the `.well-known/pi.toml` path on your specified domain. This file contains essential metadata about your token, which Pi Server uses for verification and listing in the Pi Wallet. The file must be publicly accessible via HTTPS and served as plain text.
### Method
GET
### Endpoint
`https:///.well-known/pi.toml`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
(Accessing the file via a web browser or `curl`)
```bash
curl https:///.well-known/pi.toml
```
### Response
#### Success Response (200)
- **Content-Type**: `text/plain`
- **Body**: Plain text TOML format containing token metadata.
#### Response Example
```toml
[[CURRENCIES]]
code="TestToken"
issuer="GCNCQ6RRVEERQXWGKB3XMRK6VGJRIHGT5UTDAAU6QEU5NL2AHFOJDYLC"
name="Pi Core Team"
desc="This is a test token that is created as an example and has no value."
image="https://image-of-your-token.com/image.png"
```
### Required Fields in `pi.toml`
- **code** (string) - The code of the token.
- **issuer** (string) - The public key of the token issuer.
- **name** (string) - The name of the token issuer.
- **desc** (string) - A simple description of the token.
- **image** (string) - A URL to an image that contains the icon of the token.
### Important Notes
- The `pi.toml` file and the token image must be accessible via HTTPS.
- Ensure proper caching for both `pi.toml` and the token image to maintain listing status.
- If an issuer issues multiple tokens, each token must have its own `[[CURRENCIES]]` section.
- Failure to meet these requirements may result in delisting.
```
--------------------------------
### Initialize Pi SDK with Environment Variable
Source: https://pi-apps.github.io/pi-sdk-docs/platform/SDK_reference
Dynamically set the sandbox mode based on environment variables, commonly used in Node.js applications. This allows the SDK to run in sandbox mode during development and in production mode otherwise.
```html
Pi.init({ version: "2.0", sandbox: <%= process.env.NODE_ENV !== 'production' %> })
```
--------------------------------
### Backend Metadata Support API
Source: https://pi-apps.github.io/pi-sdk-docs/platform/pinet
PiNet sends GET requests to your backend endpoint to fetch metadata. The endpoint should respond with a `PiNetMetadataDTO` object.
```APIDOC
## GET /pinet/meta
### Description
This endpoint is called by PiNet to retrieve metadata for a given pathname. It is used in the backend metadata support flow.
### Method
GET
### Endpoint
`/pinet/meta?pathname=`
### Query Parameters
- **pathname** (string) - Required - The encoded pathname for which to retrieve metadata.
### Request Body
This endpoint does not have a request body.
### Response
#### Success Response (200)
- **title** (string) - Optional - The title of the page.
- **description** (string) - Optional - The description of the page.
- **authors** (object | array) - Optional - Information about the authors.
- **keywords** (string | array) - Optional - Keywords associated with the page.
- **creator** (string) - Optional - The creator of the content.
- **publisher** (string) - Optional - The publisher of the content.
- **formatDetection** (object) - Optional - Settings for format detection.
- **abstract** (string) - Optional - An abstract of the content.
- **archives** (string | array) - Optional - Archives related to the content.
- **category** (string) - Optional - The category of the content.
- **classification** (string) - Optional - The classification of the content.
- **openGraph** (object) - Optional - OpenGraph metadata.
- **twitter** (object) - Optional - Twitter Card metadata.
- **icons** (string | array | object) - Optional - Icons associated with the content.
#### Response Example
```json
{
"title": "Example Page Title",
"description": "This is an example description for the page.",
"keywords": ["example", "pi-net", "metadata"],
"openGraph": {
"title": "OpenGraph Title",
"description": "OpenGraph Description",
"type": "website",
"url": "https://example.com/page",
"image": "https://example.com/image.jpg"
},
"twitter": {
"card": "summary_large_image",
"title": "Twitter Card Title",
"description": "Twitter Card Description",
"image": "https://example.com/twitter-image.jpg"
}
}
```
### Error Handling
- **400 Bad Request**: If the request parameters are invalid.
- **500 Internal Server Error**: If there is an issue processing the request on the backend.
```
--------------------------------
### User Authentication Flow
Source: https://pi-apps.github.io/pi-sdk-docs/platform/authentication
This section details the steps involved in authenticating users for your application using Pi SDK and API.
```APIDOC
## Pi Authentication Flow
### Description
This guide outlines the process of authenticating users for your application using the Pi SDK and verifying their identity via the Pi API.
### Step 1: Call `authenticate()` of Pi SDK
#### Description
Use the Pi SDK's `authenticate()` method to obtain user information and an access token.
#### Method
JavaScript (Client-side)
#### Code Example
```javascript
const authRes = await window.Pi.authenticate(scopes, onIncompletePaymentFound);
```
### Step 2: Make a GET request to `/me` Pi API endpoint
#### Description
Verify the user data obtained in Step 1 by making a GET request to the `/me` Pi API endpoint. Include the access token in the `Authorization` header. A valid token will return a `UserDTO`, while an invalid token will result in a `401 Unauthorized` response.
#### Method
GET
#### Endpoint
`https://api.minepi.com/v2/me`
#### Parameters
##### Headers
- **Authorization** (string) - Required - The access token obtained from `Pi.authenticate()`, formatted as `Bearer [accessToken]`.
#### Request Example
```javascript
const accessToken = authRes.accessToken; // Assuming accessToken is part of authRes
const me = await axios.get('https://api.minepi.com/v2/me', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
```
#### Response
##### Success Response (200)
- **UserDTO** (object) - Contains the authenticated user's information.
##### Error Response (401)
- **Unauthorized** - Returned if the access token is invalid.
```
--------------------------------
### Request User-To-App Payment (JavaScript)
Source: https://pi-apps.github.io/pi-sdk-docs/Platform
This JavaScript snippet illustrates how to request a payment from the current user to your application's account using `Pi.createPayment`. It includes parameters for the amount, a memo for the user, and a metadata object for your internal use. Crucially, it defines callbacks for various payment stages like server approval, completion, cancellation, and errors.
```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) { /* ... */ },
});
```
--------------------------------
### Pi SDK Authentication
Source: https://pi-apps.github.io/pi-sdk-docs/Platform
Demonstrates how to authenticate a user using the Pi SDK, which is necessary before performing any user-related operations. It also explains the initial consent dialog presented to the user.
```APIDOC
## Pi SDK Authentication
You cannot perform any user-related operations (e.g read the user’s info, request a payment from them) until you have successfully authenticated the user. The first time, they will be presented with a dialog asking for their consent to share their data with your app.
### Pi SDK Authentication
JavaScript
```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);
});
```
```
--------------------------------
### Source API Key
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
Loads the PI_API_KEY from a secrets file into the current shell environment. This key is necessary for the Pi SDK to authenticate with the Pi network.
```shell
source ../secrets
```
--------------------------------
### Initialize Pi SDK in Sandbox Mode
Source: https://pi-apps.github.io/pi-sdk-docs/platform/SDK_reference
Configure the Pi Apps SDK to run in sandbox mode by setting the `sandbox` option to `true` during initialization. This is useful for testing your application in a simulated environment before deploying to production.
```html
```
--------------------------------
### Pi Token Metadata Configuration (TOML)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/tokens
This TOML configuration defines the metadata for a Pi token, including its code, issuer, name, description, and an image URL. This file, typically named `pi.toml`, must be hosted at the `.well-known/pi.toml` path on your specified home domain and served as plain text. Ensure all fields are accurate and the image is publicly accessible via HTTPS.
```toml
[[CURRENCIES]]
code="TestToken"
issuer="GCNCQ6RRVEERQXWGKB3XMRK6VGJRIHGT5UTDAAU6QEU5NL2AHFOJDYLC"
name="Pi Core Team"
desc="This is a test token that is created as an example and has no value."
image="https://image-of-your-token.com/image.png"
```
--------------------------------
### Run Database Migrations
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
Applies pending database migrations to create or update the database schema. This command is essential after generating new models or making changes to existing ones.
```shell
rake db:migrate
```
--------------------------------
### Database Integration with Custom Approve Handler (TypeScript)
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Demonstrates how to create a custom approve handler for database integration. This involves finding or creating a user and creating a transaction record before potentially calling the default Pi API handler. It requires the 'pi-sdk-express' package.
```typescript
import { approveHandler } from 'pi-sdk-express';
// Custom approve handler with database
async function customApproveHandler(req: Request, res: Response) {
const { accessToken, paymentId } = req.body;
// Find or create user
const user = await findOrCreateUser(accessToken);
// Create transaction record
const transaction = await Transaction.create({
paymentId,
userId: user.id,
state: 'approval_pending'
});
// Call default handler (or implement your own Pi API call)
// ... your implementation
}
```
--------------------------------
### Generate Root Controller and Index View
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Rails
Generates a root controller and its index action, which will serve as the main page for the application. This is often used to display the frontend integration point.
```shell
rails generate controller root index
```
--------------------------------
### Get Native Features List (TypeScript)
Source: https://pi-apps.github.io/pi-sdk-docs/platform/SDK_reference
Retrieves a list of native features supported by the user's current Pi Browser version. This is crucial for ensuring compatibility and proper functioning of certain SDK features.
```typescript
type NativeFeature = "inline_media" | "request_permission" | "ad_network";
Pi.nativeFeaturesList(): Promise>;
```
--------------------------------
### Create Payment
Source: https://pi-apps.github.io/pi-sdk-docs/platform/SDK_reference
Initiates the payment flow, allowing users to review and submit blockchain transactions.
```APIDOC
## POST /payments
### Description
Creates a new payment and initiates the payment flow. This will open an interface for the user to review and approve the transaction.
### Method
POST
### Endpoint
`/payments`
### Parameters
#### Request Body
- **paymentData** (object) - Required - Contains details of the payment.
- **amount** (number) - Required - The amount the user is requested to pay.
- **memo** (string) - Required - A memo for the payment, visible to the user.
- **metadata** (object) - Optional - Arbitrary data for internal use, linking to business logic.
- **callbacks** (object) - Required - Functions to handle different stages of the payment flow.
- **onReadyForServerApproval** (function) - Called when the paymentId is obtained from Pi Servers. Use for Server-Side Approval.
- **onReadyForServerCompletion** (function) - Called when the user submits the transaction to the Pi Blockchain. Use for Server-Side Completion.
- **onCancel** (function) - Called when the payment is cancelled by the user or due to other issues.
- **onError** (function) - Called when an error occurs during the payment process.
### Request Example
```json
{
"paymentData": {
"amount": 3.1415,
"memo": "Digital kitten #1234",
"metadata": {
"orderId": 1234,
"itemIds": [11, 42, 314]
}
},
"callbacks": {
"onReadyForServerApproval": "(paymentId) => console.log(paymentId)",
"onReadyForServerCompletion": "(paymentId, txid) => console.log(paymentId, txid)",
"onCancel": "(paymentId) => console.log(paymentId)",
"onError": "(error, payment) => console.error(error)"
}
}
```
### Response
#### Success Response (void)
This method returns void. Callbacks handle the response.
#### Error Handling
- **Concurrent Payments**: If an open payment exists, it may be cancelled or the new payment rejected. The `onError` callback will be invoked, and `onIncompletePaymentFound` (from `authenticate`) may be called.
```
--------------------------------
### Custom Route Mounting
Source: https://pi-apps.github.io/pi-sdk-docs/tmtt/Express
Demonstrates how to mount the Pi payment router at a custom base path other than the default '/pi_payment'.
```APIDOC
## Custom Route Mounting
### Description
This allows you to mount the Pi payment router at a different base path in your Express application, providing flexibility in structuring your API.
### Method
Applies to all Pi payment endpoints.
### Endpoint
Customizable base path (e.g., `/api/payments/pi`).
### Example
```javascript
import express from 'express';
import { createPiPaymentRouter } from 'pi-sdk-express';
const app = express();
// Mount Pi payment routes at a custom path
app.use('/api/payments/pi', createPiPaymentRouter());
app.listen(3000);
```
**Note:** If you change the mount path, you’ll need to configure the frontend SDK accordingly to match the new endpoint URLs.
```