diff --git a/.claude/.gitignore b/.claude/.gitignore deleted file mode 100644 index 56a6038..0000000 --- a/.claude/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -# Local settings (personal, not shared) -settings.local.json - -# Local agent memory (personal, not shared) -agent-memory-local/ diff --git a/.claude/agents/.gitkeep b/.claude/agents/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/.claude/commands/.gitkeep b/.claude/commands/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/.claude/hooks/.gitkeep b/.claude/hooks/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/.claude/output-styles/.gitkeep b/.claude/output-styles/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/.claude/rules/.gitkeep b/.claude/rules/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/.claude/settings.json b/.claude/settings.json deleted file mode 100644 index 5fc89c2..0000000 --- a/.claude/settings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "hooks" : { - "SessionStart" : [ - { - "hooks" : [ - { - "command" : "$CLAUDE_PROJECT_DIR/.agents/polyfills/agentsmd/claude.sh", - "type" : "command" - } - ], - "matcher" : "startup" - } - ] - } -} diff --git a/.claude/settings.json.backup.1771570091 b/.claude/settings.json.backup.1771570091 deleted file mode 100644 index 0967ef4..0000000 --- a/.claude/settings.json.backup.1771570091 +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/.claude/skills b/.claude/skills deleted file mode 120000 index 2b7a412..0000000 --- a/.claude/skills +++ /dev/null @@ -1 +0,0 @@ -../.agents/skills \ No newline at end of file diff --git a/.cursor/hooks.json b/.cursor/hooks.json deleted file mode 100644 index aefb4d3..0000000 --- a/.cursor/hooks.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "version": 1, - "hooks": { - "sessionStart": [ - { - "command": "$CURSOR_PROJECT_DIR/.agents/polyfills/agentsmd/cursor.sh" - } - ] - } -} diff --git a/.cursor/skills b/.cursor/skills deleted file mode 120000 index 2b7a412..0000000 --- a/.cursor/skills +++ /dev/null @@ -1 +0,0 @@ -../.agents/skills \ No newline at end of file diff --git a/.cursorignore b/.cursorignore deleted file mode 100644 index 9f98c28..0000000 --- a/.cursorignore +++ /dev/null @@ -1,174 +0,0 @@ -# Distribution and Environment -dist/* -build/* -venv/* -env/* -*.env -.env.* -virtualenv/* -.python-version -.ruby-version -.node-version - -# Logs and Temporary Files -*.log -*.tsv -*.csv -*.txt -tmp/* -temp/* -.tmp/* -*.temp -*.cache -.cache/* -logs/* - -# Sensitive Data -*.sqlite -*.sqlite3 -*.dbsql -secrets.* -.npmrc -.yarnrc -.aws/* -.config/* - -# Credentials and Keys -*.pem -*.ppk -*.key -*.pub -*.p12 -*.pfx -*.htpasswd -*.keystore -*.jks -*.truststore -*.cer -id_rsa* -known_hosts -authorized_keys -.ssh/* -.gnupg/* -.pgpass - -# Config Files -*.conf -*.toml -*.ini -.env.local -.env.development -.env.test -.env.production -config/* - -# Database Files -*.sql -*.db -*.dmp -*.dump -*.backup -*.restore -*.mdb -*.accdb -*.realm* - -# Backup and Archive Files -*.bak -*.backup -*.swp -*.swo -*.swn -*~ -*.old -*.orig -*.archive -*.gz -*.zip -*.tar -*.rar -*.7z - -# Compiled and Binary Files -*.pyc -*.pyo -**/__pycache__/** -*.class -*.jar -*.war -*.ear -*.dll -*.exe -*.so -*.dylib -*.bin -*.obj - -# IDE and Editor Files -.idea/* -*.iml -.vscode/* -.project -.classpath -.settings/* -*.sublime-* -.atom/* -.eclipse/* -*.code-workspace -.history/* - -# Build and Dependency Directories -node_modules/* -bower_components/* -vendor/* -packages/* -jspm_packages/* -.gradle/* -target/* -out/* - -# Testing and Coverage Files -coverage/* -.coverage -htmlcov/* -.pytest_cache/* -.tox/* -junit.xml -test-results/* - -# Mobile Development -*.apk -*.aab -*.ipa -*.xcarchive -*.provisionprofile -google-services.json -GoogleService-Info.plist - -# Certificate and Security Files -*.crt -*.csr -*.ovpn -*.p7b -*.p7s -*.pfx -*.spc -*.stl -*.pem.crt -ssl/* - -# Container and Infrastructure -*.tfstate -*.tfstate.backup -.terraform/* -.vagrant/* -docker-compose.override.yml -kubernetes/* - -# Design and Media Files (often large and binary) -*.psd -*.ai -*.sketch -*.fig -*.xd -assets/raw/* diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index bec33a0..0000000 --- a/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -.git -.dockerignore -.tools \ No newline at end of file diff --git a/.gemini/settings.json b/.gemini/settings.json deleted file mode 100644 index 5e535b2..0000000 --- a/.gemini/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "context": { - "fileName": ["AGENTS.md", "GEMINI.md"] - } -} diff --git a/.gemini/skills b/.gemini/skills deleted file mode 120000 index 2b7a412..0000000 --- a/.gemini/skills +++ /dev/null @@ -1 +0,0 @@ -../.agents/skills \ No newline at end of file diff --git a/.gitignore b/.gitignore index b4fe17b..b2abef3 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,6 @@ razorpay-cli # Generated RPC files (generated from proto source files via buf) /rpc + +# macOS +.DS_Store diff --git a/.makerc b/.makerc deleted file mode 100644 index f3ef51a..0000000 --- a/.makerc +++ /dev/null @@ -1,4 +0,0 @@ -# Make configuration to suppress override warnings -export MAKEFLAGS="--no-print-directory" -export MAKEFLAGS += --no-builtin-rules -export MAKEFLAGS += --warn-undefined-variables diff --git a/.semgrepignore b/.semgrepignore deleted file mode 100644 index b60d878..0000000 --- a/.semgrepignore +++ /dev/null @@ -1,5 +0,0 @@ -.gitignore -.semgrepignore -pkg/registry/ -cmd/loadgen/ -cmd/loadgen/go.mod \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index af84fa6..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,64 +0,0 @@ -# go-foundation-v2 — Agent Instructions - -Production-ready Go microservice template using the Razorpay Foundation framework (gRPC + HTTP, PostgreSQL, buf/proto). Module: `github.com/razorpay/go-foundation-v2`. - -## Skills Index - -Load these skills **before** working on any matching task: - -| Skill | Trigger | -|-------|---------| -| `.agents/skills/repo-skill/core/architecture.md` | Adding/modifying layers, wiring dependencies, server startup | -| `.agents/skills/repo-skill/core/foundation-framework.md` | Foundation server config, Container, telemetry, DB collection | -| `.agents/skills/repo-skill/core/proto-grpc-workflow.md` | Proto files, buf commands, gRPC/HTTP handler registration | -| `.agents/skills/repo-skill/core/error-handling.md` | Creating errors, error codes, gRPC status mapping, WrapError | -| `.agents/skills/repo-skill/core/build-system.md` | Makefile targets, service rename, Docker, CI | -| `.agents/skills/repo-skill/modules/domain/model-patterns.md` | Domain models, spine.SoftDeletableModel, ToProto/FromProto | -| `.agents/skills/repo-skill/modules/technical/database-patterns.md` | spine.Repo, GORM, Create/Get, primary/replica DB | -| `.agents/skills/repo-skill/modules/technical/config-management.md` | Custom config structs, TOML layout, mapstructure tags | -| `.agents/skills/repo-skill/modules/technical/testing-patterns.md` | Unit tests, mock injection, testify patterns | -| `.agents/skills/code-security/SKILL.md` | Writing or reviewing any code | -| `.agents/skills/go-code-reviewer/SKILL.md` | Go code review requests | -| `.agents/skills/log-volume-optimizer/SKILL.md` | Log optimization | -| `.agents/skills/tech-spec-reviewer/SKILL.md` | Tech spec review | -| `.agents/skills/devstack/SKILL.md` | Deploying to devstack | - -## Critical Rules - -1. **Proto-generated code** (`rpc/`) is NOT committed. Run `make proto-generate` locally or let Docker do it. If imports from `rpc/` fail, run `make proto-generate` first. - -2. **Dual error return** — gRPC handlers ALWAYS return both: embed error in response proto (`Error: errpkg.ToProtoPublicError(err)`) AND return `errpkg.WrapError(err)` as the error return. - -3. **Context propagation** — always use `r.database.DBInstance(ctx)` (not `r.database.Db`) for database ops. - -4. **Service layer returns IError** — never return `error` from service/repo; always `errors.IError` from `github.com/razorpay/goutils/errors`. - -5. **Spine sentinel errors** — check `spine.UniqueConstraintViolation` and `spine.RecordNotFound` in the service layer after repo calls, not in the repo itself. - -6. **Repo interface** — `service/repo.go` defines the `Repo` interface; use it for mock injection in tests. - -## Repository Structure - -``` -cmd//main.go # entry point — Foundation bootstrap -internal// - server.go # gRPC server struct + RPC method implementations - handler.go # GRPCHandler + HTTPHandler registration - service/ - service.go # business logic - repo.go # Repo interface (for mocking) - repo/repo.go # spine/GORM data access - model/model.go # domain model + proto conversion -config// # TOML config files -proto///v1/ # .proto source files (COMMITTED) -rpc/ # generated Go code (NOT committed) -migrations/ # SQL migration files -``` - -## Common Tasks - -**Add a new entity:** Follow the pattern in `internal/user/` — create model, repo, service, server, handler, then wire in `cmd//main.go`. Add proto file in `proto/`, run `make proto-generate`. - -**Add a new RPC:** Define in `.proto` file, run `make proto-generate`, implement in `server.go`, add error handling with the dual return pattern. - -**Create a new service from this template:** Run `make rename NAME=`, update `Makefile` BINS and REPO_PREFIX, update `.github/workflows/*.yaml`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6655ab5..c0e5ca8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## v1.0.7 — 2026-05-11 + +- Removed sudo command from the install.sh script + +## v1.0.6 — 2026-05-11 + +- install.sh: Fixed broken S3_BASE_URL that caused 404s; simplified to download directly from latest/ folder +- docs/install.md: Rewrote to match production docs structure with curl commands, quick-install one-liner, macOS quarantine step, and credential configuration + ## v1.0.5 — 2026-05-11 - Enhance make release flow with auto-generated notes and version bump diff --git a/README.md b/README.md index 84b9898..61a572d 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ The script downloads the right tarball for your OS/arch, extracts the `razorpay` ```bash $ razorpay --version -razorpay version v1.0.5 +razorpay version v1.0.7 ``` Other options — Homebrew-style manual download, `go install`, building from source — are in [docs/install.md](docs/install.md). diff --git a/config/user/default.toml b/config/user/default.toml deleted file mode 100644 index 35ecf83..0000000 --- a/config/user/default.toml +++ /dev/null @@ -1,154 +0,0 @@ -[errors] - # List of services for which error mapping is enabled - mappings = [] # e.g. ["go-foundation-v2"] - -# Database Configuration -# Each database is now a key under the [databases] table. -[databases.primary_db] - debug = true # Enable debug logging for database operations - [databases.primary_db.connection] - dialect = "postgres" # Database dialect: postgres, mysql, sqlite - protocol = "tcp" # Connection protocol - url = "postgres" # Database server URL (Docker service name from docker-compose.yml) - port = 5432 # Database server port - username = "example" # Database username - password = "example_pass" # Database password - sslmode = "disable" # SSL mode: disable, require, verify-full - name = "example" # Database name to connect to - schema = "public" # Default database schema - charset = "utf8" # Character set for the connection - [databases.primary_db.connection_pool] - maxopenconnections = 25 # Maximum number of open connections - maxidleconnections = 10 # Maximum number of idle connections - connectionmaxlifetime = 300 # Maximum connection lifetime in seconds - connectionmaxidletime = 60 # Maximum connection idle time in seconds - -# Replica Database Configuration -# [databases.replica_db] -# debug = true # Enable debug logging for database operations -# [databases.replica_db.connection] -# dialect = "postgres" # Database dialect: postgres, mysql, sqlite -# protocol = "tcp" # Connection protocol -# url = "postgres_replica" # Database server URL (Docker service name from docker-compose.yml) -# port = 5432 # Database server port (inside container, postgres always uses 5432) -# username = "example" # Database username -# password = "example_pass" # Database password -# sslmode = "disable" # SSL mode: disable, require, verify-full -# name = "example_replica" # Database name to connect to (replica database) -# schema = "public" # Default database schema -# charset = "utf8" # Character set for the connection -# [databases.replica_db.connection_pool] -# maxopenconnections = 25 # Maximum number of open connections -# maxidleconnections = 10 # Maximum number of idle connections -# connectionmaxlifetime = 300 # Maximum connection lifetime in seconds -# connectionmaxidletime = 60 # Maximum connection idle time in seconds - -# gRPC Server Configuration -[grpc_server] - shutdown_timeout = "30s" # Maximum duration to wait for graceful shutdown - # Server addresses configuration - [grpc_server.server_addresses] - grpc = ":8080" # gRPC server address and port - http = ":8081" # HTTP gateway server address and port - internal = ":8082" # Internal metrics server address and port - # Interceptor configuration - [grpc_server.interceptor] - header_filters = [ # Headers to filter or process - "authorization", - "x-request-id", - "user-agent" - ] - additional_forwarded_headers = [ # Extra HTTP headers forwarded to gRPC metadata - "x-idempotency-key", - "x-merchant-id" - ] - # Access log interceptor configuration - [grpc_server.interceptor.accesslog] - enable_log = true # Enable access logging - log_level = "DEBUG" # Log level: error, warn, info, debug - request_headers = [ # Request headers to capture in logs - "request-id", - "authorization", - "content-type", - "user-agent", - "x-forwarded-for" - ] - - # Credentials map: username -> passwords array - # Each username is a key, and the value is an array of 1-2 passwords - # (1-2 passwords are supported for password rotation scenarios) - [grpc_server.interceptor.basic_auth] - enabled = false # Enable basic authentication - [grpc_server.interceptor.basic_auth.credentials] - "ticker" = ["ticker_secret_from_env"] - - # Passport (authentication) interceptor configuration - [grpc_server.interceptor.passport] - enabled = false # Enable passport authentication - jwks_host = "" # JWKS endpoint URL (required when enabled) - connection_timeout = "1s" # Timeout for JWKS HTTP requests - max_retries = 3 # Maximum number of retry attempts - retry_delay = "100ms" # Delay between retry attempts - -# Telemetry Configuration -[telemetry] - # Logger configuration - [telemetry.logger] - level = "DEBUG" # Log level: DEBUG, INFO, WARN, ERROR (defaults to ERROR) - add_source = true # Include source code location in logs - add_stack_trace_at = "ERROR" # Record stack trace for messages at or above this level - caller_skip_count = 0 # Number of callers to skip for source attribution (defaults to 0) - enabled = true # Whether the logger is functional or acts as no-op (defaults to true) - secure_fields = [ # Field names that should be treated as secure - "password", - "token", - "authorization", - "secret", - "key" - ] - # Masking options for field redaction functionality - [telemetry.logger.mask_options] - redact_fields = [ # Exact field names to completely redact - "password", - "token", - "secret", - "private_key", - "auth_token", - "isfc_code" - ] - redact_field_prefixes = [ # Field name prefixes to redact - "pass", - "auth", - "secret", - "token" - ] - # Metrics configuration - [telemetry.metrics] - enabled = true # Enable metrics collection and export - exporter = "prometheus" # Metrics exporter: prometheus, otlp, jaeger, console - namespace = "foundation_app" # Namespace prefix for all metrics - service_name = "foundation_service" # Service name for metric labels - - # Exponential buckets configuration for histograms - [telemetry.metrics.exponential_buckets] - start = 1.0 # Starting value for first bucket boundary - factor = 2.0 # Multiplication factor between buckets - count = 10 # Total number of bucket boundaries - -# Health Check Configuration -[health_check] - # Maximum goroutine count check - [health_check.max_goroutine_count] - count = 500 # Maximum allowed goroutines - optional = false # Whether this check is optional - # Garbage collection pause check - [health_check.gc_max_pause] - max_pause = "10s" # Maximum allowed GC pause duration - optional = false # Whether this check is optional - -[worker] - disabled = true # This service does not use workers - -[aws] - region = "ap-south-1" - s3_bucket = "random_bucket" diff --git a/config/user/dev.toml b/config/user/dev.toml deleted file mode 100644 index 95c1276..0000000 --- a/config/user/dev.toml +++ /dev/null @@ -1,17 +0,0 @@ -[databases.primary_db.connection] - dialect = "postgres" - protocol = "tcp" - url = "localhost" - port = 5432 - username = "example" - password = "example_pass" - sslmode = "disable" - name = "example" - schema = "public" - charset = "utf8" - -[databases.primary_db.connection_pool] - maxopenconnections = 25 - maxidleconnections = 10 - connectionmaxlifetime = 300 - connectionmaxidletime = 60 diff --git a/config/user/route_config.toml b/config/user/route_config.toml deleted file mode 100644 index 68c7f98..0000000 --- a/config/user/route_config.toml +++ /dev/null @@ -1,2 +0,0 @@ -"/common.health.v2.HealthService/ReadinessCheck" = { basic_auth = false } -"/common.health.v2.HealthService/LivenessCheck" = { basic_auth = true } diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index fb1b033..0000000 --- a/docs/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# Documentation - -This directory contains detailed documentation for the Go Foundation v2 template. Each guide focuses on a specific aspect of the template to help you understand and customize it for your service. - -## 📚 Documentation Index - -### [Example Service](example-service.md) -Understanding the included User Service that demonstrates the template's architecture and patterns. - -**Topics covered:** -- Architecture overview and directory structure -- Key components (entry point, server, service, repository, model layers) -- Request flow through the system -- Code patterns (dependency injection, interfaces, error handling) -- Running the example service - -**Start here if:** you want to understand how the template works before making changes. - ---- - -### [Migration Guide](migration-guide.md) -Step-by-step instructions for transitioning from the example User Service to your custom service. - -**Topics covered:** -- Three-phase migration approach -- Copying service structure and updating proto definitions -- Implementing domain models and business logic -- Configuration and deployment updates -- What to keep vs. what to replace - -**Start here once:** you're ready to build your own service - ---- - -### [Best Practices](best-practices.md) -Coding standards and architectural guidelines to maintain when building services. - -**Topics covered:** -- Layered architecture principles -- Error handling patterns -- Configuration management -- Database patterns and migrations -- Testing guidelines -- Code organization and API design -- Logging, observability, and security - -**Start here if:** you want to ensure your service follows established patterns and standards. - ---- - -### [Build System](build-system.md) -Understanding the Makefile structure and Docker build process. - -**Topics covered:** -- Makefile structure and organization -- Key variables to configure -- Essential Make targets (development, Docker, proto, utility) -- Environment-specific builds -- Extending the Makefile with custom targets -- Troubleshooting common build issues - -**Start here if:** you need to understand or customize the build process. - ---- - -### [Proto Management](proto-management.md) -Guide to managing Protocol Buffers with the centralized proto repository approach. - -**Topics covered:** -- Proto modules configuration -- Complete proto workflow (fetch, generate, lint, refresh) -- Proto file structure -- Buf configuration and customization -- Central proto repository integration -- Proto best practices and troubleshooting - -**Start here if:** you need to work with Protocol Buffers or integrate with the central proto repository. - ---- - -## Quick Reference - -### Getting Started Flow -1. Read [Example Service](example-service.md) to understand the architecture -2. Follow [Migration Guide](migration-guide.md) to create your service -3. Reference [Best Practices](best-practices.md) as you implement features -4. Use [Build System](build-system.md) and [Proto Management](proto-management.md) as needed - -### Common Tasks -- **Running the example:** → [Example Service - Running the Example](example-service.md#running-the-example) -- **Creating your service:** → [Migration Guide - Phase 2](migration-guide.md#phase-2-gradual-replacement) -- **Updating proto files:** → [Proto Management - Proto Workflow](proto-management.md#proto-workflow) -- **Building and testing:** → [Build System - Essential Make Targets](build-system.md#essential-make-targets) -- **Following patterns:** → [Best Practices](best-practices.md) - -## Additional Resources - -- **Main README:** [../README.md](../README.md) - Quick start guide and setup instructions -- **Razorpay Go Style Guide:** https://github.com/razorpay/go-style-guide -- **Foundation Library:** https://github.com/razorpay/foundation -- **Proto Repository:** https://github.com/razorpay/proto - ---- - -**Need help?** Reach out to the Developer Experience Engineering team on slack [#developer-experience](https://razorpay.enterprise.slack.com/archives/C08DS8AE7T8) - diff --git a/docs/best-practices.md b/docs/best-practices.md deleted file mode 100644 index ce41aa9..0000000 --- a/docs/best-practices.md +++ /dev/null @@ -1,79 +0,0 @@ -# Best Practices - -Coding standards and architectural guidelines to maintain when building services from this template. - -## Layered Architecture - -- **Maintain separation** between handler, service, and repository layers -- **Use dependency injection** for testability and flexibility -- **Define clear interfaces** between layers to enable mocking and testing -- Keep business logic in the service layer, not in handlers - -## Error Handling - -- Use structured errors with proper error codes from the `internal/errors` package -- Separate public-facing error messages from internal error details -- Implement proper error logging and metrics for observability -- Always wrap errors with context when propagating them up - -Example: -```go -if err != nil { - return nil, errpkg.WrapError(err) -} -``` - -## Configuration Management - -- Use environment-specific configuration files (`default.toml`, `dev.toml`, etc.) -- Keep sensitive data in environment variables, not in config files -- Document all configuration options in the default config file -- Use the Foundation library's config management utilities - -## Database Patterns - -- Use migrations for all schema changes (never modify schema directly) -- Implement proper connection pooling and timeout configurations -- Add database health checks to monitor connectivity -- Use transactions appropriately for operations that modify multiple tables -- Keep raw SQL queries in the repository layer only - -## Testing Patterns - -- Write unit tests for business logic in the service layer -- Use mocks for external dependencies (database, external APIs) -- Implement integration tests for critical paths -- Test error conditions and edge cases -- Maintain test coverage above 70% for business logic - -## Code Organization - -- Keep domain logic in the `internal/` directory (private to the service) -- Use meaningful package names that reflect domain concepts -- Avoid cyclic dependencies between packages -- Group related functionality together in the same package - -## API Design - -- Follow RESTful principles for HTTP endpoints -- Use proper HTTP status codes and error responses -- Validate all inputs using proto validation rules -- Version your APIs appropriately (`/v1/`, `/v2/`) -- Document your API endpoints in proto files - -## Logging and Observability - -- Use structured logging with the telemetry interface -- Include request IDs in all log statements -- Log at appropriate levels (debug, info, warn, error) -- Emit metrics for critical operations (latency, error rates) -- Add tracing context for distributed tracing - -## Security - -- Validate and sanitize all user inputs -- Use parameterized queries to prevent SQL injection -- Implement proper authentication and authorization -- Keep dependencies up to date for security patches -- Never log sensitive information (passwords, tokens, PII) - diff --git a/docs/build-system.md b/docs/build-system.md deleted file mode 100644 index 9feae27..0000000 --- a/docs/build-system.md +++ /dev/null @@ -1,147 +0,0 @@ -# Build System - -Overview of the Makefile structure and Docker build process. - -## Makefile Structure - -The build system uses a modular approach with multiple makefiles: - -``` -Makefile # Main Makefile (service-specific variables) -scripts/ -├── variables.mk # Global variables and configuration -├── common.mk # Common targets and rules -├── docker.mk # Docker-based build targets -└── local.mk # Local development targets -``` - -## Key Variables - -Configure these variables in the root `Makefile` for your service: - -```makefile -# Update these variables as per your application -BINS ?= user user_migration # Your service binaries -IMAGE_PREFIX ?= fnd- # Docker image prefix -``` - -## Essential Make Targets - -### Development Targets (Faster) -```bash -# Build binaries using local Go installation -make build ENV=local - -# Build specific binary -make build ENV=local BIN=user - -# Run tests locally -make test ENV=local - -# Lint code locally -make lint ENV=local -``` - -### Docker Targets (Default for CI/CD) -```bash -# Build using Docker containers -make build - -# Run tests in containers -make test - -# Lint code in containers -make lint - -# Build and push Docker images -make push -``` - -### Proto Targets -```bash -# Fetch proto files from central repo -make proto-fetch - -# Generate Go code from protos -make proto-generate - -# Lint proto files -make proto-lint - -# Complete proto workflow (clean + fetch + generate + lint) -make proto-refresh -``` - -### Utility Targets -```bash -# Show all available targets and variables -make help - -# Clean build artifacts -make clean - -# Show version information -make version -``` - -## Environment-Specific Builds - -The build system supports different environments: - -```bash -# Local: Uses your local Go installation (faster for development) -make build ENV=local - -# Docker: Uses Docker containers (default, recommended for CI/CD) -make build ENV=docker -``` - -## Extending the Makefile - -To add custom targets for your service, add them to the root `Makefile` after the includes: - -```makefile -# Custom targets for your service -run-local: build - ./bin/your-service --config ./config/your-service/dev.toml - -migrate-up: - ./bin/your-service_migration up - -migrate-down: - ./bin/your-service_migration down -``` - -Use existing patterns from `scripts/common.mk` for consistency. - -## Build Dependencies - -The build system automatically handles: -- Go module dependencies via `go mod download` -- Proto generation tools (buf, protoc-gen-*) -- Linting tools (golangci-lint) -- Docker image dependencies from the base image - -## Common Issues - -### Proto Generation Fails -```bash -# Ensure buf is installed and proto files are fetched -make proto-fetch -make proto-generate ENV=local -``` - -### Build Failures -```bash -# Clean and rebuild -make clean -make build ENV=local -``` - -### Dependency Issues -```bash -# Update Go dependencies -go mod tidy -go mod download -``` - diff --git a/docs/customers.md b/docs/customers.md deleted file mode 100644 index 145d983..0000000 --- a/docs/customers.md +++ /dev/null @@ -1,77 +0,0 @@ -# Customers - -Customer records store contact information for reuse across orders and payments. Associating a customer with a payment enables features like saved cards and payment history. - -## Create a customer - -```bash -razorpay customers create [--name ] [--email ] [--contact ] [--param ] -``` - -At least one of `--name`, `--email`, or `--contact` is required. - -Flags: - -| Flag | Type | Description | -| ----------- | ------ | ---------------------------------------- | -| `--name` | string | Customer's full name | -| `--email` | string | Customer's email address | -| `--contact` | string | Customer's phone number (with country code) | -| `--param` | string | Additional parameter as `key=value`, repeatable | - -Examples: - -```bash -# Create a customer with all fields -razorpay customers create \ - --name "Gaurav Kumar" \ - --email gaurav.kumar@example.com \ - --contact "+919000090000" - -# Create a customer with just an email -razorpay customers create --email gaurav.kumar@example.com -``` - -## List customers - -```bash -razorpay customers list [flags] -``` - -Flags: - -| Flag | Type | Default | Description | -| --------- | ---- | ------- | ------------------------------ | -| `--count` | int | 10 | Number of customers to fetch | -| `--skip` | int | 0 | Records to skip for pagination | - -Example: - -```bash -razorpay customers list --count 25 -``` - -## Fetch a customer - -```bash -razorpay customers fetch -``` - -Example: - -```bash -razorpay customers fetch cust_K6fNE0WJZWGqtN -``` - -## Update a customer - -```bash -razorpay customers update [--name ] [--email ] [--contact ] [--param ] -``` - -Example: - -```bash -# Update a customer's email address -razorpay customers update cust_K6fNE0WJZWGqtN --email newemail@example.com -``` diff --git a/docs/disputes.md b/docs/disputes.md deleted file mode 100644 index 7cfc8d5..0000000 --- a/docs/disputes.md +++ /dev/null @@ -1,90 +0,0 @@ -# Disputes - -A dispute is raised when a customer files a chargeback with their bank. Razorpay notifies you via webhook and gives you a window to either accept the dispute or contest it with evidence. - -## List disputes - -```bash -razorpay disputes list [flags] -``` - -Flags: - -| Flag | Type | Default | Description | -| --------- | ----- | ------- | --------------------------------------- | -| `--count` | int | 10 | Number of disputes to fetch | -| `--skip` | int | 0 | Records to skip for pagination | -| `--from` | int64 | -- | Unix timestamp lower bound (created_at) | -| `--to` | int64 | -- | Unix timestamp upper bound (created_at) | - -Example: - -```bash -razorpay disputes list --count 20 -``` - -## Fetch a dispute - -```bash -razorpay disputes fetch -``` - -Example: - -```bash -razorpay disputes fetch disp_AHfqOvkokHwMsN -``` - -## Accept a dispute - -Accepting a dispute means you concede the chargeback. The disputed amount is deducted from your next settlement. - -```bash -razorpay disputes accept -``` - -Example: - -```bash -razorpay disputes accept disp_AHfqOvkokHwMsN -``` - -> This action is irreversible. Once accepted, the dispute cannot be contested. - -## Contest a dispute - -Contesting a dispute submits evidence to Razorpay for review. You can save a draft first, then submit when ready. - -```bash -razorpay disputes contest [--action ] [--param ] -``` - -Flags: - -| Flag | Type | Description | -| ---------- | ------ | -------------------------------------------------- | -| `--action` | string | `draft` to save without submitting, `submit` to submit for review | -| `--param` | string | Evidence parameter as `key=value`, repeatable | - -Examples: - -```bash -# Save a draft with evidence fields -razorpay disputes contest disp_AHfqOvkokHwMsN \ - --action draft \ - --param "billing_proof=doc_xxx" \ - --param "explanation=Order was delivered on time" - -# Submit the contest -razorpay disputes contest disp_AHfqOvkokHwMsN --action submit -``` - -## Dispute statuses - -| Status | Meaning | -| ----------- | -------------------------------------------------------------- | -| `open` | Dispute raised; action required before the deadline | -| `under_review` | Evidence submitted; awaiting bank decision | -| `won` | Dispute resolved in your favour; no deduction | -| `lost` | Dispute resolved against you; amount deducted | -| `closed` | Dispute closed without a chargeback (e.g. customer retracted) | diff --git a/docs/example-service.md b/docs/example-service.md deleted file mode 100644 index f18e464..0000000 --- a/docs/example-service.md +++ /dev/null @@ -1,125 +0,0 @@ -# Example User Service - -This template includes a complete **User Service** that demonstrates the recommended architecture and patterns for building microservices. - -## Architecture Overview - -``` -cmd/user/ # Service entry point -├── main.go # Application bootstrap - -internal/user/ # Business logic -├── server.go # gRPC server implementation -├── handler.go # HTTP/gRPC handler registration -├── service/ # Business logic layer -├── repo/ # Data access layer -├── model/ # Domain models -└── migrations/ # Database migrations - -config/user/ # Configuration files -├── default.toml # Default configuration -├── dev.toml # Development overrides -└── route_config.toml # API routing configuration - -rpc/go_foundation_v2/ # Generated proto code -└── user/v1/ # User service proto definitions -``` - -## Key Components - -### 1. Entry Point (`cmd/user/main.go`) -- Initializes the Foundation server with configuration -- Sets up database connections and health checks -- Wires together all service dependencies -- Registers gRPC and HTTP handlers - -### 2. Server Layer (`internal/user/server.go`) -- Implements the gRPC service interface -- Handles request validation using proto validation -- Manages error handling and response formatting -- Delegates business logic to the service layer - -### 3. Service Layer (`internal/user/service/`) -- Contains core business logic -- Implements domain rules and validations -- Orchestrates data access operations -- Returns domain models - -### 4. Repository Layer (`internal/user/repo/`) -- Handles data persistence operations -- Abstracts database implementation details -- Provides clean interfaces for data access -- Manages database transactions - -### 5. Model Layer (`internal/user/model/`) -- Defines domain entities and value objects -- Contains business logic specific to entities -- Provides conversion methods (e.g., `ToProto()`) -- Implements validation rules - -## Request Flow - -``` -HTTP/gRPC Request - ↓ - Handler Layer (server.go) - ↓ [validation] - Service Layer (service/) - ↓ [business logic] - Repository Layer (repo/) - ↓ [data access] - Database -``` - -1. Handler receives and validates the request -2. Service layer applies business rules -3. Repository layer handles database interactions -4. Results flow back up through the layers -5. Errors are properly formatted and returned - -## Code Patterns - -### Dependency Injection -```go -// Clean dependency injection in main.go -userServer, err := user.New( - tel, // Telemetry - userservice.New( // Service layer - tel, - repo.New(tel, primaryDB), // Repository layer - ), -) -``` - -### Interface-Based Design -```go -// Service interface defines business operations -type Service interface { - CreateUser(ctx context.Context, req *userv1.CreateRequest) (*model.User, goutilsError.IError) - GetUser(ctx context.Context, req *userv1.GetRequest) (*model.User, goutilsError.IError) -} -``` - -### Error Handling -```go -// Structured error handling with public/private error separation -if err != nil { - return &userv1.User{ - Error: errpkg.ToProtoPublicError(err), - }, errpkg.WrapError(err) -} -``` - -## Running the Example - -```bash -# Run the example service -make build ENV=local -./bin/user --config ./config/user/dev.toml - -# Or using Docker -docker-compose up -``` - -Examine the API endpoints, database migrations, and configuration files to understand the complete flow. - diff --git a/docs/install.md b/docs/install.md index 849d716..7bf24b3 100644 --- a/docs/install.md +++ b/docs/install.md @@ -1,110 +1,229 @@ -# Installing the Razorpay CLI +# Install the Razorpay CLI ---- +The Razorpay CLI lets you interact with Razorpay APIs directly from your terminal. Use it to test integrations, trigger events, manage resources and automate workflows in your CI/CD pipelines. + +To install the Razorpay CLI, you must complete the following actions: + +1. [Download and Install the Binary](#step-1-download-and-install-the-binary) +2. [Configure Your API Credentials](#step-2-configure-your-api-credentials) + +## Step 1: Download and Install the Binary + +### Quick Install (macOS and Linux) -## macOS +Run the install script to automatically detect your OS and architecture, download the latest binary, and install it to `~/.local/bin`: -1. Download the binary for your CPU architecture: +```bash +curl -fsSL https://razorpay.com/cli/latest/install.sh | bash +``` + +### macOS + +1. Download the binary that matches your CPU architecture. | Architecture | Download | |---|---| - | Apple Silicon (M1/M2/M3) | [razorpay_mac-os_arm64.tar.gz](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_mac-os_arm64.tar.gz) | - | Intel | [razorpay_mac-os_x86_64.tar.gz](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_mac-os_x86_64.tar.gz) | + | Apple Silicon | [razorpay_mac-os_arm64.tar.gz](https://razorpay.com/cli/latest/razorpay_mac-os_arm64.tar.gz) | + | Intel | [razorpay_mac-os_x86_64.tar.gz](https://razorpay.com/cli/latest/razorpay_mac-os_x86_64.tar.gz) | + + Or download using curl: + + **Apple Silicon:** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_mac-os_arm64.tar.gz | tar -xz + ``` + + **Intel:** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_mac-os_x86_64.tar.gz | tar -xz + ``` + +2. Extract the archive. -2. Extract the archive: ```bash tar -xvf razorpay_mac-os_.tar.gz ``` -3. Move the binary to your execution path: +3. Make the binary executable and remove the macOS quarantine attribute. + + ```bash + chmod +x ./razorpay + xattr -d com.apple.quarantine ./razorpay + ``` + +4. Move the binary to your execution path. + ```bash sudo mv razorpay /usr/local/bin/ ``` -4. Verify: +5. Verify the installation. + ```bash razorpay --version ``` --- -## Linux +### Linux -1. Download the binary for your architecture: +1. Download the binary that matches your architecture and preferred package format. - | Architecture | Download | - |---|---| - | x86-64 (.tar.gz) | [razorpay_linux_x86_64.tar.gz](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_linux_x86_64.tar.gz) | - | ARM64 (.tar.gz) | [razorpay_linux_arm64.tar.gz](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_linux_arm64.tar.gz) | - | x86-64 (.deb) | [razorpay_linux_amd64.deb](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_linux_amd64.deb) | - | ARM64 (.deb) | [razorpay_linux_arm64.deb](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_linux_arm64.deb) | - | x86-64 (.rpm) | [razorpay_linux_amd64.rpm](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_linux_amd64.rpm) | - | ARM64 (.rpm) | [razorpay_linux_arm64.rpm](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_linux_arm64.rpm) | + | Architecture | Format | Download | + |---|---|---| + | x86-64 | tar.gz | [razorpay_linux_x86_64.tar.gz](https://razorpay.com/cli/latest/razorpay_linux_x86_64.tar.gz) | + | ARM64 | tar.gz | [razorpay_linux_arm64.tar.gz](https://razorpay.com/cli/latest/razorpay_linux_arm64.tar.gz) | + | x86-64 | deb | [razorpay_linux_amd64.deb](https://razorpay.com/cli/latest/razorpay_linux_amd64.deb) | + | ARM64 | deb | [razorpay_linux_arm64.deb](https://razorpay.com/cli/latest/razorpay_linux_arm64.deb) | + | x86-64 | rpm | [razorpay_linux_amd64.rpm](https://razorpay.com/cli/latest/razorpay_linux_amd64.rpm) | + | ARM64 | rpm | [razorpay_linux_arm64.rpm](https://razorpay.com/cli/latest/razorpay_linux_arm64.rpm) | + + Or download using curl: + + **x86-64 (tar.gz):** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_linux_x86_64.tar.gz | tar -xz + ``` -2. Install based on the format downloaded: + **ARM64 (tar.gz):** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_linux_arm64.tar.gz | tar -xz + ``` + + **x86-64 (deb):** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_linux_amd64.deb -o /tmp/razorpay.deb \ + && sudo dpkg -i /tmp/razorpay.deb + ``` + + **ARM64 (deb):** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_linux_arm64.deb -o /tmp/razorpay.deb \ + && sudo dpkg -i /tmp/razorpay.deb + ``` + + **x86-64 (rpm):** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_linux_amd64.rpm -o /tmp/razorpay.rpm \ + && sudo rpm -i /tmp/razorpay.rpm + ``` + + **ARM64 (rpm):** + ```bash + curl -fsSL https://razorpay.com/cli/latest/razorpay_linux_arm64.rpm -o /tmp/razorpay.rpm \ + && sudo rpm -i /tmp/razorpay.rpm + ``` + +2. Install based on the format you downloaded. + + For `tar.gz`: - **tar.gz:** ```bash tar -xvf razorpay_linux_.tar.gz sudo mv razorpay /usr/local/bin/ ``` - **deb (Debian / Ubuntu):** + For `deb` (Debian and Ubuntu): + ```bash sudo dpkg -i razorpay_linux_.deb ``` - **rpm (RHEL / Fedora / Amazon Linux):** + For `rpm` (RHEL, Fedora and Amazon Linux): + ```bash sudo rpm -i razorpay_linux_.rpm ``` -3. Verify: +3. Verify the installation. + ```bash razorpay --version ``` --- -## Windows +### Windows -1. Download the binary for your architecture: +1. Download the binary that matches your architecture. | Architecture | Download | |---|---| - | x86-64 | [razorpay_windows_x86_64.zip](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_windows_x86_64.zip) | - | x86 (32-bit) | [razorpay_windows_i386.zip](https://.s3..amazonaws.com/razorpay-cli/latest/razorpay_windows_i386.zip) | + | x86-64 | [razorpay_windows_x86_64.zip](https://razorpay.com/cli/latest/razorpay_windows_x86_64.zip) | + | x86 (32-bit) | [razorpay_windows_i386.zip](https://razorpay.com/cli/latest/razorpay_windows_i386.zip) | + + Or download using curl in PowerShell: -2. Unzip the file: + **x86-64:** ```powershell - Expand-Archive razorpay_windows_.zip -DestinationPath . + curl.exe -fsSL -o razorpay_windows_x86_64.zip https://razorpay.com/cli/latest/razorpay_windows_x86_64.zip ``` -3. Add the path to `razorpay.exe` to your `Path` environment variable: - - Open **System Properties → Environment Variables** - - Under **System variables**, select `Path` → **Edit** → **New** - - Add the folder path where `razorpay.exe` is located + **x86 (32-bit):** + ```powershell + curl.exe -fsSL -o razorpay_windows_i386.zip https://razorpay.com/cli/latest/razorpay_windows_i386.zip + ``` + +2. Extract the archive. + + Open PowerShell in the folder where you downloaded the file and run: -4. Open a new terminal and verify: ```powershell + Expand-Archive razorpay_windows_.zip -DestinationPath . + ``` + +3. Add the binary to your Path environment variable. + + 1. Open **System Properties** > **Environment Variables**. + 2. Under **System variables**, select **Path** > **Edit** > **New**. + 3. Add the folder path where `razorpay.exe` is located. + 4. Click **OK** to save the changes. + +4. Verify the installation. + + Open a new terminal and run: + + ```bash razorpay --version ``` --- -## Next steps +## Step 2: Configure Your API Credentials + +After installing the CLI, configure it with your API credentials to start making requests. Generate your keys from the [Razorpay Dashboard](https://dashboard.razorpay.com/app/keys). + +You can configure credentials in two ways: -Configure your API credentials: +**Option 1: Pass credentials directly in the command** ```bash -razorpay configure +razorpay configure --key-id rzp_test_xxxxxxxxxxxx --key-secret xxxxxxxxxxxxxxxxxxxx ``` -You will be prompted for your **Key ID** and **Key Secret** from the [Razorpay Dashboard](https://dashboard.razorpay.com/app/website-app-settings/api-keys). +**Option 2: Use the interactive prompt** -For CI/CD environments, use environment variables instead: +Run the command without arguments and enter your credentials when prompted: ```bash -export RAZORPAY_KEY_ID=rzp_test_xxxxxxxxxxxx -export RAZORPAY_KEY_SECRET=xxxxxxxxxxxxxxxxxxxx +razorpay configure +``` + +``` +Enter your Razorpay Key ID: rzp_test_xxxxxxxxxxxx +Enter your Razorpay Key Secret: xxxxxxxxxxxxxxxxxxxx ``` + +> **Test Mode and Live Mode** +> +> The CLI supports both Test Mode and Live Mode keys. Use Test Mode keys (prefixed with `rzp_test_`) while building and testing your integration. + +> **Verify Your Setup** +> +> Once configured, run `razorpay --version` to confirm the CLI is installed and ready to use. + +## Related Information + +- [Authentication](https://razorpay.com/docs/api/authentication/) +- [Sandbox Setup](https://razorpay.com/docs/api/sandbox-setup/) +- [API Reference Guide](https://razorpay.com/docs/api/) diff --git a/docs/migration-guide.md b/docs/migration-guide.md deleted file mode 100644 index b8f3531..0000000 --- a/docs/migration-guide.md +++ /dev/null @@ -1,104 +0,0 @@ -# Migration Guide - -Step-by-step guide for transitioning from the example User Service to your custom service. - -## Phase 1: Understanding the Example - -Before making changes, familiarize yourself with the template: - -1. Run the example service to understand the flow -2. Examine the API endpoints using the generated HTTP handlers -3. Study the database migrations in `internal/user/migrations/` -4. Review the configuration files in `config/user/` - -## Phase 2: Gradual Replacement - -### Step 1: Copy the Service Structure - -Keep the established structure and replace the domain logic: - -```bash -# Copy the user service as a template for your domain -cp -r internal/user internal/your-domain -cp -r cmd/user cmd/your-domain -cp -r config/user config/your-domain -``` - -### Step 2: Update Proto Definitions - -Define your service's proto files in the central proto repository: - -1. Update `build/proto_modules` with your service name: - ```bash - echo "your_service_name" > build/proto_modules - ``` - -2. Refresh proto files: - ```bash - make proto-refresh - ``` - -### Step 3: Implement Domain Models - -Replace the user-specific entities with your domain: - -1. Update `internal/your-domain/model/model.go` with your entities -2. Create database migrations for your schema in `internal/your-domain/migrations/` -3. Modify repository methods in `internal/your-domain/repo/` for your data access patterns - -### Step 4: Update Business Logic - -1. Replace service layer methods in `internal/your-domain/service/` with your business operations -2. Update validation rules and error handling -3. Modify `internal/your-domain/server.go` to handle your specific endpoints - -## Phase 3: Configuration and Deployment - -### Update Configuration - -1. Modify `config/your-domain/*.toml` files with service-specific settings -2. Update database connection strings and service settings -3. Configure routing and middleware options in `route_config.toml` - -### Update Build Configuration - -1. Update `BINS` in the root `Makefile`: - ```makefile - BINS ?= your-domain your-domain_migration - ``` - -2. Update `IMAGE_PREFIX` if needed: - ```makefile - IMAGE_PREFIX ?= your-prefix- - ``` - -3. Update GitHub Actions workflows: - - Modify `.github/workflows/build_example.yaml` with your service name - - Update image names and binary references - -## What to Keep vs. Replace - -### ✅ Keep These Patterns -- Overall project structure and directory layout -- Dependency injection and interface design -- Error handling and validation patterns -- Configuration management approach -- Build system and CI/CD workflows -- Logging and metrics integration - -### 🔄 Replace These Components -- Domain-specific models and business logic -- Database schema and migrations -- Proto definitions and generated code -- Service-specific configuration values -- API endpoint implementations -- Domain-specific validation rules - -## Exploring Without Full Migration - -If you want to explore the example service first without setting up your own protos: - -1. Keep the existing `build/proto_modules` content -2. Run `make proto-fetch && make proto-generate` to ensure generated code is up-to-date -3. The example user service will work with the existing proto definitions - diff --git a/docs/orders.md b/docs/orders.md deleted file mode 100644 index a7155d7..0000000 --- a/docs/orders.md +++ /dev/null @@ -1,103 +0,0 @@ -# Orders - -An order is a payment intent that you create before presenting the Razorpay checkout to your customer. Every payment in Razorpay is recommended to be associated with an order for full payment tracking. - -## Create an order - -```bash -razorpay orders create --amount [--currency ] [--receipt ] [--param ] -``` - -Flags: - -| Flag | Type | Default | Description | -| ------------- | ------ | ------- | -------------------------------------------------- | -| `--amount` | int | -- | Amount in smallest currency unit (required) | -| `--currency` | string | `INR` | ISO 4217 currency code | -| `--receipt` | string | -- | Your internal receipt or order ID (max 40 chars) | -| `--param` | string | -- | Additional parameter as `key=value`, repeatable | - -Examples: - -```bash -# Create an INR order for Rs. 299 (29900 paise) -razorpay orders create --amount 29900 --currency INR --receipt "receipt-001" - -# Create an order with partial payment enabled -razorpay orders create --amount 50000 --currency INR --param partial_payment=true -``` - -## List orders - -```bash -razorpay orders list [flags] -``` - -Flags: - -| Flag | Type | Default | Description | -| ----------- | ------ | ------- | ----------------------------------------------- | -| `--count` | int | 10 | Number of orders to fetch (max 100) | -| `--skip` | int | 0 | Records to skip for pagination | -| `--from` | int64 | -- | Unix timestamp lower bound | -| `--to` | int64 | -- | Unix timestamp upper bound | -| `--status` | string | -- | Filter by status: `created`, `attempted`, `paid` | - -Examples: - -```bash -# List all unpaid orders -razorpay orders list --status created - -# List 50 orders created this week -razorpay orders list --count 50 --from 1711929600 -``` - -## Fetch an order - -```bash -razorpay orders fetch -``` - -Example: - -```bash -razorpay orders fetch order_RB58MiP5SPFYyM -``` - -## Update an order - -Only the `notes` field can be updated after order creation. - -```bash -razorpay orders update --param ... -``` - -Example: - -```bash -razorpay orders update order_RB58MiP5SPFYyM \ - --param "notes[shipping_id]=SHIP-9012" -``` - -## Fetch payments for an order - -Returns all payment attempts (successful and failed) made against an order. - -```bash -razorpay orders payments -``` - -Example: - -```bash -razorpay orders payments order_RB58MiP5SPFYyM -``` - -## Order statuses - -| Status | Meaning | -| ----------- | -------------------------------------------------------------- | -| `created` | No payment attempt has been made yet | -| `attempted` | At least one payment attempt has been made; none captured yet | -| `paid` | A payment has been captured; no further payments are accepted | diff --git a/docs/payments.md b/docs/payments.md deleted file mode 100644 index a4ca759..0000000 --- a/docs/payments.md +++ /dev/null @@ -1,106 +0,0 @@ -# Payments - -Payments represent a customer's payment attempt against an order or a direct charge. The Razorpay payment lifecycle is: `created` -> `authorized` -> `captured` -> `refunded`. - -## List payments - -Fetches a paginated list of payments in reverse chronological order. - -```bash -razorpay payments list [flags] -``` - -Flags: - -| Flag | Type | Default | Description | -| ----------- | ----- | ------- | ---------------------------------------- | -| `--count` | int | 10 | Number of payments to fetch (max 100) | -| `--skip` | int | 0 | Number of records to skip for pagination | -| `--from` | int64 | -- | Unix timestamp lower bound (created_at) | -| `--to` | int64 | -- | Unix timestamp upper bound (created_at) | - -Examples: - -```bash -# Fetch the 20 most recent payments -razorpay payments list --count 20 - -# Fetch payments from January 2024 -razorpay payments list --from 1704067200 --to 1706745600 -``` - -## Fetch a payment - -```bash -razorpay payments fetch -``` - -Example: - -```bash -razorpay payments fetch pay_29QQoUBi66xm2f -``` - -## Capture a payment - -Changes a payment's status from `authorized` to `captured`. The `--amount` must equal the authorized amount. - -```bash -razorpay payments capture --amount [--currency ] -``` - -Flags: - -| Flag | Type | Default | Description | -| ------------ | ------ | ------- | ------------------------------------------------- | -| `--amount` | int | -- | Amount in smallest currency unit, e.g. paise | -| `--currency` | string | `INR` | ISO 4217 currency code | - -Example: - -```bash -# Capture INR 10.00 (1000 paise) -razorpay payments capture pay_29QQoUBi66xm2f --amount 1000 --currency INR -``` - -> Attempting to capture a payment that is not in the `authorized` state returns a `400` error. - -## Update a payment - -Updates the `notes` field on a payment. Notes are key-value pairs stored for your internal reference. - -```bash -razorpay payments update --param ... -``` - -Example: - -```bash -razorpay payments update pay_29QQoUBi66xm2f \ - --param "notes[order_ref]=ORD-1234" \ - --param "notes[customer_ref]=CUST-5678" -``` - -## Fetch transfers for a payment - -Returns all Route transfers created from a payment. - -```bash -razorpay payments transfers -``` - -Example: - -```bash -razorpay payments transfers pay_29QQoUBi66xm2f -``` - -## Payment statuses - -| Status | Meaning | -| ------------ | ---------------------------------------------------- | -| `created` | Payment initiated but not yet authorized | -| `authorized` | Bank has authorized; capture required | -| `captured` | Amount deducted from customer; funds with Razorpay | -| `refunded` | Amount refunded partially or fully | -| `failed` | Payment failed at authorization or capture | diff --git a/docs/proto-management.md b/docs/proto-management.md deleted file mode 100644 index 08a1138..0000000 --- a/docs/proto-management.md +++ /dev/null @@ -1,151 +0,0 @@ -# Protocol Buffers Management - -Guide to managing Protocol Buffers with the centralized proto repository approach. - -## Overview - -This template uses a centralized proto repository to manage proto definitions across services. Proto files are fetched from a central repository and code is generated locally. - -## Proto Modules Configuration - -The `build/proto_modules` file specifies which proto modules to fetch: - -```bash -# View current proto module -cat build/proto_modules -# Output: go_foundation_v2 -``` - -### Updating for Your Service - -After renaming your service, update the proto module: - -```bash -echo "your_service_name" > build/proto_modules -``` - -## Proto Workflow - -### 1. Fetch Proto Files - -Download proto files from the central repository: - -```bash -make proto-fetch -``` - -This fetches proto files from `https://github.com/razorpay/proto.git` into the `proto/` directory. - -### 2. Generate Go Code - -Generate Go code from proto files: - -```bash -make proto-generate -``` - -This creates Go code in the `rpc/` directory using buf and protoc plugins. - -### 3. Lint Proto Files - -Validate proto files against best practices: - -```bash -make proto-lint -``` - -### 4. Complete Refresh - -Run the complete proto workflow: - -```bash -make proto-refresh -``` - -This performs: clean → fetch → generate → lint - -## Proto File Structure - -After fetching and generating, your proto structure will look like: - -``` -proto/ -└── your_service_name/ - └── your_domain/ - └── v1/ - └── your_service.proto - -rpc/ -└── your_service_name/ - └── your_domain/ - └── v1/ - ├── your_service.pb.go # Generated proto messages - ├── your_service_grpc.pb.go # Generated gRPC services - └── your_service.pb.validate.go # Generated validation -``` - -## Buf Configuration - -The template uses [buf](https://buf.build/) for proto management: - -- `buf.yaml`: Defines the proto module and lint rules -- `buf.gen.yaml`: Configures code generation plugins -- `buf.lock`: Locks dependencies for reproducible builds - -### Updating Buf Configuration - -Modify `buf.gen.yaml` to customize code generation: - -```yaml -version: v1 -plugins: - - plugin: buf.build/protocolbuffers/go - out: rpc - opt: paths=source_relative - - plugin: buf.build/grpc/go - out: rpc - opt: paths=source_relative -``` - -## Central Proto Repository - -### Adding New Proto Definitions - -1. Add your proto files to the central proto repository -2. Follow the standard directory structure: `your_service/domain/v1/` -3. Update `build/proto_modules` in your service repository -4. Run `make proto-refresh` to fetch and generate code - -### Proto Best Practices - -- Version your APIs (`v1`, `v2`, etc.) -- Use meaningful message and field names -- Add validation rules using `buf.build/bufbuild/protovalidate` -- Document your proto files with comments -- Keep proto files focused on a single domain - -## Troubleshooting - -### Missing Generated Code -```bash -# Regenerate proto code -make proto-generate -``` - -### Proto Lint Errors -```bash -# Check lint errors -make proto-lint - -# Fix formatting issues in proto files -``` - -### Buf Dependencies Out of Date -```bash -# Update buf dependencies -buf mod update proto/ -``` - -### Proto Fetch Failures -Ensure you have access to the central proto repository and your GitHub credentials are configured correctly. - diff --git a/docs/refunds.md b/docs/refunds.md deleted file mode 100644 index 9cac9cd..0000000 --- a/docs/refunds.md +++ /dev/null @@ -1,90 +0,0 @@ -# Refunds - -A refund returns captured funds to a customer. Refunds can be full or partial. Partial refunds can be issued multiple times as long as the total does not exceed the captured amount. - -## Create a refund - -Refunds are created against a specific payment, not directly against an order. - -```bash -razorpay refunds create [--amount ] [--speed ] [--param ] -``` - -Flags: - -| Flag | Type | Description | -| ---------- | ------ | ------------------------------------------------------------------ | -| `--amount` | int | Amount to refund in smallest currency unit; omit for full refund | -| `--speed` | string | Refund processing speed: `normal` or `optimum` | -| `--param` | string | Additional parameter as `key=value`, repeatable | - -Examples: - -```bash -# Full refund -razorpay refunds create pay_29QQoUBi66xm2f - -# Partial refund of Rs. 5.00 (500 paise) -razorpay refunds create pay_29QQoUBi66xm2f --amount 500 - -# Optimum-speed refund (processed within business hours) -razorpay refunds create pay_29QQoUBi66xm2f --speed optimum -``` - -> `optimum` speed routes refunds through IMPS when possible, resulting in faster settlements compared to `normal`. - -## List refunds - -```bash -razorpay refunds list [flags] -``` - -Flags: - -| Flag | Type | Default | Description | -| --------- | ----- | ------- | ---------------------------------------- | -| `--count` | int | 10 | Number of refunds to fetch (max 100) | -| `--skip` | int | 0 | Records to skip for pagination | -| `--from` | int64 | -- | Unix timestamp lower bound (created_at) | -| `--to` | int64 | -- | Unix timestamp upper bound (created_at) | - -Example: - -```bash -razorpay refunds list --count 50 --from 1704067200 -``` - -## Fetch a refund - -```bash -razorpay refunds fetch -``` - -Example: - -```bash -razorpay refunds fetch rfnd_FP8QHiV938haTz -``` - -## Update a refund - -Only the `notes` field can be updated after a refund is created. - -```bash -razorpay refunds update --param ... -``` - -Example: - -```bash -razorpay refunds update rfnd_FP8QHiV938haTz \ - --param "notes[reason]=Customer requested cancellation" -``` - -## Refund statuses - -| Status | Meaning | -| ---------- | ---------------------------------------------------- | -| `pending` | Refund is queued but not yet processed | -| `processed`| Funds have been returned to the customer | -| `failed` | Refund processing failed; funds not returned | diff --git a/docs/settlements.md b/docs/settlements.md deleted file mode 100644 index 070eefc..0000000 --- a/docs/settlements.md +++ /dev/null @@ -1,63 +0,0 @@ -# Settlements - -Settlements represent the transfer of funds from Razorpay to your bank account. Razorpay batches captured payments and settles them on a T+2 or T+3 cycle depending on your plan. - -## List settlements - -```bash -razorpay settlements list [flags] -``` - -Flags: - -| Flag | Type | Default | Description | -| --------- | ----- | ------- | ---------------------------------------- | -| `--count` | int | 10 | Number of settlements to fetch | -| `--skip` | int | 0 | Records to skip for pagination | -| `--from` | int64 | -- | Unix timestamp lower bound (created_at) | -| `--to` | int64 | -- | Unix timestamp upper bound (created_at) | - -Example: - -```bash -# Settlements from Q1 2024 -razorpay settlements list --from 1704067200 --to 1711929599 --count 100 -``` - -## Fetch a settlement - -```bash -razorpay settlements fetch -``` - -Example: - -```bash -razorpay settlements fetch setl_7IbFiDRTBaQqeL -``` - -## Fetch settlement recon report - -The recon report contains a line-by-line breakdown of every transaction included in a settlement. Use this for reconciling settlements against your internal records. - -```bash -razorpay settlements recon [--year ] [--month ] [--day ] -``` - -Flags: - -| Flag | Type | Description | -| --------- | ---- | ------------------------------------ | -| `--year` | int | Year, e.g. `2024` | -| `--month` | int | Month as a number, `1` through `12` | -| `--day` | int | Day of the month, `1` through `31` | - -Examples: - -```bash -# Recon report for January 2024 -razorpay settlements recon --year 2024 --month 1 - -# Recon report for a specific day -razorpay settlements recon --year 2024 --month 3 --day 15 -``` diff --git a/install.sh b/install.sh index 78ea5a0..8361171 100644 --- a/install.sh +++ b/install.sh @@ -2,8 +2,8 @@ set -euo pipefail BINARY="razorpay" -INSTALL_DIR="/usr/local/bin" -S3_BASE_URL="https://razorpay.com/cli/latest/install.sh" +INSTALL_DIR="$HOME/.local/bin" +BASE_URL="https://razorpay.com/cli/latest" # --------------------------------------------------------------------------- # Detect OS and architecture @@ -29,27 +29,14 @@ case "$ARCH" in ;; esac -# --------------------------------------------------------------------------- -# Resolve latest version from S3 -# --------------------------------------------------------------------------- -echo "Fetching latest version..." -VERSION=$(curl -fsSL "${S3_BASE_URL}/latest") - -if [ -z "$VERSION" ]; then - echo "Could not determine latest version. Check your internet connection." - exit 1 -fi - -echo "Latest version: $VERSION" - # --------------------------------------------------------------------------- # Download and extract # --------------------------------------------------------------------------- -ARCHIVE="${BINARY}_${VERSION#v}_${OS_NAME}_${ARCH_NAME}.tar.gz" -URL="${S3_BASE_URL}/${VERSION#v}/${ARCHIVE}" +ARCHIVE="${BINARY}_${OS_NAME}_${ARCH_NAME}.tar.gz" +URL="${BASE_URL}/${ARCHIVE}" TMP_DIR="$(mktemp -d)" -echo "Downloading $ARCHIVE..." +echo "Downloading ${ARCHIVE}..." curl -fsSL "$URL" -o "$TMP_DIR/$ARCHIVE" echo "Extracting..." @@ -58,17 +45,36 @@ tar -xzf "$TMP_DIR/$ARCHIVE" -C "$TMP_DIR" # --------------------------------------------------------------------------- # Install # --------------------------------------------------------------------------- -if [ ! -w "$INSTALL_DIR" ]; then - echo "Installing to $INSTALL_DIR (requires sudo)..." - sudo mv "$TMP_DIR/$BINARY" "$INSTALL_DIR/$BINARY" - sudo chmod +x "$INSTALL_DIR/$BINARY" -else - mv "$TMP_DIR/$BINARY" "$INSTALL_DIR/$BINARY" - chmod +x "$INSTALL_DIR/$BINARY" -fi +mkdir -p "$INSTALL_DIR" +mv "$TMP_DIR/$BINARY" "$INSTALL_DIR/$BINARY" +chmod +x "$INSTALL_DIR/$BINARY" rm -rf "$TMP_DIR" +# --------------------------------------------------------------------------- +# Ensure ~/.local/bin is in PATH +# --------------------------------------------------------------------------- +if ! echo "$PATH" | tr ':' '\n' | grep -q "^$INSTALL_DIR$"; then + SHELL_NAME="$(basename "$SHELL")" + case "$SHELL_NAME" in + zsh) PROFILE="$HOME/.zshrc" ;; + bash) PROFILE="$HOME/.bashrc" ;; + *) PROFILE="$HOME/.profile" ;; + esac + + EXPORT_LINE="export PATH=\"\$HOME/.local/bin:\$PATH\"" + + if ! grep -qF '.local/bin' "$PROFILE" 2>/dev/null; then + echo "" >> "$PROFILE" + echo "$EXPORT_LINE" >> "$PROFILE" + echo "Added $INSTALL_DIR to PATH in $PROFILE" + fi + + echo "" + echo "NOTE: Run 'source $PROFILE' or open a new terminal for the PATH change to take effect." +fi + +VERSION=$("$INSTALL_DIR/$BINARY" --version 2>/dev/null || echo "unknown") echo "" -echo "razorpay $VERSION installed to $INSTALL_DIR/$BINARY" +echo "razorpay ${VERSION} installed to $INSTALL_DIR/$BINARY" echo "Run 'razorpay configure' to set up your API credentials." diff --git a/scripts/devstack-debugger.sh b/scripts/devstack-debugger.sh deleted file mode 100644 index 41e3a7b..0000000 --- a/scripts/devstack-debugger.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/sh -# ============================================================================= -# Devstack Remote Debugger Script -# ============================================================================= -# This script attaches Delve debugger to the running application process. -# It is executed by DevSpace after file sync to enable remote debugging. -# -# Usage: ./devstack-debugger.sh -# - port: The port on which Delve will listen (e.g., 2345) -# ============================================================================= - -echo "Remote Debugger" - -echo "Getting the PID of Delve process if it is already running" -DLV_PIDS=$(ps -ef | grep dlv | grep -v grep | awk '{print $2}') -if [ -n "$DLV_PIDS" ]; then - echo "Killing existing Delve processes: $DLV_PIDS" - for pid in $DLV_PIDS; do - kill -9 "$pid" 2>/dev/null || true - done -fi - -echo "[Debugger] Waiting for process to start..." -while ! curl -s -w '%{http_code}\n' 'http://localhost:8081/ready' 2>/dev/null | grep -q 200; do - echo "[Debugger] Application not ready yet, retrying in 5s..." - sleep 5 -done - -echo "Application is ready, getting PID of the running application" -PID=$(ps -ef | grep "/tmp/app" | grep -v "CompileDaemon" | grep -v "grep" | awk '{print $2}' | head -1) - -if [ -n "$PID" ]; then - echo "Attaching debugger to process: $PID on port :$1" - dlv attach "$PID" --listen=":$1" --headless --api-version=2 --accept-multiclient --check-go-version=false -else - echo "ERROR: Could not find application PID" - exit 1 -fi - diff --git a/scripts/rename.sh b/scripts/rename.sh deleted file mode 100644 index f1bb2cc..0000000 --- a/scripts/rename.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash - -# Script to replace "go-foundation-v2" with your service name across -# the Go codebase only -# Will not touch YAML files, Dockerfiles, or GitHub workflow files - -set -e # Exit on error - -# Check if an argument is provided -if [ -z "$1" ]; then - echo -e "${RED}Error: No service name provided.${NC}" - echo "Usage: $0 " - exit 1 -fi - -NEW_SERVICE_NAME=$1 -OLD_MODULE_PATH="github.com/razorpay/go-foundation-v2" -NEW_MODULE_PATH="github.com/razorpay/${NEW_SERVICE_NAME}" -OLD_SERVICE_NAME="go-foundation-v2" - -# Colors for output -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -RED='\033[0;31m' -NC='\033[0m' # No Color - -echo -e "${YELLOW}Starting replacement of '${OLD_SERVICE_NAME}' with '${NEW_SERVICE_NAME}' in Go files only...${NC}" - -# 1. First replace in go.mod file -echo -e "Updating ${GREEN}go.mod${NC}..." -sed -i '' "s|${OLD_MODULE_PATH}|${NEW_MODULE_PATH}|g" go.mod - -# 2. Replace in all .go files -echo -e "Updating ${GREEN}Go source files${NC}..." -find . -name "*.go" -type f -print0 | xargs -0 sed -i '' "s|${OLD_MODULE_PATH}|${NEW_MODULE_PATH}|g" - -# 3. Update git remote origin URL -NEW_REMOTE_URL="git@github.com:razorpay/${NEW_SERVICE_NAME}.git" -echo -e "Updating ${GREEN}git remote origin${NC} URL to ${NEW_REMOTE_URL}..." -git remote set-url origin "${NEW_REMOTE_URL}" - -echo -e "${YELLOW}Replacement complete in Go files, go.mod, Makefile, and git remote origin URL.${NC}" -echo -e "${YELLOW}Note: You will need to manually update Dockerfiles and GitHub workflow files.${NC}" -echo -e "${YELLOW}Note: You may need to run 'go mod tidy' after this script to update dependencies.${NC}" \ No newline at end of file