zynpay 0.2.3
Accept crypto payments with ease. No API keys required!
License: MIT
Requires Python: >=3.8
Keywords: crypto, payments, blockchain, web3, usdc, ethereum, base, arc

# ZynPay Python SDK

> 🧪 **Currently Available on Testnet** | Mainnet deployment coming soon!

## Accept crypto payments in your Python app

Built for **merchants and businesses** who want to accept USDC payments. Your customers pay with their wallet—MetaMask, Coinbase Wallet, or any web3 wallet.

## Why businesses choose ZynPay

**What your customers get:**

- ✅ Pay with their existing wallet (MetaMask, Coinbase Wallet, etc.)
- ✅ See the exact amount before approving
- ✅ Their private keys never leave their wallet
- ✅ No sign-ups or extra accounts needed

**What you get as a merchant:**

- ✅ Get paid in USDC directly to your wallet
- ✅ Integrate in under 10 minutes
- ✅ Python backend + MetaMask frontend
- ✅ Zero backend infrastructure required
- ✅ Works on Base, Arc, Ethereum (testnet ready, mainnet soon)

## Installation

```bash
pip install zynpay
```

> **🧪 Testnet Ready**: Test with free tokens on Base Sepolia before going live!

## 🎯 Quick Start: Web App with MetaMask

The recommended way - customers pay with MetaMask (no private keys on your server!)

### Backend (FastAPI)

```python
from fastapi import FastAPI
from zynpay import ZynPayClient, Environment

app = FastAPI()

client = ZynPayClient(
    merchant_wallet="0xYourBusinessWallet",  # You receive payments here
    environment=Environment.TESTNET
)

@app.post("/api/payment/create")
async def create_payment(amount: float):
    payment = client.payments.create(amount=amount, chain="base")
    return {
        'payment_id': payment.id,
        'amount': payment.amount,
        'router_address': payment.router_address
    }
```

### Frontend (HTML + MetaMask)

```javascript
// Customer connects MetaMask
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = await provider.getSigner();

// Create payment on your backend
const response = await fetch("/api/payment/create", {
  method: "POST",
  body: JSON.stringify({ amount: 49.99 }),
});
const { payment_id, router_address } = await response.json();

// Customer approves and pays in MetaMask
// (No private keys exposed!)
```

> 💡 **Full example**: See `examples/web_app/` for complete FastAPI + MetaMask integration

## 🔐 Server-Side Payments (Advanced)

For **automation and backend-to-backend payments only**. Not for customer-facing payments!

```python
import os
from zynpay import ZynPayClient, Environment

client = ZynPayClient(
    merchant_wallet="0x1234567890123456789012345678901234567890",
    environment=Environment.TESTNET
)

# Create payment
payment = client.payments.create(amount=5.00, chain="base")

# Execute with environment variable ONLY
payer_key = os.getenv("PAYER_PRIVATE_KEY")  # NEVER hardcode!
if payer_key:
    tx_hash = client.payments.pay(payment, payer_key, wait_for_confirmation=True)
    print(f"✅ Payment confirmed! TX: {tx_hash}")
```

> ⚠️ **IMPORTANT**: For customer payments, use the MetaMask web app (see `examples/web_app/`). Only use private keys for server-side automation!

## Features

### Environment Management

```python
from zynpay import Environment

# Testnet (safe for development)
client = ZynPayClient(
    merchant_wallet="0x...",
    environment=Environment.TESTNET
)
print(client.is_testnet)  # True

# Mainnet (production)
client = ZynPayClient(
    merchant_wallet="0x...",
    environment=Environment.MAINNET
)
print(client.is_mainnet)  # True
```

### Check Balance

```python
# Check USDC and native balance
balance = client.web3.get_balance(
    wallet="0x...",
    chain="base"
)

print(f"USDC: {balance.usdc}")
print(f"Native: {balance.native}")
print(f"Has funds: {balance.has_usdc and balance.has_gas}")
```

### Estimate Gas

```python
# Estimate gas cost for payment
estimate = client.web3.estimate_gas(
    amount=5.00,
    chain="base"
)

print(f"Gas cost: ${estimate.total_cost_usd:.2f}")
```

### Testnet Helpers

```python
if client.is_testnet:
    # Get faucet URL
    faucet_url = client.testnet.get_faucet_url("base")
    print(f"Get testnet USDC: {faucet_url}")

    # Or use helper
    client.testnet.get_usdc(wallet="0x...", amount=10.0)
```

### Verify Payment

```python
# Verify payment on blockchain
verified = client.payments.verify(payment)

if verified:
    print("✅ Payment confirmed on blockchain!")
    print(f"Merchant received: {payment.amount * 0.90} USDC")
    print(f"Platform received: {payment.amount * 0.10} USDC")
```

## Supported Networks

### 🧪 Testnet (Currently Available - Free Tokens!)

- ✅ **Base Sepolia** (`chain="base"`) - **Recommended for testing**

  - Router: `0x29F81b4870c3b6806a36d2c07db24fDFC6EcB5FF` (3% fee, V2 with refunds)
  - Get free ETH & USDC: https://portal.cdp.coinbase.com/products/faucets

- ✅ **Arc Testnet** (`chain="arc"`) - **USDC is the gas token** 🔥

  - Router: `0x3309F63914954a1A35cc662E76a3805E86D37715`
  - Get free USDC: https://faucet.circle.com

- 🔜 **Ethereum Sepolia** (`chain="ethereum"`) - Coming soon

### 🚀 Mainnet (Coming Soon)

- 🔜 **Base Mainnet** (`chain="base"`) - Production deployment planned
- 🔜 **Ethereum Mainnet** (`chain="ethereum"`) - Production deployment planned

> **Note**: Mainnet contracts will be deployed and audited before production release. Follow [@zyntrialabs](https://github.com/Zyntria-Labs) for updates!

## Error Handling

```python
from zynpay import (
    ZynPayClient,
    InsufficientFundsException,
    PaymentFailedException
)

try:
    payment = client.payments.create(amount=5.00)
    # Note: For customer payments, use MetaMask integration
    # See examples/web_app/ for the recommended approach
except InsufficientFundsException as e:
    print(f"Not enough funds: {e.required} USDC required")
except PaymentFailedException as e:
    print(f"Payment failed: {e.reason}")
```

## 📚 Example Apps

### Payment Link Example (`examples/web_app/`)

Shows how to build a payment link page using the SDK:

```bash
cd examples/web_app
pip install -r requirements.txt
python app.py
# Open http://localhost:5000 and connect MetaMask!
```

**What it demonstrates:**

- Creating payment requests with the SDK
- MetaMask integration for customer payments
- Real-time balance checking
- Step-by-step payment flow
- No private keys on server!

### Dashboard Example (`examples/dashboard_app/`)

Shows how to build a merchant dashboard using `list_payments()`:

```bash
cd examples/dashboard_app
pip install -r requirements.txt
python app.py
# Open http://localhost:8080
```

**What it demonstrates:**

- Using `list_payments()` to fetch payment history
- Displaying payment statistics
- Building a payment history table
- Filtering by network

These are **reference implementations** showing merchants how to build these features using the ZynPay SDK.

## API Reference

### ZynPayClient

```python
client = ZynPayClient(
    merchant_wallet="0x...",           # Required: Your wallet address
    environment=Environment.TESTNET,   # TESTNET or MAINNET
    default_chain="base",              # Default blockchain
    require_confirmation=False,        # Confirm mainnet operations
    verbose=True,                      # Print info messages
    api_base_url=None                  # Optional: API URL for payment history (defaults to localhost:3000 or env var)
)
```

### Payments

#### `client.payments.create()`

```python
payment = client.payments.create(
    amount=5.00,                       # Amount in USDC
    chain="base",                      # Chain name
    metadata={"order_id": "123"}       # Optional metadata
)
```

#### `client.payments.pay()` (Server-side only)

For automation/backend use only. For customer payments, use MetaMask web app.

```python
import os
tx_hash = client.payments.pay(
    payment=payment,                   # Payment object
    payer_private_key=os.getenv("PAYER_PRIVATE_KEY"),  # From env only!
    wait_for_confirmation=True         # Wait for blockchain confirmation
)
```

#### `client.payments.verify()`

```python
verified = client.payments.verify(
    payment=payment,                   # Payment object
    tx_hash="0x..."                    # Optional: tx hash
)
```

#### `client.payments.list_payments()`

Fetch all on-chain payments for a merchant. This queries the blockchain directly using `getLogs` to retrieve all `PaymentSplit` events.

```python
# List all payments for the merchant wallet
payments = client.payments.list_payments()

# List payments for a specific merchant address
payments = client.payments.list_payments(
    merchant_address="0xMerchantAddress..."
)

# List payments with filters
payments = client.payments.list_payments(
    merchant_address="0xMerchantAddress...",
    network="base-sepolia",
    from_block="34000000",
    to_block="latest"
)

# Process payments
for payment in payments:
    amount = float(payment['amountTotal']) / 1e6  # Convert to USDC
    merchant_amount = float(payment['amountToMerchant']) / 1e6
    fee = float(payment['amountToPlatform']) / 1e6

    print(f"Payment: ${amount:.2f} USDC")
    print(f"  You receive: ${merchant_amount:.2f} USDC")
    print(f"  Platform fee: ${fee:.2f} USDC")
    print(f"  TX: {payment['txHash']}")
    print(f"  Payer: {payment['payer']}")
    if payment.get('metadata'):
        print(f"  Metadata: {payment['metadata']}")
```

**💡 Tip**: You can also view payments in the [Merchant Dashboard](https://api.zynpay.app/dashboard) by entering your wallet address!

**Note**: The `api_base_url` defaults to `http://localhost:3000` for local development. Set `ZYNPAY_API_URL` environment variable or pass `api_base_url` to the client constructor to use production API.

### Web3

#### `client.web3.get_balance()`

```python
balance = client.web3.get_balance(
    wallet="0x...",
    chain="base"
)
# Returns: Balance(usdc=10.0, native=0.5, chain="base")
```

#### `client.web3.estimate_gas()`

```python
estimate = client.web3.estimate_gas(
    amount=5.00,
    chain="base"
)
# Returns: GasEstimate(gas_limit=300000, total_cost_usd=0.02, ...)
```

### Testnet (only in testnet mode)

#### `client.testnet.get_faucet_url()`

```python
url = client.testnet.get_faucet_url("base")
# Returns: "https://portal.cdp.coinbase.com/products/faucets"
```

#### `client.testnet.get_usdc()`

```python
client.testnet.get_usdc(wallet="0x...", amount=10.0)
# Prints faucet URL and instructions
```

## Run Examples

### Web App with MetaMask (Recommended)

```bash
cd examples/web_app
pip install -r requirements.txt
python app.py
# Open http://localhost:5000 in browser with MetaMask
```

### Server-Side Example (Automation only)

```bash
# Set environment variable (NEVER hardcode!)
export PAYER_PRIVATE_KEY="0x..."

# Run example
python examples/basic_payment.py
```

> 💡 **For customer payments, always use the web app with MetaMask!**

## Development

### Install for Development

```bash
git clone https://github.com/zynpay/zynpay-python
cd zynpay-python
pip install -e ".[dev]"
```

### Run Tests

```bash
pytest tests/
```

## Why No API Keys?

Traditional payment platforms require API keys because they:

- Track transactions on their servers
- Manage user accounts
- Handle authentication

**ZynPay is different:**

- Works directly with blockchain (no servers needed)
- No accounts or authentication
- 3% fee enforced by smart contract
- Fully decentralized

**Result:** Simpler for merchants, more reliable, truly permissionless! 🚀

## Business Model

### For Merchants (You)

- ✅ **Free to use**: No monthly fees, no setup costs
- ✅ **Instant setup**: Just provide your wallet address
- ✅ **Receive 97%**: Automatic via smart contract
- ✅ **No chargebacks**: Payments are final

### For Platform (ZynPay)

- ✅ **Automatic income**: 3% from every payment
- ✅ **No tracking needed**: Smart contract handles it
- ✅ **Scales infinitely**: No servers to maintain
- ✅ **Truly decentralized**: Just the SDK + blockchain

## Contributing

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

## License

MIT License - see LICENSE file for details.

## Support

- **Documentation**: https://docs.zynpay.com
- **GitHub**: https://github.com/zynpay/zynpay-python
- **Issues**: https://github.com/zynpay/zynpay-python/issues

## Links

- **Website**: https://zynpay.com
- **TypeScript SDK**: https://github.com/zynpay/zynpay-typescript

---

**Made with ❤️ by the ZynPay team**

**No API keys. No servers. Just payments.** ⚡