# Laravel 12 Crypto Payment Gateway API Starter

Production-oriented modular-monolith starter for a provider-backed crypto payment gateway.

## Included
- Merchant session authentication endpoints
- Sandbox/live API credentials with one-time secret display
- Canonical HMAC request authentication
- Idempotent invoice creation/list/retrieve/cancel
- Provider contract and TRON adapter placeholder
- Provider webhook ingestion and deduplication
- Atomic amount handling using `DECIMAL(65,0)` strings
- Balanced double-entry ledger service
- Ledger-derived balances
- Payout request with allowlist/2FA/operator approval flow
- Signed merchant IPN jobs and retry state
- MySQL 8.4 migrations, Redis queues, Horizon-compatible jobs
- Reconciliation command/job skeletons
- Feature tests for signature and ledger invariants

## Install into a fresh Laravel 12 project

```bash
composer create-project laravel/laravel gateway "^12.0"
cd gateway
composer require laravel/sanctum laravel/horizon pragmarx/google2fa-laravel
php artisan install:api
```

Copy this package's `app`, `routes`, `database`, `config`, `bootstrap`, and `tests` files into the project.

```bash
cp .env.example .env
php artisan key:generate
php artisan migrate
php artisan horizon
php artisan schedule:work
```

## Required environment variables

```env
APP_ENV=local
APP_KEY=
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crypto_gateway
DB_USERNAME=gateway
DB_PASSWORD=

QUEUE_CONNECTION=redis
CACHE_STORE=redis
REDIS_CLIENT=phpredis

GATEWAY_ENVIRONMENT=sandbox
GATEWAY_API_CLOCK_SKEW_SECONDS=300
GATEWAY_API_NONCE_TTL_SECONDS=600
GATEWAY_CHECKOUT_URL=http://localhost:3000/pay


WEBHOOK_MAX_ATTEMPTS=10
WEBHOOK_TIMEOUT_SECONDS=10
```

## Request signing

Headers:

```text
x-api-key: pk_test_xxxxx
x-api-timestamp: 1783940000
x-api-nonce: random-unique-value
x-api-signature: hex-hmac-sha256
```

Canonical string:

```text
METHOD\n
/path?sorted=query\n
TIMESTAMP\n
NONCE\n
SHA256_RAW_BODY
```

Signature:

```text
hash_hmac('sha256', canonical_string, decrypted_api_secret)
```

## Main API routes

- `POST /api/v1/auth/register`
- `POST /api/v1/auth/login`
- `POST /api/v1/auth/logout`
- `GET /api/v1/me`
- `GET|POST /api/v1/api-keys`
- `POST /api/v1/api-keys/{apiKey}/rotate`
- `DELETE /api/v1/api-keys/{apiKey}`
- `POST /api/v1/payments`
- `GET /api/v1/payments`
- `GET /api/v1/payments/{publicId}`
- `POST /api/v1/payments/{publicId}/cancel`
- `GET /api/v1/balances`
- `POST /api/v1/payouts`
- `GET /api/v1/payouts`
- `POST /api/v1/webhook-endpoints`

## Important production work still required

This starter intentionally does not contain private-key custody or live transfer signing. Before mainnet:
- integrate KMS/envelope encryption rather than relying only on `APP_KEY`;
- add KYB/AML/risk provider integration;
- configure WAF, mTLS/provider IP rules where supported;
- implement operator roles and approval quorum;
- implement wallet sweeping and custody-provider controls;
- run reconciliation and failure-injection tests;
- obtain jurisdiction-specific legal approval.

## Public API contract update

The package now implements API version `2026-07-01`, request IDs, standardized success/error envelopes, decimal public amounts, currency-code lookup, persisted payment quotes, payment filters, estimate/currencies endpoints, synthetic webhook tests, payout `202` responses, SSRF-aware URL validation, scope middleware, and an explicit payment state machine. See `docs/PUBLIC_API_SPEC.md`.

## USDT-TRC20 detection and queues


The adapter intentionally does not generate addresses or broadcast transfers. Connect those methods to a provider-managed custody API or isolated signing environment before production use.

## Operations hardening update

The package now includes exact merchant-webhook retry timing and immutable per-attempt records, Redis locks for payment finalization and payout broadcast, payout address allowlists with cooling periods, manual operator approvals, hierarchical payout kill switches, daily balance snapshots, operations alerts, and the specified scheduler cadence. See `docs/RETRIES_WEBHOOKS_PAYOUTS.md`.

## Security, testing, and operations completion

The latest revision adds:

- tenant-owned model scopes and authorization policy scaffolding;
- dashboard email/account-state enforcement middleware;
- TOTP setup, enablement, and recent payout step-up verification;
- per-key endpoint-group throttles and account-aware login throttling;
- a KMS/envelope-encryption contract that fails closed in production when only local encryption is configured;
- recursive structured-log redaction for credentials, passwords, TOTP values, tokens, seed/private-key fields and sensitive headers;
- MySQL 8.4 append-only triggers for ledger records;
- reconciliation exception, provider-health, audit-chain and endpoint-health schema;
- readiness checks for MySQL 8.4 and Redis;
- Docker Compose services for PHP-FPM, Nginx, Horizon, scheduler, MySQL 8.4 and Redis;
- CI gates for Pint, Larastan, tests, Composer audit, Gitleaks, Semgrep and Trivy;
- property/concurrency/security test scaffolding and the complete mandatory scenario matrix;
- OpenAPI starter and launch/security runbooks.

This remains a source package rather than a generated full Laravel skeleton. Copy these files into a fresh Laravel 12 application, install Composer dependencies, register providers from `bootstrap/providers.php`, run migrations, and complete provider-specific integration fixtures before mainnet.


## Provider policy


MySQL uses `DECIMAL(65,0)` because MySQL supports at most 65 digits of precision. This is sufficient for the enabled USDT-TRC20 atomic amounts.



## Blockchain provider status

No concrete third-party blockchain API is implemented. The generic `BlockchainGateway` contract remains, and the default adapter fails closed until a reviewed provider or private-node adapter is configured. Provider webhook, project-coin synchronization, provider address collection, and provider-specific endpoints have been removed.


## P0 implementation
This repository now includes a complete Laravel application skeleton, MySQL runtime configuration, factories/test bootstrap, decimal-safe money conversion, verified/active merchant enforcement, TOTP step-up, AWS KMS envelope encryption, a self-hosted TRON node plus isolated signer adapter, manual fail-closed risk review, and a transactional outbox. Run `composer install`, copy `.env.example`, then `scripts/verify-mysql.sh`. Provider integration requires your own TRON FullNode and isolated signing service.
