A secure payment processing API with tour booking functionality, built on Hono framework with OpenAPI-driven development and deployed on Val Town.
- OpenAPI-First Development: Dynamic route generation and validation from OpenAPI specification
- Two-Step Nonce Security: Advanced payment security with time-limited nonces and bot protection
- Comprehensive Security: CSRF protection, rate limiting, Turnstile bot detection, and secure headers
- Tour Management: Complete tour listing, booking, and payment processing
- Admin Dashboard: Secure admin endpoints with token-based authentication
- Real-time Validation: Automatic request/response validation via Zod schemas
- Val Town Optimized: Designed for serverless deployment on Val Town platform
- Val Town Account: Required for deployment
- Cloudflare Turnstile: For bot protection (free tier available)
- ZenPay Account: For payment processing integration
Create a .env file with the following variables:
# Environment APP_ENV=dev # 'dev' or 'prod' LOG_LEVEL=info # 'debug', 'info', 'warn', 'error' # OpenAPI Configuration OPENAPI_LOCAL_PATH=./openapi.json # Local OpenAPI spec path OPENAPI_BLOB_KEY=openapi-spec # Val Town blob storage key OPENAPI_PUBLIC_URL=https://... # Public URL for OpenAPI spec # Authentication ZP_USERNAME=admin # Basic auth username ZP_PASSWORD=secure-password # Basic auth password MASTER_KEY=your-master-api-key # Bearer token for API access # Security TURNSTILE_SECRET_KEY=your-secret-key # Cloudflare Turnstile secret CORS_ORIGINS=https://yourdomain.com # Allowed CORS origins # Payment Integration ZENPAY_API_KEY=your-zenpay-key # ZenPay API key ZENPAY_WEBHOOK_SECRET=webhook-secret # ZenPay webhook secret
-
Clone the repository:
git clone https://github.com/yourusername/ZenServer.git cd ZenServer -
Configure environment:
cp src/.env.example src/.env # Edit src/.env with your configuration -
Deploy to Val Town:
- Upload the project to your Val Town val
- Set environment variables in Val Town dashboard
- The main entry point is
src/main.ts
For local development outside Val Town:
# Install Deno curl -fsSL https://deno.land/install.sh | sh # Run the server deno run --allow-all src/main.ts
curl -H "Authorization: Bearer YOUR_API_KEY" \ https://your-val-town-url.web.val.run/api/v1/admin/generate-pay-token
curl -u admin:password \ https://your-val-town-url.web.val.run/api/v1/admin/generate-pay-token
curl -X POST https://your-val-town-url.web.val.run/api/v1/create-nonce \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: your-csrf-token" \ -d '{ "tourId": "tour-paris-explorer", "cfToken": "turnstile-token-here", "email_verify": "🍯" }'
curl -X POST https://your-val-town-url.web.val.run/api/v1/payment/exchange-nonce \ -H "Content-Type: application/json" \ -H "X-Payment-Nonce: nonce-from-step-1" \ -d '{ "apiKey": "your-api-key", "mode": "production", "paymentAmount": 299.99, "merchantUniquePaymentId": "booking-123", "timestamp": "2024-01-01T12:00:00Z" }'
curl https://your-val-town-url.web.val.run/api/v1/tours
curl https://your-val-town-url.web.val.run/api/v1/tours/tour-paris-explorer
curl -X POST https://your-val-town-url.web.val.run/api/v1/create-booking \ -H "Content-Type: application/json" \ -d '{"tourId": "tour-paris-explorer"}'
- API Gateway (
src/gateway/apiGateway.ts): Main application orchestrator - OpenAPI Loader (
src/utils/openApiLoader.ts): Dynamic route generation - Handlers (
src/handlers/): Business logic for endpoints - Middleware (
src/middleware/): Security, CORS, rate limiting - Services (
src/services/): Authentication, validation, payment processing - Database (
src/database/): SQLite integration with Val Town
- Two-Step Nonce Gating: Prevents replay attacks and ensures human interaction
- CSRF Protection: Origin validation + token verification
- Rate Limiting: Configurable per-endpoint limits
- Bot Protection: Cloudflare Turnstile integration
- Secure Headers: Comprehensive security header middleware
- Input Validation: Automatic request/response validation
The application uses SQLite with the following main tables:
app_tp_booking_orders: Tour booking informationsys_pay_tokens: Shareable payment tokenssys_nonces: Security nonces for payment flowsys_infra_hook_backs: Webhook callback logs
src/
├── config/ # Environment configuration
├── data/ # Static data (tours, etc.)
├── database/ # Database schemas and services
├── gateway/ # Main application gateway
├── handlers/ # Route handlers
├── middleware/ # Security middleware
├── services/ # Business logic services
├── types/ # TypeScript type definitions
├── utils/ # Utility functions
└── main.ts # Application entry point
-
Update OpenAPI Spec (
openapi.json):{ "paths": { "/api/v1/your-endpoint": { "post": { "operationId": "yourEndpoint", "summary": "Your endpoint description", "requestBody": { ... }, "responses": { ... } } } } } -
Create Handler (
src/handlers/yourHandler.ts):export async function yourEndpoint(request: Request, db: Database): Promise<Response> { // Your implementation return new Response(JSON.stringify({ success: true }), { status: 200, headers: { "Content-Type": "application/json" } }); } -
Register Handler (
src/gateway/apiGateway.ts):const handlerMap = { // ... existing handlers yourEndpoint: yourHandler.yourEndpoint, };
# Test health endpoint curl https://your-val-town-url.web.val.run/api/v1/health # Test documentation curl https://your-val-town-url.web.val.run/api/v1/docs # Test OpenAPI spec curl https://your-val-town-url.web.val.run/api/v1/openapi.json
Use the Turnstile test page for bot protection testing:
curl https://your-val-town-url.web.val.run/api/v1/turnstile/test
Enable debug logging by setting:
LOG_LEVEL=debug
Debug correlation IDs are added to all requests for tracing. Check logs for:
correlationId: Unique request identifierendpoint: API endpoint being calledmethod: HTTP methodsecurity: Security validation results
- Upload Project: Copy all files to your Val Town val
- Set Environment Variables: Configure in Val Town dashboard
- Update OpenAPI Spec: Upload
openapi.jsonto Val Town blob storage - Configure Domains: Set up custom domain if needed
- All environment variables configured
- OpenAPI spec uploaded to blob storage
- CORS origins configured for production domains
- Turnstile keys configured for production
- Rate limits configured appropriately
- Database tables created
- Webhook endpoints configured in ZenPay
- SSL certificates configured
- Monitoring and logging configured
- Always use HTTPS in production
- Store API keys securely
- Implement proper error handling
- Validate all inputs
- Use rate limiting appropriately
- Never store sensitive payment data
- Use secure nonces for all payments
- Implement proper callback validation
- Log all payment attempts
- Monitor for suspicious activity
- Use parameterized queries
- Implement proper access controls
- Regular security audits
- Backup strategies
- Monitor database access
# Check blob storage curl https://your-val-town-url.web.val.run/api/v1/openapi.json # Check local file ls -la openapi.json
# Check CORS configuration curl -H "Origin: https://yourdomain.com" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: Content-Type" \ -X OPTIONS https://your-val-town-url.web.val.run/api/v1/tours
# Check rate limit headers curl -I https://your-val-town-url.web.val.run/api/v1/tours
# Check database connectivity curl https://your-val-town-url.web.val.run/api/v1/health
- 400: Bad Request - Invalid input data
- 401: Unauthorized - Authentication required
- 403: Forbidden - Bot detected or access denied
- 404: Not Found - Resource not found
- 429: Too Many Requests - Rate limit exceeded
- 500: Internal Server Error - Server error
- Fork the repository
- Create feature branch:
git checkout -b feature/amazing-feature - Make changes: Follow coding standards
- Test thoroughly: Ensure all tests pass
- Submit pull request: Include description and tests
- Use TypeScript for all new code
- Follow ESLint configuration
- Add JSDoc comments for functions
- Include error handling
- Write comprehensive tests
- Update documentation
- Never commit secrets or API keys
- Use environment variables for configuration
- Validate all inputs
- Follow secure coding practices
- Regular security reviews
This project is licensed under the MIT License - see the LICENSE file for details.
- Issues: Report bugs and request features
- Discussions: Ask questions and share ideas
- Wiki: Community-maintained documentation
For enterprise support, custom integrations, or consulting services, please contact the development team.
Built with ❤️ for secure payment processing on Val Town