npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jpmvtv/a2u-payments

v1.3.0

Published

Portable A2U payment system for Pi Network integration in Next.js apps

Readme

@jpmvtv/a2u-payments

Portable A2U (App-to-User) payment system for Pi Network integration in Next.js applications

npm version License: MIT

✨ Features

  • Smart Setup Wizard - Auto-detects your schema, prevents breaking auth
  • UID-based payments - No wallet address requests needed
  • Framework-agnostic - Works with Next.js 14, 15, 16+
  • React Components - Pre-built payment buttons and hooks
  • Type-safe - Full TypeScript support
  • Secure - Input validation, error handling, audit logging
  • Flexible RLS support - Multi-tenant with any column naming convention
  • Database migrations - PostgreSQL with 4 isolation strategies
  • Copy-paste API routes - Ready to use endpoints
  • Production-ready - Error handling, retry logic, logging

🆕 Smart Setup Wizard

No more breaking your existing auth! The wizard:

  1. 🔍 Scans your database to detect your Pi UID column naming
  2. ❓ Confirms with you before making any changes
  3. 📝 Generates custom migrations for your specific schema
  4. ⚙️ Creates configuration files for your setup

Perfect for: myPiAtlas, existing projects, custom schemas, or any production app where you can't afford to break things.

🚀 Quick Start

npm install @jpmvtv/a2u-payments
npm run setup:a2u-payments  # 🧙‍♂️ Interactive wizard prevents breaking your auth!

Understanding Pi UID

The recipientUid prop requires the Pi Network UID of the payment recipient. This is NOT a database column name - it's the actual Pi Network user identifier that you get from your authentication system or user profile.

Where to get the Pi UID:

  • From your authenticated user context: user.piUid
  • From your user database table: user.pi_uid column
  • From Pi Network API response: user.uid

Basic Usage

import { A2UPaymentButton } from '@jpmvtv/a2u-payments/react';
import { useAuth } from '@/lib/auth'; // Your auth system

function PaymentComponent() {
  const { user } = useAuth(); // Get authenticated user
  
  return (
    <A2UPaymentButton
      recipientUid={user.piUid} // Use actual Pi Network UID from user
      amount={3.14}
      memo="Reward payment"
      transactionType="customer_reward"
      onSuccess={(payment) => console.log('Sent!', payment.txid)}
    />
  );
}

## 🔑 Getting User Pi UID

The most common confusion is where to get the `recipientUid` value. Here's how it works:

### Data Flow

Your Auth System → User Profile → Pi Network UID → Payment Component


### Common Patterns

#### Pattern 1: From Auth Context
```typescript
const { user } = useAuth(); // user.piUid contains the Pi Network UID

Pattern 2: From Database

// Your users table typically has a pi_uid column
const user = await db.users.findOne({ where: { id: userId } });
// user.pi_uid is the Pi Network UID

Pattern 3: From API Response

const response = await fetch('/api/user/profile');
const userData = await response.json();
// userData.piUid is the Pi Network UID

Important Notes

  • Component prop: recipientUid (React component interface)
  • Database column: uid (in a2u_payments table)
  • Your user table: pi_uid or piUid (your user management)
  • Source: Your authentication system or user profile database

📋 Prerequisites

  • Node.js 18+
  • Next.js 14+ (or 15, 16)
  • PostgreSQL database
  • Pi Network API credentials
  • React 18+

📖 Documentation

🎯 Use Cases

Perfect for:

  • Customer rewards - Loyalty programs, cashback, bonuses
  • Staff payments - Salaries, commissions, tips
  • Affiliate payouts - Commission distributions
  • Refunds - Customer returns and exchanges
  • Platform payments - Operational and merchant payouts

🛠️ Installation

npm install @jpmvtv/a2u-payments

Quick Setup (5 minutes)

  1. Configure environment variables:

    PI_API_KEY=your_api_key_here
    PI_WALLET_PRIVATE_KEY=your_wallet_private_key_here
    PI_API_URL=https://api.minepi.com/v2
    DATABASE_URL=your_postgresql_connection_string
  2. Run database migrations:

    cp node_modules/@jpmvtv/a2u-payments/src/db/migrations/*.sql your_database/migrations/
    npm run db:migrate
  3. Add API route:

    mkdir -p src/app/api/a2u-payments
    cp node_modules/@jpmvtv/a2u-payments/src/api/a2u-payments/route.ts src/app/api/a2u-payments/route.ts
  4. Use in components:

    import { A2UPaymentButton } from '@jpmvtv/a2u-payments/react';
       
    <A2UPaymentButton
      recipientUid="user-uid"
      amount={3.14}
      memo="Payment"
      transactionType="customer_reward"
      onSuccess={(payment) => alert(`Sent: ${payment.txid}`)}
    />

📦 Package Contents

@jpmvtv/a2u-payments/
├── dist/                          # Compiled TypeScript
├── src/
│   ├── api/
│   │   └── a2u-payments/route.ts # API endpoint
│   ├── core/
│   │   ├── a2u-payment.ts        # Core payment logic
│   │   ├── payment-tracker.ts     # Payment tracking
│   │   └── payment-validator.ts   # Input validation
│   ├── db/
│   │   ├── connection.ts          # Database connection
│   │   ├── queries.ts             # SQL queries
│   │   └── migrations/            # Database schemas
│   ├── react/
│   │   ├── components/
│   │   │   └── A2UPaymentButton.tsx
│   │   └── hooks/
│   │       ├── useA2UPayment.ts
│   │       └── usePaymentHistory.ts
│   └── utils/                     # Utilities
└── docs/                          # Full documentation

🎨 Components

A2UPaymentButton

Pre-built payment button with loading states and error handling.

<A2UPaymentButton
  recipientUid="user-pi-uid"
  amount={3.14}
  memo="Reward payment"
  transactionType="customer_reward"
  onSuccess={(payment) => console.log('Sent!', payment)}
  onError={(error) => console.error('Failed:', error)}
  loadingText="Processing..."
  buttonText="Send Reward"
  className="custom-button"
/>

🪝 Hooks

useA2UPayment

Hook for sending A2U payments with full control.

const { sendPayment, isLoading, error } = useA2UPayment();

const result = await sendPayment({
  uid: 'user-pi-uid',
  amount: 3.14,
  memo: 'Reward',
  transaction_type: 'customer_reward'
});

usePaymentHistory

Hook for retrieving payment history.

const { payments, isLoading, error, refreshHistory } = usePaymentHistory('user-pi-uid');

🔧 Transaction Types

  • customer_reward - Customer rewards and cashback
  • customer_refund - Refunds for returns
  • staff_payout - Staff salary and commissions
  • affiliate_payout - Affiliate commissions
  • merchant_payout - Platform payouts to merchants
  • platform_payout - Platform operational payments

🗄️ Database Schema

The package uses PostgreSQL with two main tables:

  • a2u_payments - Payment records with full audit trail
  • payment_logs - Detailed transaction logs

Flexible Multi-Tenancy Support

RLS Strategies Available:

  1. User-based isolation - Isolate by user_uid, piUid, user_id, etc.
  2. Tenant-based isolation - Isolate by tenant_id (SaaS apps)
  3. Organization-based - Isolate by organization_id or team_id
  4. Combined isolation - Both tenant + user (advanced scenarios)

Any Column Naming Convention: Customize column names to match your existing user table schema (pi_uid, piUid, user_id, etc.)

Setup: Choose your strategy in 003_enable_rls.sql and uncomment the relevant section. Supports both RLS (multi-tenant) and non-RLS (single-tenant) environments.

See Installation Guide for detailed RLS configuration.

🔒 Security

  • Input validation and sanitization
  • Secure database operations with parameterized queries
  • Audit logging for all transactions
  • Error handling without sensitive data exposure
  • Environment-based configuration

🐛 Troubleshooting

Common Issues

"pi-backend not found"

npm install pi-backend

"Database connection failed"

  • Check DATABASE_URL or A2U_PAYMENTS_DB_URL
  • Verify PostgreSQL server is running
  • Ensure database user has proper permissions

"Pi Network credentials not configured"

  • Verify PI_API_KEY and PI_WALLET_PRIVATE_KEY are set
  • Check credentials are valid on Pi Network dashboard

For detailed troubleshooting, see INSTALL.md.

📄 License

MIT © JP Veneracion

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📞 Support

🙏 Acknowledgments

Built for the Pi Network ecosystem to enable seamless A2U payment integration.


Made with ❤️ for the Pi Network community