# AgenticlyPay

A Python library and API service for processing agentic payments (ACP, AP2, x402) via Stripe. Built for agentic developers who need automated payment processing, monthly payouts, and tax compliance.

## Features

- **Multi-Protocol Support**: Process payments using ACP (Agentic Commerce Protocol), AP2 (Agent Payments Protocol), or x402 protocols
- **Square Payout Integration**: Seamless onboarding for developer payout profiles backed by Square
- **Automated Square Payouts**: Monthly automated payouts sent through Square to the verified bank account tied to your Square location
- **Tax Compliance**: Automatic 1099 form generation and filing
- **Transparent Pricing**: 6.5% + $0.30 per transaction
- **Flexible Authentication**: Use email addresses or API tokens for secure authentication
- **RESTful API**: Complete API for integration into any application
- **Web Dashboard**: Frontend website with detailed integration instructions and token management

## Requirements to Use AgenticlyPay

1. Use or register a Square business account: https://app.squareup.com/signup/
2. Use the AgenticlyPay package with the same email address used in Square.
3. Check usage on https://agenticlypay.com/console

## Quick Start

### Developer Console

Manage your account and view usage at the [Developer Console](https://agenticlypay.com/console):
- Sign in with Google, GitHub, or email
- View usage statistics by email
- Create and manage API tokens for secure authentication
- Review Square payout profile status

### Installation

```bash
pip install -r requirements.txt
```

### Configuration

Create a `.env` file with your Stripe credentials:

```env
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...
PLATFORM_FEE_PERCENTAGE=0.065
PLATFORM_FEE_FIXED=30
FRONTEND_URL=http://localhost:3000
SQUARE_APPLICATION_ID=sq0idp-xxxxxxxxxxxxxxxxxxxxxx
SQUARE_ACCESS_TOKEN=EAAAXXXXXXXXXXXXXXXXXXXXXXXXX
SQUARE_LOCATION_ID=XXXXXXXXXXXX
SQUARE_ENVIRONMENT=production
SQUARE_WEBHOOK_SIGNATURE_KEY=XXXXXXXXXXXXXXXXXXXXXXXX
```

### Running the Backend API

```bash
uvicorn agenticlypay.api.main:app --host 0.0.0.0 --port 8000
```

### Running the Frontend

```bash
cd frontend
npm install
npm run dev
```

### Docker Compose

```bash
docker-compose up
```

## API Documentation

### Base URL

- Production: `https://api.agenticlypay.com`
- Local (development): `http://localhost:8000`

### Endpoints

#### Connect (Account Management)

- `POST /api/v1/connect/accounts` - Create a developer account
- `GET /api/v1/connect/accounts/{account_id}` - Get account status
- `POST /api/v1/connect/onboarding` - Create onboarding link
- `POST /api/v1/connect/payout-schedule` - Configure payout schedule (Express)
- `PUT /api/v1/connect/metadata` - Update account metadata
- `POST /api/v1/connect/tax-info` - Collect tax information

#### Payments

- `POST /api/v1/payments/process` - Process a payment (ACP/AP2/x402)
- `POST /api/v1/payments/confirm` - Confirm a payment
- `GET /api/v1/payments/status/{protocol}/{payment_id}` - Get payment status
- `GET /api/v1/payments/fee/{amount}` - Calculate platform fee

#### Payouts

- `GET /api/v1/payouts/earnings/{account_id}/{year}/{month}` - Get monthly earnings
- `POST /api/v1/payouts/create` - Create a monthly payout
- `POST /api/v1/payouts/process-all` - Process payouts for all developers
- `GET /api/v1/payouts/history/{account_id}` - Get payout history
- `POST /api/v1/payouts/transfer` - Manual transfer to a connected account

#### Tax Reporting

- `GET /api/v1/tax/earnings/{account_id}/{year}` - Get annual earnings
- `POST /api/v1/tax/1099/generate` - Generate 1099 form
- `POST /api/v1/tax/1099/generate-all` - Generate 1099 forms for all developers
- `GET /api/v1/tax/forms/{account_id}` - Get tax forms

#### Webhooks

- `POST /api/v1/webhooks/stripe` - Stripe webhook handler

## Integration Examples
Below are minimal request/response examples for key endpoints.

### ACP Payment

```python
from agenticlypay import PaymentProcessor

processor = PaymentProcessor()

# Unified flow (AUTO): add mandate for AP2, resource_url for x402
result = processor.process_payment(
    protocol="AUTO",
    amount=10000,  # $100.00 in cents
    currency="usd",
    developer_account_id="acct_xxxxx",
    description="Payment for service",
    # mandate={...},         # uncomment to select AP2
    # resource_url="/...",  # uncomment to select x402
)
```

REST request:
```bash
curl -X POST https://api.agenticlypay.com/api/v1/payments/process \
  -H "Content-Type: application/json" \
  -d '{
    "protocol": "ACP",
    "amount": 10000,
    "currency": "usd",
    "developer_account_id": "acct_xxxxx",
    "description": "Payment for service"
  }'
```
Response (abridged):
```json
{
  "success": true,
  "payment": {
    "checkout_id": "pi_...",
    "client_secret": "pi_..._secret_...",
    "amount": 10000,
    "currency": "usd",
    "fee": 965,
    "net_amount": 9035,
    "status": "requires_payment_method"
  }
}
```

### AP2 Payment

```python
result = processor.process_payment(
    protocol="AP2",
    amount=10000,
    currency="usd",
    developer_account_id="acct_xxxxx",
    mandate={
        "agent_id": "agent_123",
        "user_id": "user_456",
        "permissions": ["create_payment", "complete_purchase"],
        "expires_at": 1735689600,
        "mandate_id": "mandate_789"
    }
)
```

### x402 Payment

```python
result = processor.process_payment(
    protocol="x402",
    amount=10000,
    currency="usd",
    developer_account_id="acct_xxxxx",
    resource_url="/api/data/endpoint"
)
```

### Configure payout schedule (Express)
```bash
curl -X POST https://api.agenticlypay.com/api/v1/connect/payout-schedule \
  -H "Content-Type: application/json" \
  -d '{
    "account_id": "acct_xxxxx",
    "interval": "monthly",
    "monthly_anchor": 1
  }'
```
Response (abridged):
```json
{
  "success": true,
  "account_id": "acct_xxxxx",
  "payout_schedule": {
    "interval": "monthly",
    "monthly_anchor": 1
  }
}
```

### Manual transfer to a connected account
```bash
curl -X POST https://api.agenticlypay.com/api/v1/payouts/transfer \
  -H "Content-Type: application/json" \
  -d '{
    "developer_account_id": "acct_xxxxx",
    "amount": 8500,
    "currency": "usd",
    "reference": "Monthly payout"
  }'
```
Response (abridged):
```json
{
  "success": true,
  "transfer_id": "tr_...",
  "amount": 8500,
  "currency": "usd",
  "destination": "acct_xxxxx",
  "status": "paid"
}
```

## Deployment to Google Cloud Run

### Prerequisites

1. Google Cloud SDK installed
2. Docker installed
3. GCP project created

### Deploy

```bash
export PROJECT_ID=your-gcp-project-id
export REGION=us-central1

# Create secrets in GCP Secret Manager
gcloud secrets create stripe-secret-key --data-file=- <<< "sk_live_..."
gcloud secrets create stripe-webhook-secret --data-file=- <<< "whsec_..."

# Run deployment script
./scripts/deploy.sh
```

## Project Structure

```
agenticlypay-com/
├── agenticlypay/          # Python package
│   ├── api/              # FastAPI application
│   ├── protocols/        # Payment protocol handlers
│   ├── connect.py        # Developer payout account management
│   ├── payments.py       # Payment processing
│   ├── payouts.py        # Payout management
│   └── tax.py            # Tax reporting
├── frontend/              # Next.js frontend
│   ├── src/
│   │   ├── app/          # Next.js app directory
│   │   ├── components/   # React components
│   │   └── lib/          # Utilities
│   └── Dockerfile
├── Dockerfile.backend    # Backend container
├── docker-compose.yml    # Local development
├── cloud-run-*.yaml      # Cloud Run configs
└── scripts/              # Deployment scripts
```

## Development

### Backend

```bash
# Install dependencies
pip install -r requirements.txt

# Run development server
uvicorn agenticlypay.api.main:app --reload
```

### Frontend

```bash
cd frontend
npm install
npm run dev
```

### Testing

```bash
# Backend tests (when implemented)
pytest

# Frontend tests (when implemented)
cd frontend
npm test
```

## License

All rights reserved. AgenticlyPay is closed-source software; please contact dan@danbroz.com for commercial usage terms.

## Support

For integration help, visit https://agenticlypay.com or email dan@danbroz.com.

