Skip to content

Authorization

alxspiker edited this page Jul 31, 2025 · 4 revisions

Access Token (Bearer Token)

API calls requiring Pioneer-specific data use Access Tokens obtained via the Pi App Platform SDK's Pi.Authenticate function. Include the token in the Authorization header:

Authorization: Bearer <Pioneer's access token>

Example Code (Python/JavaScript):

const headers = { headers: { authorization: "Bearer " + { PioneerAccessToken } }};
axios.get("https://api.minepi.com/v2/me", headers);

πŸ”„ Hybrid App Authorization

Important: Pi Authentication only works within Pi Browser. For hybrid applications:

  • Always detect Pi Browser first before calling Pi.authenticate()
  • Show login options only in Pi Browser to avoid scary popups
  • Provide clear messaging for non-Pi Browser users about Pi Browser requirement
  • Use user-initiated authentication instead of auto-login on page load

Hybrid Authorization Example

// βœ… Hybrid authentication approach
async function handleLogin() {
  // 1. Check if we're in Pi Browser
  const isPiBrowser = await detectPiBrowser();
  
  if (!isPiBrowser) {
    // Show fallback message instead of authentication popup
    showPiBrowserRequired();
    return;
  }

  // 2. Only authenticate when in Pi Browser and user clicks login
  try {
    const auth = await Pi.authenticate(['payments'], onIncompletePaymentFound);
    
    // 3. Send access token to your backend for verification
    const response = await fetch('/api/verify-user', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${auth.accessToken}`
      },
      body: JSON.stringify({ uid: auth.user.uid })
    });
    
    if (response.ok) {
      console.log('User authenticated successfully');
      updateUIForLoggedInUser(auth);
    }
  } catch (error) {
    console.error('Authentication failed:', error);
  }
}

function showPiBrowserRequired() {
  document.getElementById('auth-section').innerHTML = `
    <div class="pi-browser-required">
      <h3>Login Available in Pi Browser</h3>
      <p>To access your Pi account, please open this app in Pi Browser:</p>
      <a href="https://pinet.com/YOUR_APP_LINK" class="pi-button">
        Open in Pi Browser
      </a>
    </div>
  `;
}

// ❌ Bad: Don't do this - causes popups in regular browsers
// Pi.authenticate(['payments'], callback); // Called on page load

Backend Token Verification (Unchanged)

The backend verification process remains the same regardless of whether your app is hybrid:

Obtaining an Access Token

The Pi.Authenticate function of the Pi SDK provides an AuthResults object:

AuthResults{
    accessToken: string,
    user: {
    uid: string 
    }
}

Security Note: Use the accessToken from the frontend only for verification with the /me API endpoint. Do not store it long-term for identifying the Pioneer, as it is dynamic.

Verifying the Access Token

  1. Pass to Backend: Send the accessToken from your frontend to your server.

  2. Call /me Endpoint: Make a request to the Pi API's /me endpoint using the following header format:

    Authorization: Bearer <Pioneer's access token>
    

    Example (Python with Axios):

    const PioneerAccessToken = accessToken_Obtained_from_App_Frontend;
    const header = { headers: { authorization: "Bearer " + PioneerAccessToken }};
    axios.get("https://api.minepi.com/v2/me", header);
  3. Handle Response:

    • Success (200): The /me endpoint returns a UserDTO object containing the verified uid:

      Object{
        user: {
          uid: string, 
          username: string 
        }
      }
    • Error (401): The Access Token is invalid.

Using the uid within your App

  • Create Unique Records: The verified uid from the /me endpoint can reliably create unique records in your app's database.
  • Personalized Experience: Use the uid to retrieve stored information like purchases or progress, enabling seamless login-free personalization.

Important: Use the verified uid from the /me endpoint, not the initial uid returned by Pi.Authenticate.

Server API Key (Authorization Key)

Certain API calls require authorization from your app's server-side for security reasons. To use a Server API Key:

  1. Obtain from the Developer Portal: Instructions for generating a Server API Key can be found in the appropriate section of the Developer Portal guide.

  2. Include in Authorization Header: Add the key to your API requests in the following format:

    Authorization: Key <Your App's Server API Key>
    

Example Code (Python: Payments Endpoint)

const postingURL = `https://api.minepi.com/v2/payments/${payment_id}`;
const headers = { headers: { authorization: `Key ${APIKEY}` } };
axios.get(postingURL, null, headers); 

Important Notes

  • Secure Storage: Protect your Server API Key. Store it securely on your server and never expose it in client-side code.
  • Refer to Developer Portal: The Developer Portal will provide the most up-to-date instructions for API Key management and usage within specific API endpoints.

Enhancements

  • Purpose: Add a sentence or two clarifying the types of actions that typically require a Server API Key (e.g., processing payments, accessing sensitive Pioneer data).
  • Link to Developer Portal: Provide a direct link to the relevant section of the Developer Portal for easy reference.

🧭 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