fintechin

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 21 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-fintech-india · v0.4.0

This repository's public history begins from a single initial commit; see CHANGELOG.md for the version-by-version record of what shipped.

CI Go Reference Docs Portal llms.txt Coverage OpenSSF Scorecard

go-fintech-india is a zero-dependency, production-grade Go library designed for financial engines, banking gateways, neo-banks, and enterprise ERPs operating in the Indian economy.

Engineered with pure Go standard library primitives, zero heap allocations on verification hot-paths, and strict compliance with Indian statutory authorities (UIDAI, GSTN, Income Tax Department, RBI, NPCI, and MCA).


Key Highlights

  • ⚡ Zero External Dependencies: 100% pure Go standard library. Zero bloat, zero supply-chain risk.
  • 💰 Exact Integer Paise Math: Represents all currency as int64 paise (1 INR = 100 paise). Eliminates IEEE 754 floating-point rounding errors and penny-dropping bugs.
  • 🧮 Remainder-Safe Allocations: Proportional distribution and Hare-Niemeyer weighted allocation guarantee $\sum \text{parts} == \text{total}$.
  • 📜 Indian Lakhs/Crores & Cheque Printing: Canonical formatting (₹12,34,567.89), zero-allocation streaming (AppendINR), and legal words conversion for bank cheques and invoices.
  • 🛡️ Statutory Identity Checksums:
    • UIDAI Aadhaar: Official Verhoeff Dihedral $D_5$ algorithm validation and statutory masking (XXXX-XXXX-1234).
    • Income Tax PAN: Structural verification, 4th-character entity classification (Individual, Company, Firm, Trust, etc.), surname cross-validation, and masking.
    • GSTN GSTIN: 15-character Mod-36 checksum calculation and full 37 State/UT code registry lookup.
  • 🏦 Interbank & Retail Payments:
    • RBI IFSC & MICR: Bank routing validation, 4-letter bank codes, and 9-digit cheque clearing transit codes.
    • NPCI UPI Payments: VPA validation, PSP handle verification, and UPI Intent / QR code URI generator and parser.
    • Bank Account & Mobile: RBI account masking, DoT 10-digit mobile verification, and international E.164 standardization (+91).
  • 📅 Statutory Accounting & Tax Schedules:
    • Indian Financial Year (April 1 to March 31) and Assessment Year resolution.
    • Advance Tax installment due dates and statutory cumulative percentages (Section 211).
    • MCA Schedule III Trade Receivables aging bucketing (0-30, 31-60, 61-90, 91-180, >180 days).

Installation

go get github.com/abeta-dev/go-fintech-india@v0.4.0

Full Code Examples

1. Money Math & Remainder-Safe Split
package main

import (
	"fmt"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	// 100 Rupees = 10,000 paise
	total := fintechin.NewMoneyFromRupees(100)

	// Split 100 rupees evenly among 3 parties
	// Standard division would drop 1 paisa (33.33 * 3 = 99.99).
	// fintechin.Split distributes remainder paise so sum == total.
	parts, _ := total.Split(3)
	for i, part := range parts {
		fmt.Printf("Party %d: %s (%d paise)\n", i+1, part.String(), part.Paise())
	}
	// Output:
	// Party 1: 33.34 (3334 paise)
	// Party 2: 33.33 (3333 paise)
	// Party 3: 33.33 (3333 paise)

	// Proportional allocation (e.g. 50%, 30%, 20%)
	allocated, _ := total.Allocate(50, 30, 20)
	fmt.Printf("Allocated 50%%: %s, 30%%: %s, 20%%: %s\n",
		allocated[0].String(), allocated[1].String(), allocated[2].String())
}
2. Words in INR & Cheque Printing
package main

import (
	"fmt"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	amount, _ := fintechin.ParseINR("₹12,34,567.89")

	// Print amount in words for cheques per Indian banking conventions
	chequeText := fintechin.InWords(amount)
	fmt.Println(chequeText)
	// Output:
	// Rupees Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven and Eighty-Nine Paise Only

	// Standard number to words
	fmt.Println(fintechin.NumberToIndianWords(10000000))
	// Output: One Crore
}
3. GSTIN Mod-36 Validation & State Lookup
package main

import (
	"fmt"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	gstin := "29AACCG0527D1Z0"

	if err := fintechin.ValidateGSTIN(gstin); err != nil {
		fmt.Println("Invalid GSTIN:", err)
		return
	}

	stateName, _ := fintechin.StateName(fintechin.StateCode(gstin))
	pan := fintechin.ExtractPAN(gstin)

	fmt.Printf("Valid GSTIN for State: %s (State Code %s), Embedded PAN: %s\n",
		stateName, fintechin.StateCode(gstin), pan)
	// Output:
	// Valid GSTIN for State: Karnataka (State Code 29), Embedded PAN: AACCG0527D
}
4. Aadhaar Verhoeff Checksum & UIDAI Masking
package main

import (
	"fmt"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	aadhaar := "999941057058"

	// Validates length, non 0/1 start, and Verhoeff dihedral D5 checksum
	if err := fintechin.ValidateAadhaar(aadhaar); err != nil {
		fmt.Println("Invalid Aadhaar:", err)
		return
	}

	// Mask for storage and display (statutory compliance)
	masked := fintechin.MaskAadhaar(aadhaar)
	formatted := fintechin.FormatAadhaar(aadhaar)

	fmt.Printf("Aadhaar Valid: Masked=%s, Formatted=%s\n", masked, formatted)
	// Output:
	// Aadhaar Valid: Masked=XXXX-XXXX-7058, Formatted=9999 4105 7058
}
5. PAN Entity Parsing & Surname Verification
package main

import (
	"fmt"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	pan := "ABCDE1234F"

	if err := fintechin.ValidatePAN(pan); err != nil {
		fmt.Println("Invalid PAN:", err)
		return
	}

	entity, _ := fintechin.EntityType(pan)
	fmt.Printf("Entity Type: %s\n", entity) // Output: Entity Type: Company

	// Individual PAN example: 4th char is 'P', 5th char is first letter of surname
	indPAN := "ABCDS1234F"
	isSharma := fintechin.MatchesSurname(indPAN, "Sharma")
	fmt.Printf("Matches surname Sharma: %t\n", isSharma) // Output: true

	fmt.Printf("Masked PAN: %s\n", fintechin.MaskPAN(indPAN)) // Output: XXXXX1234X
}
6. UPI Intent URI & QR Code Generation
package main

import (
	"fmt"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	params := fintechin.UPIParams{
		PayeeAddress: "merchant@okhdfcbank",
		PayeeName:    "SuperStore Enterprises",
		Amount:       "1499.50",
		Note:         "Order #98234",
		RefID:        "TXN98234001",
	}

	// Generate compliant NPCI upi://pay URI
	uri, err := fintechin.GenerateUPIURI(params)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("UPI Intent URI / QR Payload:")
	fmt.Println(uri)
	// Output:
	// upi://pay?am=1499.50&cu=INR&pa=merchant%40okhdfcbank&pn=SuperStore+Enterprises&tn=Order+%2398234&tr=TXN98234001
}
7. Financial Year & Advance Tax Schedules
package main

import (
	"fmt"
	"time"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	fy := fintechin.FYFromDate(time.Date(2025, time.August, 15, 0, 0, 0, 0, time.UTC))
	fmt.Printf("Current: %s (%s)\n", fy.Label(), fy.AssessmentYear())
	// Output: Current: FY 2025-26 (AY 2026-27)

	// Statutory advance tax schedule under Section 211
	installments := fy.AdvanceTaxDueDates()
	for _, inst := range installments {
		fmt.Printf("Q%d Due: %s (Cumulative: %d%%)\n",
			inst.Quarter, inst.DueDate.Format("02 Jan 2006"), inst.PercentageCum)
	}
	// Output:
	// Q1 Due: 15 Jun 2025 (Cumulative: 15%)
	// Q2 Due: 15 Sep 2025 (Cumulative: 45%)
	// Q3 Due: 15 Dec 2025 (Cumulative: 75%)
	// Q4 Due: 15 Mar 2026 (Cumulative: 100%)
}
8. Webhook Signature Verification (Razorpay, Cashfree, PhonePe)
package main

import (
	"fmt"
	"time"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	// Razorpay HMAC-SHA256 verification (constant-time)
	if err := fintechin.ValidateRazorpayWebhook(payload, signature, secret); err != nil {
		fmt.Println("Razorpay signature invalid:", err)
	}

	// Cashfree HMAC-SHA256 with replay-attack tolerance window (e.g. 5 minutes)
	if err := fintechin.ValidateCashfreeWebhook(payload, signature, timestampHeader, secret, 5*time.Minute); err != nil {
		fmt.Println("Cashfree signature invalid or expired:", err)
	}

	// PhonePe S2S checksum verification (constant-time)
	if err := fintechin.ValidatePhonePeWebhook(responseBase64, checksum, saltKey, saltIndex); err != nil {
		fmt.Println("PhonePe checksum invalid:", err)
	}
}
9. Indian Bank Branch Resolution (IFSC Lookup)
package main

import (
	"context"
	"fmt"
	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	// Offline resolver: zero heap allocations, no network dependencies
	offline := fintechin.NewOfflineIFSCResolver()
	branch, err := offline.Resolve(context.Background(), "HDFC0000001")
	if err == nil {
		fmt.Printf("Bank: %s, Branch: %s, State: %s\n", branch.Bank, branch.Branch, branch.State)
	}

	// HTTP resolver: queries live Razorpay IFSC directory API with context & timeout
	httpResolver := fintechin.NewHTTPResolver()
	branch, err = httpResolver.Resolve(context.Background(), "SBIN0000691")
	if err == nil {
		fmt.Printf("Live Bank: %s, City: %s\n", branch.Bank, branch.City)
	}
}

Benchmark Performance Summary

All algorithms are optimized for zero or minimal heap allocations. Benchmarks run on standard 64-bit architecture:

Operation Benchmark Target Latency (ns/op) Heap Memory (B/op) Allocations (allocs/op)
Aadhaar Verhoeff D5 Checksum BenchmarkValidateAadhaar ~38 ns/op 0 B/op 0 allocs/op
GSTIN Mod-36 Checksum BenchmarkValidateGSTIN ~51 ns/op 0 B/op 0 allocs/op
PAN Format & Structure BenchmarkValidatePAN ~7 ns/op 0 B/op 0 allocs/op
IFSC Code Validation BenchmarkValidateIFSC ~7 ns/op 0 B/op 0 allocs/op
UPI VPA Validation BenchmarkValidateUPI ~47 ns/op 0 B/op 0 allocs/op
Money Remainder-Safe Split BenchmarkMoneySplit ~28 ns/op 64 B/op 1 allocs/op
Money Proportional Allocate BenchmarkMoneyAllocate ~51 ns/op 96 B/op 2 allocs/op
Currency Format INR (Lakhs/Crores) BenchmarkFormatINR ~24 ns/op 0 B/op 0 allocs/op
Currency Append INR (Zero Alloc) BenchmarkAppendINR ~17 ns/op 0 B/op 0 allocs/op
Currency Parse INR BenchmarkParseINR ~306 ns/op 48 B/op 2 allocs/op
Offline IFSC Resolution BenchmarkOfflineIFSCResolver ~71 ns/op 144 B/op 1 allocs/op
Razorpay Webhook Verification BenchmarkVerifyRazorpayWebhook ~1.7 µs/op 664 B/op 9 allocs/op
Cashfree Webhook Verification BenchmarkVerifyCashfreeWebhook ~2.3 µs/op 776 B/op 12 allocs/op
PhonePe Webhook Verification BenchmarkVerifyPhonePeWebhook ~542 ns/op 192 B/op 4 allocs/op
Number to Indian Words (Legal Cheque) BenchmarkInWords ~530 ns/op 400 B/op 13 allocs/op
Number to Indian Words (Pure Words) BenchmarkNumberToIndianWords ~292 ns/op 240 B/op 8 allocs/op

Statutory Standards & Specifications

Module Governing Body Statutory Standard / Reference
Aadhaar UIDAI Verhoeff Dihedral Group $D_5$ Checksum Algorithm, UIDAI Masking Regulations
GSTIN GSTN / CBIC ISO/IEC 7064:2003 Mod 36,36 Checksum, CGST Rules 2017
PAN Income Tax Dept (CBDT) Section 139A of Income Tax Act 1961, Rule 114 of Income Tax Rules
IFSC / MICR Reserve Bank of India (RBI) RBI National Clearing Cell, RTGS / NEFT Procedural Guidelines
UPI NPCI Unified Payments Interface (UPI) Merchant Specifications & QR Intent Guidelines
Mobile DoT (Telecom) National Numbering Plan (NNP) & ITU-T E.164 Recommendation
Financial Year / Tax CBDT / MoF Section 2(9), Section 208/211 of Income Tax Act 1961
Receivables Aging MCA Companies Act 2013, Schedule III Division I & II

🤖 AI Agent Skills & Multi-Model Context Routing

go-fintech-india includes vendor-neutral Agent Skills (SKILL.md), a root AGENTS.md router, and an AI discovery index (llms.txt / https://abeta-dev.github.io/go-fintech-india/llms.txt) for any LLM coding agent (Antigravity, Gemini CLI, Claude Code, OpenAI Codex, Cursor, Windsurf):

Skill Path Covered Capabilities
go-fintech-india (Umbrella) skills/go-fintech-india/SKILL.md 127-symbol catalog router, zero-dependency invariants, and truth gates
go-fintech-india-money-tax skills/go-fintech-india-money-tax/SKILL.md Exact int64 paise Money, Split, Allocate, Lakh/Crore FormatINR/AppendINR, InWords, FinancialYear, AdvanceTaxDueDates, AgingReport
go-fintech-india-kyc-statutory skills/go-fintech-india-kyc-statutory/SKILL.md ValidateGSTIN (mod-36), ValidatePAN, ValidateAadhaar (Verhoeff D5 & MaskAadhaar), ValidateIFSC + NewOfflineIFSCResolver, ValidateMICR, ValidateMobile, ValidateBankAccount
go-fintech-india-payments-upi skills/go-fintech-india-payments-upi/SKILL.md ValidateUPI, IsKnownPSPHandle, GenerateUPIURI/ParseUPIURI, and constant-time Razorpay/Cashfree/PhonePe webhook verifiers

🌐 Abeta Go Ecosystem

go-fintech-india is part of the Abeta open-source Go engineering ecosystem:

Repository Role Live Documentation Portal Go Reference
github.com/abeta-dev/go-libs 35 foundational Go packages: Gin middleware (ginmw), resilience (retry, circuitbreaker, ratelimit), pgxpool DB helpers, RBAC/JWKS security, OTel telemetry, and type-safe utilities abeta-dev.github.io/go-libs pkg.go.dev/github.com/abeta-dev/go-libs
github.com/abeta-dev/go-fintech-india Zero-dependency Indian FinTech primitives: exact int64 paise math, GSTIN Mod-36, PAN, Aadhaar Verhoeff D5, IFSC/MICR, NPCI UPI URIs, Razorpay/Cashfree/PhonePe webhooks, and Indian FY/Advance Tax calendars abeta-dev.github.io/go-fintech-india pkg.go.dev/github.com/abeta-dev/go-fintech-india
github.com/abeta-dev/go-app-kit Enterprise SaaS application building blocks: transactional outbox, tamper-evident audit logging, multi-channel notifications, CSV/JSON streaming export, and PDF generation abeta-dev.github.io/go-app-kit pkg.go.dev/github.com/abeta-dev/go-app-kit
github.com/abeta-dev/cloud-native-observability Production LGTM observability stack (Loki, Grafana, Tempo, Mimir, OpenTelemetry Collector), SRE SLO alerting rules, and GitOps Terraform blueprints abeta-dev.github.io/cloud-native-observability github.com/abeta-dev/cloud-native-observability

License

MIT License. Copyright (c) 2026 Abeta. See LICENSE for details.

Documentation

Overview

Package fintechin provides a zero-dependency Indian fintech, identity, taxation, banking, and accounting accelerator for Go.

Designed for high-throughput transactional backends, payment gateways, ERPs, neo-banks, and e-commerce platforms operating within the Indian financial ecosystem.

Features & Standards Compliance:

  • Money & Currency: Remainder-safe integer paise financial arithmetic, proportional allocation algorithms, Lakhs & Crores formatting (e.g. ₹12,34,567.89), and legal words representation for cheque printing per Indian banking conventions.
  • Statutory Taxation & Accounting: Indian Financial Year (April 1 to March 31) lifecycle, quarterly advance tax installment schedules (Section 208/211), and MCA Schedule III trade receivables aging bucketing.
  • Identity Verification (UIDAI & Income Tax): Official Verhoeff D5 checksum validation and statutory masking (XXXX-XXXX-1234) for Aadhaar numbers, plus entity type classification (Individual, Company, Firm, Trust, etc.) and structural validation for PAN.
  • Indirect Taxation (GSTN): Full 15-character GSTIN validation with state code lookup (all 37 States and Union Territories) and ISO/IEC 7064 Mod 36,36 checksum.
  • Interbank & Clearing (RBI): 11-character IFSC validation with bank code and branch identification, 9-digit MICR transit code parsing (City, Bank, Branch).
  • Retail Payments (NPCI): UPI Intent QR code and URI generation/parsing, VPA / UPI handle verification, and bank account number masking.
  • Telecom: Indian mobile number validation and E.164 standardization (+91).

All operations are thread-safe, zero external dependency, and strictly rely upon the Go standard library.

Index

Examples

Constants

View Source
const (
	EntityTypeIndividual                PANEntityType = "Individual"
	EntityTypeCompany                   PANEntityType = "Company"
	EntityTypeHUF                       PANEntityType = "HUF"
	EntityTypeFirm                      PANEntityType = "Firm/LLP"
	EntityTypeAOP                       PANEntityType = "AOP"
	EntityTypeTrust                     PANEntityType = "Trust"
	EntityTypeBOI                       PANEntityType = "BOI"
	EntityTypeLocalAuthority            PANEntityType = "Local Authority"
	EntityTypeArtificialJuridicalPerson PANEntityType = "Artificial Juridical Person"
	EntityTypeGovernmentAgency          PANEntityType = "Government Agency"

	// Convenient aliases
	EntityIndividual                = EntityTypeIndividual
	EntityCompany                   = EntityTypeCompany
	EntityHUF                       = EntityTypeHUF
	EntityFirm                      = EntityTypeFirm
	EntityAOP                       = EntityTypeAOP
	EntityTrust                     = EntityTypeTrust
	EntityBOI                       = EntityTypeBOI
	EntityLocalAuthority            = EntityTypeLocalAuthority
	EntityArtificialJuridicalPerson = EntityTypeArtificialJuridicalPerson
	EntityGovernmentAgency          = EntityTypeGovernmentAgency
)

Variables

View Source
var (
	// ErrInvalidAadhaarLength indicates the Aadhaar number is not 12 digits.
	ErrInvalidAadhaarLength = errors.New("aadhaar: number must be exactly 12 digits")
	// ErrInvalidAadhaarFormat indicates the Aadhaar number contains invalid characters.
	ErrInvalidAadhaarFormat = errors.New("aadhaar: number must contain only numeric digits")
	// ErrAadhaarStartsWithZeroOrOne indicates the Aadhaar number starts with 0 or 1, which UIDAI disallows.
	ErrAadhaarStartsWithZeroOrOne = errors.New("aadhaar: number cannot start with 0 or 1")
	// ErrInvalidAadhaarChecksum indicates the Aadhaar number fails the Verhoeff checksum check.
	ErrInvalidAadhaarChecksum = errors.New("aadhaar: invalid verhoeff checksum")
)
View Source
var (
	// ErrInvalidBankAccountLength indicates the bank account number length is not between 9 and 18 digits.
	ErrInvalidBankAccountLength = errors.New("account: bank account number must be between 9 and 18 digits")
	// ErrInvalidBankAccountFormat indicates the account number contains non-digit characters.
	ErrInvalidBankAccountFormat = errors.New("account: bank account number must contain only numeric digits")
	// ErrInvalidBankAccountAllZeros indicates the account number consists entirely of zeros.
	ErrInvalidBankAccountAllZeros = errors.New("account: bank account number cannot be all zeros")
)
View Source
var (
	// ErrInvalidGSTINLength indicates the GSTIN does not have exactly 15 characters.
	ErrInvalidGSTINLength = errors.New("gstin: number must be exactly 15 characters")
	// ErrInvalidGSTINFormat indicates the GSTIN contains invalid characters or does not meet structural rules.
	ErrInvalidGSTINFormat = errors.New("gstin: invalid format, expected 2 digits state + 10 PAN + 1 entity + 'Z' + 1 check character")
	// ErrInvalidStateCode indicates the 2-digit state code is not recognized by GSTN.
	ErrInvalidStateCode = errors.New("gstin: invalid state code")
	// ErrInvalidGSTINChecksum indicates the 15th character does not match the official Mod-36 checksum.
	ErrInvalidGSTINChecksum = errors.New("gstin: invalid checksum character")
)
View Source
var (
	// ErrInvalidIFSCLength indicates the IFSC string does not have length 11.
	ErrInvalidIFSCLength = errors.New("ifsc: code must be exactly 11 characters")
	// ErrInvalidIFSCBankCode indicates the first 4 characters are not alphabetic.
	ErrInvalidIFSCBankCode = errors.New("ifsc: first 4 characters must be uppercase alphabetic bank code")
	// ErrInvalidIFSCFifthChar indicates the 5th character is not '0'.
	ErrInvalidIFSCFifthChar = errors.New("ifsc: 5th character must be '0'")
	// ErrInvalidIFSCBranchCode indicates the last 6 characters are not alphanumeric.
	ErrInvalidIFSCBranchCode = errors.New("ifsc: last 6 characters must be alphanumeric branch code")
)
View Source
var (
	// ErrInvalidMICRLength indicates the MICR code does not have exactly 9 digits.
	ErrInvalidMICRLength = errors.New("micr: code must be exactly 9 digits")
	// ErrInvalidMICRFormat indicates the MICR code contains non-numeric characters.
	ErrInvalidMICRFormat = errors.New("micr: code must contain only numeric digits")
	// ErrInvalidMICRAllZeros indicates the MICR code is all zeros, which is invalid.
	ErrInvalidMICRAllZeros = errors.New("micr: code cannot be all zeros")
)
View Source
var (
	// ErrInvalidPANLength indicates the PAN string does not have length 10.
	ErrInvalidPANLength = errors.New("pan: number must be exactly 10 characters")
	// ErrInvalidPANFormat indicates the PAN does not conform to [A-Z]{5}[0-9]{4}[A-Z]{1}.
	ErrInvalidPANFormat = errors.New("pan: invalid format, must match [A-Z]{5}[0-9]{4}[A-Z]{1}")
	// ErrInvalidPANEntityType indicates the 4th character of PAN is not an acknowledged entity code.
	ErrInvalidPANEntityType = errors.New("pan: invalid entity type character at 4th position")
)
View Source
var (
	// ErrInvalidMobileLength indicates the mobile number does not resolve to 10 digits.
	ErrInvalidMobileLength = errors.New("mobile: number must resolve to exactly 10 digits")
	// ErrInvalidMobileFormat indicates the mobile number contains invalid characters.
	ErrInvalidMobileFormat = errors.New("mobile: number must contain only numeric digits")
	// ErrInvalidMobileStartDigit indicates the mobile number does not begin with DoT allocated blocks (6, 7, 8, or 9).
	ErrInvalidMobileStartDigit = errors.New("mobile: number must start with 6, 7, 8, or 9")
)
View Source
var (
	// ErrInvalidUPIFormat indicates the UPI VPA does not have exactly one '@' character.
	ErrInvalidUPIFormat = errors.New("upi: virtual payment address must contain exactly one '@'")
	// ErrInvalidUPIUsername indicates the UPI username violates NPCI format guidelines.
	ErrInvalidUPIUsername = errors.New("upi: invalid username, must be 1-64 alphanumeric characters, dots, hyphens, or underscores (no consecutive/edge dots)")
	// ErrInvalidUPIHandle indicates the UPI PSP handle violates NPCI format guidelines.
	ErrInvalidUPIHandle = errors.New("upi: invalid handle, must be 2-64 alphanumeric characters")
	// ErrInvalidUPIScheme indicates the URI does not use upi://pay scheme.
	ErrInvalidUPIScheme = errors.New("upi: uri must have scheme 'upi' and authority 'pay'")
	// ErrInvalidUPIMissingPayee indicates mandatory 'pa' parameter is absent.
	ErrInvalidUPIMissingPayee = errors.New("upi: missing mandatory 'pa' (payee address) parameter")
	// ErrInvalidUPICRLF indicates input contains illegal CRLF characters.
	ErrInvalidUPICRLF = errors.New("upi: parameter contains illegal CRLF characters")
	// ErrInvalidUPIAmount indicates the payment amount string is invalid.
	ErrInvalidUPIAmount = errors.New("upi: invalid amount, must be positive decimal with up to 2 decimal places")
)
View Source
var (
	// ErrInvalidSignature indicates a cryptographic signature mismatch on a webhook payload.
	ErrInvalidSignature = errors.New("fintechin: invalid webhook signature")
	// ErrExpiredWebhook indicates that the webhook timestamp exceeds the allowed replay tolerance window.
	ErrExpiredWebhook = errors.New("fintechin: webhook timestamp expired or drifted beyond tolerance")
	// ErrMalformedWebhook indicates a malformed signature, timestamp, or payload structure.
	ErrMalformedWebhook = errors.New("fintechin: malformed webhook payload or signature parameters")
)

AllAgingBuckets returns the standard MCA Schedule III aging buckets in ascending duration order.

View Source
var (
	// ErrBranchNotFound is returned when an IFSC code cannot be resolved to an active branch.
	ErrBranchNotFound = errors.New("fintechin: bank branch not found for IFSC")
)

Functions

func AppendINR

func AppendINR(dst []byte, paise int64) []byte

AppendINR appends the Indian Numbering Format of paise to dst and returns the extended buffer. Performs zero heap allocations when dst has sufficient capacity.

func AppendINRSymbol

func AppendINRSymbol(dst []byte, paise int64) []byte

AppendINRSymbol appends the Indian Numbering Format with Rupee symbol ("₹") to dst. Performs zero heap allocations when dst has sufficient capacity.

func BankCode

func BankCode(ifsc string) string

BankCode extracts the 4-letter bank code prefix from an IFSC code.

func BankNameFromIFSC

func BankNameFromIFSC(ifsc string) string

BankNameFromIFSC returns the full bank name for major Indian banks, or an empty string if unrecognized.

func BranchCode

func BranchCode(ifsc string) string

BranchCode extracts the 6-character branch code suffix from an IFSC code.

func CalculateGSTINChecksum

func CalculateGSTINChecksum(first14 string) (byte, error)

CalculateGSTINChecksum calculates the official GSTN Mod-36 checksum character for the first 14 characters. Employs a weighted Luhn Mod-36 algorithm with alternating factors 1 and 2. Zero heap allocations.

func CalculateVerhoeffCheckDigit

func CalculateVerhoeffCheckDigit(num string) (int, error)

CalculateVerhoeffCheckDigit computes the Verhoeff check digit for any numeric string without allocating.

func ExtractPAN

func ExtractPAN(gstin string) string

ExtractPAN extracts the embedded 10-character PAN from a GSTIN and validates it. Returns the PAN if valid, or an empty string if the GSTIN or embedded PAN is invalid.

func FormatAadhaar

func FormatAadhaar(s string) string

FormatAadhaar formats an Aadhaar string into the standard UIDAI visual pattern "1234 5678 9012".

func FormatE164

func FormatE164(s string) string

FormatE164 formats a valid Indian mobile number into international E.164 format: "+919876543210". Returns an empty string if the input mobile number is invalid.

func FormatINR

func FormatINR(paise int64) string

FormatINR formats integer paise into Indian Numbering Format (e.g. "12,34,567.89" or "-50,000.00"). Optimized to perform only a single heap allocation for the returned string.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	amountPaise := int64(123456789) // ₹12,34,567.89

	// Indian numbering system formatting (Lakhs and Crores grouping)
	formatted := fintechin.FormatINR(amountPaise)
	withSymbol := fintechin.FormatINRSymbol(amountPaise)

	fmt.Printf("Formatted: %s\n", formatted)
	fmt.Printf("With Symbol: %s\n", withSymbol)

}
Output:
Formatted: 12,34,567.89
With Symbol: ₹12,34,567.89

func FormatINRSymbol

func FormatINRSymbol(paise int64) string

FormatINRSymbol formats integer paise with the Indian Rupee symbol (e.g. "₹12,34,567.89", "-₹50,000.00"). Optimized to perform only a single heap allocation for the returned string.

func GenerateUPIURI

func GenerateUPIURI(params UPIParams) (string, error)

GenerateUPIURI constructs a compliant UPI Intent / QR URI ("upi://pay?..."). Enforces: - Valid payee address (pa) - CRLF sanitization across all fields - Safe URL query escaping - Valid decimal amount format if provided - Default currency "INR"

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	uri, err := fintechin.GenerateUPIURI(fintechin.UPIParams{
		PayeeAddress: "merchant@okhdfcbank",
		PayeeName:    "Abeta Store",
		Amount:       "499.50",
		RefID:        "ORD-1001",
		Note:         "Invoice Payment",
	})
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	parsed, _ := fintechin.ParseUPIURI(uri)
	fmt.Printf("URI: %s\n", uri)
	fmt.Printf("Parsed Payee: %s, Amount: %s, Known PSP: %t\n",
		parsed.PayeeAddress, parsed.Amount, fintechin.IsKnownPSPHandle("okhdfcbank"))

}
Output:
URI: upi://pay?am=499.50&cu=INR&pa=merchant%40okhdfcbank&pn=Abeta+Store&tn=Invoice+Payment&tr=ORD-1001
Parsed Payee: merchant@okhdfcbank, Amount: 499.50, Known PSP: true

func InWords

func InWords(m Money) string

InWords converts Money into words according to Indian banking convention. Example: 12345678 paise (Rs 1,23,456.78) -> "Rupees One Lakh Twenty-Three Thousand Four Hundred Fifty-Six and Seventy-Eight Paise Only"

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	// Convert Money (integer paise) to legal words for cheques per Indian banking convention
	amount := fintechin.NewMoney(123456789) // ₹12,34,567.89
	chequeWords := fintechin.InWords(amount)
	fmt.Println(chequeWords)

	// Pure number to Indian words
	numberWords := fintechin.NumberToIndianWords(amount.Rupees())
	fmt.Println(numberWords)

}
Output:
Rupees Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven and Eighty-Nine Paise Only
Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven

func IsKnownPSPHandle

func IsKnownPSPHandle(handle string) bool

IsKnownPSPHandle reports whether the given handle is recognized among major Indian PSP bank handles.

func IsValidAadhaar

func IsValidAadhaar(s string) bool

IsValidAadhaar reports whether the given string is a valid Aadhaar number.

func IsValidBankAccount

func IsValidBankAccount(accountNumber string) bool

IsValidBankAccount reports whether the given string is a valid bank account number.

func IsValidGSTIN

func IsValidGSTIN(s string) bool

IsValidGSTIN reports whether the given string is a valid GSTIN.

func IsValidIFSC

func IsValidIFSC(s string) bool

IsValidIFSC reports whether the given string is a valid IFSC code.

func IsValidMICR

func IsValidMICR(s string) bool

IsValidMICR reports whether the given string is a valid MICR code.

func IsValidMobile

func IsValidMobile(s string) bool

IsValidMobile reports whether the given string is a valid Indian mobile number.

func IsValidPAN

func IsValidPAN(s string) bool

IsValidPAN reports whether the given string is a valid PAN.

func IsValidUPI

func IsValidUPI(vpa string) bool

IsValidUPI reports whether the given string is a valid UPI VPA.

func MICRBankCode

func MICRBankCode(micr string) string

MICRBankCode extracts the 3-digit bank code from a MICR code.

func MICRBranchCode

func MICRBranchCode(micr string) string

MICRBranchCode extracts the 3-digit branch code suffix from a MICR code.

func MICRCityCode

func MICRCityCode(micr string) string

MICRCityCode extracts the 3-digit city code prefix from a MICR code.

func MaskAadhaar

func MaskAadhaar(s string) string

MaskAadhaar returns the masked Aadhaar representation: "XXXX-XXXX-1234". Accepts raw 12 digits or formatted Aadhaar strings.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	raw := "999941057058"
	formatted := "9999 4105 1234"

	fmt.Println(fintechin.MaskAadhaar(raw))
	fmt.Println(fintechin.MaskAadhaar(formatted))

}
Output:
XXXX-XXXX-7058
XXXX-XXXX-1234

func MaskBankAccount

func MaskBankAccount(acc string) string

MaskBankAccount masks an Indian bank account number, hiding all leading digits and revealing only the last 4: e.g. "123456789012" -> "XXXXXXXX9012".

func MaskPAN

func MaskPAN(pan string) string

MaskPAN returns the masked PAN representation "XXXXX1234X" preserving the 4 numeric digits.

func MatchesSurname

func MatchesSurname(pan, surname string) bool

MatchesSurname checks if the 5th character of the PAN matches the first letter of the surname / entity name. Matches case-insensitively.

func NormalizeMobile

func NormalizeMobile(s string) (string, error)

NormalizeMobile cleans an Indian mobile number by removing formatting, "+91", "91" prefix, or leading "0". Returns the clean 10-digit number or an error if invalid.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	clean, err := fintechin.NormalizeMobile("+91 98765-43210")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Printf("Normalized: %s, E.164: %s\n", clean, fintechin.FormatE164(clean))

}
Output:
Normalized: 9876543210, E.164: +919876543210

func NumberToIndianWords

func NumberToIndianWords(n int64) string

NumberToIndianWords converts an integer into words according to Indian numbering convention (Crores, Lakhs, Thousands, Hundreds, Units).

func Quarter

func Quarter(t time.Time) int

Quarter returns the Indian financial quarter (1 to 4) for a given date: Q1: Apr-Jun, Q2: Jul-Sep, Q3: Oct-Dec, Q4: Jan-Mar.

func StateCode

func StateCode(gstin string) string

StateCode extracts the 2-digit state code prefix from a GSTIN.

func StateName

func StateName(stateCode string) (string, error)

StateName returns the Indian State or Union Territory name for a 2-digit GST state code.

func ValidateAadhaar

func ValidateAadhaar(s string) error

ValidateAadhaar validates an Indian Aadhaar number according to UIDAI rules: - Must be exactly 12 numeric digits (accepts raw 12 digits or formatted 14 chars with spaces/hyphens) - Cannot start with 0 or 1 - Must pass the official Verhoeff Dihedral D5 checksum algorithm Zero heap allocations when validating standard 12-digit strings.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	valid := "999941057058"
	invalidChecksum := "999941057059"
	invalidPrefix := "123456789012"

	fmt.Printf("%s valid: %t\n", valid, fintechin.IsValidAadhaar(valid))
	fmt.Printf("%s valid: %t (%v)\n", invalidChecksum, fintechin.IsValidAadhaar(invalidChecksum), fintechin.ValidateAadhaar(invalidChecksum))
	fmt.Printf("%s valid: %t (%v)\n", invalidPrefix, fintechin.IsValidAadhaar(invalidPrefix), fintechin.ValidateAadhaar(invalidPrefix))

}
Output:
999941057058 valid: true
999941057059 valid: false (aadhaar: invalid verhoeff checksum)
123456789012 valid: false (aadhaar: number cannot start with 0 or 1)

func ValidateBankAccount

func ValidateBankAccount(accountNumber string) error

ValidateBankAccount validates an Indian bank account number according to RBI/banking conventions: - Length must be between 9 and 18 numeric digits - Must contain only numeric digits - Cannot be all zeros Zero heap allocations.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	acct := "012345678901"
	fmt.Printf("Valid: %t, Masked: %s\n",
		fintechin.IsValidBankAccount(acct),
		fintechin.MaskBankAccount(acct),
	)

}
Output:
Valid: true, Masked: XXXXXXXX8901

func ValidateCashfreeWebhook

func ValidateCashfreeWebhook(payload []byte, signature, timestamp, secret string, tolerance time.Duration) error

ValidateCashfreeWebhook cryptographically validates a Cashfree webhook payload with replay defense. Returns nil if valid, ErrMalformedWebhook on bad parameters or timestamp format, ErrExpiredWebhook if timestamp drifts beyond tolerance, or ErrInvalidSignature on signature mismatch.

func ValidateGSTIN

func ValidateGSTIN(s string) error

ValidateGSTIN validates a 15-character Goods and Services Tax Identification Number (GSTIN). Checks: 1. Length must be exactly 15 characters 2. First 2 characters must be a recognized GST State Code (01-38, 97, 99) 3. Characters 3-12 must be a valid PAN 4. Character 13 must be alphanumeric (entity registration number) 5. Character 14 must be 'Z' 6. Character 15 must match the official GSTN Mod-36 checksum Zero heap allocations.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	gstin := "29AACCG0527D1Z0"

	// Validate 15-character GSTIN with Mod-36 checksum
	err := fintechin.ValidateGSTIN(gstin)
	fmt.Printf("%s valid: %t\n", gstin, err == nil)

	// State identification from first 2 digits
	stateCode := fintechin.StateCode(gstin)
	stateName, _ := fintechin.StateName(stateCode)
	fmt.Printf("State: %s (%s)\n", stateName, stateCode)

	// Checksum calculation for first 14 characters
	checksum, _ := fintechin.CalculateGSTINChecksum(gstin[:14])
	fmt.Printf("Checksum character: %c\n", checksum)

	// Corrupted checksum validation
	invalidGSTIN := "29AACCG0527D1Z1"
	fmt.Printf("%s valid: %t (%v)\n", invalidGSTIN, fintechin.IsValidGSTIN(invalidGSTIN), fintechin.ValidateGSTIN(invalidGSTIN))

}
Output:
29AACCG0527D1Z0 valid: true
State: Karnataka (29)
Checksum character: 0
29AACCG0527D1Z1 valid: false (gstin: invalid checksum character)

func ValidateIFSC

func ValidateIFSC(s string) error

ValidateIFSC validates an Indian Financial System Code (IFSC) according to RBI guidelines: - Format: exactly 11 characters - Characters 1-4: 4 uppercase letters representing bank - Character 5: Reserved digit '0' - Characters 6-11: 6 alphanumeric characters representing branch Zero heap allocations.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	validIFSC := "SBIN0000001"
	invalidIFSC := "SBIN1000001" // 5th character must be '0'

	fmt.Printf("%s valid: %t\n", validIFSC, fintechin.IsValidIFSC(validIFSC))
	fmt.Printf("Bank: %s (Code: %s)\n", fintechin.BankNameFromIFSC(validIFSC), fintechin.BankCode(validIFSC))
	fmt.Printf("Branch: %s\n", fintechin.BranchCode(validIFSC))

	err := fintechin.ValidateIFSC(invalidIFSC)
	fmt.Printf("%s error: %v\n", invalidIFSC, err)

}
Output:
SBIN0000001 valid: true
Bank: State Bank of India (Code: SBIN)
Branch: 000001
SBIN1000001 error: ifsc: 5th character must be '0'

func ValidateMICR

func ValidateMICR(s string) error

ValidateMICR validates a 9-digit Magnetic Ink Character Recognition (MICR) code used for cheque clearing: - Format: exactly 9 numeric digits - Digits 1-3: City Code (aligned with first 3 digits of PIN code) - Digits 4-6: Bank Code - Digits 7-9: Branch Code - Cannot be all zeros Zero heap allocations.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	micr := "400002021"
	fmt.Printf("Valid: %t (City: %s, Bank: %s, Branch: %s)\n",
		fintechin.IsValidMICR(micr),
		fintechin.MICRCityCode(micr),
		fintechin.MICRBankCode(micr),
		fintechin.MICRBranchCode(micr),
	)

}
Output:
Valid: true (City: 400, Bank: 002, Branch: 021)

func ValidateMobile

func ValidateMobile(s string) error

ValidateMobile validates an Indian 10-digit mobile number according to DoT allocation rules.

func ValidatePAN

func ValidatePAN(s string) error

ValidatePAN validates an Indian Permanent Account Number (PAN) according to Income Tax Department rules. Must match format: [A-Z]{5}[0-9]{4}[A-Z]{1}. Zero heap allocations.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	valid := "ABCDE1234F"
	invalid := "ABCDE12345"

	fmt.Printf("%s valid: %t\n", valid, fintechin.IsValidPAN(valid))
	fmt.Printf("%s valid: %t (%v)\n", invalid, fintechin.IsValidPAN(invalid), fintechin.ValidatePAN(invalid))

}
Output:
ABCDE1234F valid: true
ABCDE12345 valid: false (pan: invalid format, must match [A-Z]{5}[0-9]{4}[A-Z]{1})

func ValidatePhonePeWebhook

func ValidatePhonePeWebhook(responseBase64, checksum, saltKey string, saltIndex int) error

ValidatePhonePeWebhook cryptographically validates a PhonePe server-to-server callback. Returns nil if valid, ErrMalformedWebhook on bad parameters or checksum format, or ErrInvalidSignature if checksum or salt index verification fails.

func ValidateRazorpayWebhook

func ValidateRazorpayWebhook(payload []byte, signature, secret string) error

ValidateRazorpayWebhook cryptographically validates a Razorpay webhook payload. Returns nil if valid, ErrMalformedWebhook if parameters are empty, or ErrInvalidSignature if signature mismatch.

Example
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"strconv"
	"time"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	payload := []byte(`{"event":"payment.captured","payload":{"payment":{"entity":{"id":"pay_123"}}}}`)
	secret := "rzp_webhook_secret_key"

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write(payload)
	sig := hex.EncodeToString(mac.Sum(nil))

	fmt.Printf("Razorpay Verified: %t\n", fintechin.VerifyRazorpayWebhook(payload, sig, secret))

	// Cashfree verification with current timestamp
	ts := strconv.FormatInt(time.Now().Unix(), 10)
	cfMac := hmac.New(sha256.New, []byte(secret))
	cfMac.Write([]byte(ts))
	cfMac.Write(payload)
	cfSig := hex.EncodeToString(cfMac.Sum(nil))
	fmt.Printf("Cashfree Verified: %t\n", fintechin.VerifyCashfreeWebhook(payload, cfSig, ts, secret, 5*time.Minute))

	// PhonePe S2S callback verification
	b64 := "eyJzdWNjZXNzIjp0cnVlLCJjb2RlIjoiUEFZTUVOVF9TVUNDRVNTIiwiZGF0YSI6e319"
	saltKey := "phonepe_salt_key"
	saltIdx := 1
	ppHash := sha256.Sum256([]byte(b64 + saltKey))
	checksum := hex.EncodeToString(ppHash[:]) + "###1"
	fmt.Printf("PhonePe Verified: %t\n", fintechin.VerifyPhonePeWebhook(b64, checksum, saltKey, saltIdx))

}
Output:
Razorpay Verified: true
Cashfree Verified: true
PhonePe Verified: true

func ValidateUPI

func ValidateUPI(vpa string) error

ValidateUPI validates a Virtual Payment Address (VPA) according to NPCI guidelines: - Format: username@handle - Exactly one '@' - Username: 1 to 64 chars [a-zA-Z0-9._-], no consecutive dots, cannot begin or end with dot - Handle: 2 to 64 alphanumeric chars [a-zA-Z0-9] Zero heap allocations.

func VerifyCashfreeWebhook

func VerifyCashfreeWebhook(payload []byte, signature, timestamp, secret string, tolerance time.Duration) bool

VerifyCashfreeWebhook verifies an incoming webhook payload from Cashfree. Cashfree signs webhooks with HMAC-SHA256 over (timestamp + string(payload)). The timestamp parameter is provided in the x-webhook-timestamp header. If tolerance > 0, the timestamp is verified against time.Now() to prevent replay attacks. Both second and millisecond epoch timestamps are supported. Signatures can be base64-encoded or hex-encoded depending on API version.

func VerifyPhonePeWebhook

func VerifyPhonePeWebhook(responseBase64, checksum, saltKey string, saltIndex int) bool

VerifyPhonePeWebhook verifies an incoming server-to-server callback from PhonePe. PhonePe passes a base64-encoded response body and an X-VERIFY header formatted as: SHA256(responseBase64 + saltKey) + "###" + saltIndex. This function verifies both the SHA256 digest and the expected salt index in constant time.

func VerifyRazorpayWebhook

func VerifyRazorpayWebhook(payload []byte, signature, secret string) bool

VerifyRazorpayWebhook verifies an incoming webhook payload from Razorpay. Razorpay signs webhook payloads using HMAC-SHA256 with the webhook secret. The signature header (X-Razorpay-Signature) contains the hex-encoded HMAC hash. This function uses subtle.ConstantTimeCompare to protect against timing attacks.

Types

type AdvanceTaxInstallment

type AdvanceTaxInstallment struct {
	Quarter       int       // 1, 2, 3, or 4
	DueDate       time.Time // Statutory payment deadline
	PercentageCum int       // Cumulative percentage due (15, 45, 75, 100)
}

AdvanceTaxInstallment represents an Indian statutory advance tax installment.

func AdvanceTaxDueDates

func AdvanceTaxDueDates(fy FinancialYear) []AdvanceTaxInstallment

AdvanceTaxDueDates returns the 4 statutory advance tax installments for corporate/non-corporate taxpayers under Section 211 of the Income Tax Act: - June 15: 15% - September 15: 45% - December 15: 75% - March 15: 100%

type AgingBucket

type AgingBucket string

AgingBucket represents a statutory trade receivables aging category under MCA Schedule III.

const (
	Bucket0To30    AgingBucket = "0-30 days"
	Bucket31To60   AgingBucket = "31-60 days"
	Bucket61To90   AgingBucket = "61-90 days"
	Bucket91To180  AgingBucket = "91-180 days"
	BucketAbove180 AgingBucket = ">180 days"
)

func CategorizeAging

func CategorizeAging(dueDate, asOfDate time.Time) AgingBucket

CategorizeAging returns the appropriate MCA Schedule III trade receivables aging bucket based on the invoice dueDate and evaluation asOfDate. Invoices not yet due or overdue by up to 30 days fall into Bucket0To30.

func (AgingBucket) String

func (b AgingBucket) String() string

String returns the human-readable description of the bucket.

type AgingItem

type AgingItem struct {
	InvoiceID string
	DueDate   time.Time
	Amount    Money
	Bucket    AgingBucket
}

AgingItem represents a recorded entry in an AgingReport.

type AgingReport

type AgingReport struct {
	AsOfDate       time.Time
	Bucket0To30    Money
	Bucket31To60   Money
	Bucket61To90   Money
	Bucket91To180  Money
	BucketAbove180 Money
	Total          Money
	Items          []AgingItem
}

AgingReport aggregates trade receivables across statutory aging buckets as of a reference date.

func NewAgingReport

func NewAgingReport(asOfDate time.Time) *AgingReport

NewAgingReport creates a new empty AgingReport with the specified asOfDate.

Example
package main

import (
	"fmt"
	"time"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	asOf := time.Date(2026, time.November, 1, 0, 0, 0, 0, time.UTC)
	report := fintechin.NewAgingReport(asOf)
	report.AddInvoice("INV-01", asOf.AddDate(0, 0, -15), fintechin.NewMoneyFromRupees(10000))
	report.AddInvoice("INV-02", asOf.AddDate(0, 0, -45), fintechin.NewMoneyFromRupees(30000))

	fmt.Printf("Count: %d, Total: ₹%s\n", report.Count(), fintechin.FormatINR(report.TotalAmount().Paise()))
	fmt.Printf("0-30 days: ₹%s, 31-60 days: ₹%s (%.0f%%)\n",
		fintechin.FormatINR(report.BucketAmount(fintechin.Bucket0To30).Paise()),
		fintechin.FormatINR(report.BucketAmount(fintechin.Bucket31To60).Paise()),
		report.Percentage(fintechin.Bucket31To60),
	)

}
Output:
Count: 2, Total: ₹40,000.00
0-30 days: ₹10,000.00, 31-60 days: ₹30,000.00 (75%)

func (*AgingReport) Add

func (r *AgingReport) Add(dueDate time.Time, amount Money)

Add adds an invoice balance to the appropriate aging bucket.

func (*AgingReport) AddInvoice

func (r *AgingReport) AddInvoice(invoiceID string, dueDate time.Time, amount Money)

AddInvoice adds an identified invoice balance to the appropriate aging bucket and logs the item.

func (*AgingReport) BucketAmount

func (r *AgingReport) BucketAmount(bucket AgingBucket) Money

BucketAmount returns the total Money balance in the given aging bucket.

func (*AgingReport) Count

func (r *AgingReport) Count() int

Count returns the number of invoice items added to the report.

func (*AgingReport) Percentage

func (r *AgingReport) Percentage(bucket AgingBucket) float64

Percentage returns the percentage (0.0 - 100.0) of total balance held in the specified bucket.

func (*AgingReport) TotalAmount

func (r *AgingReport) TotalAmount() Money

TotalAmount returns the aggregate balance of all invoices in this report.

type BankBranch

type BankBranch struct {
	IFSC     string `json:"ifsc"`
	Bank     string `json:"bank"`
	BankCode string `json:"bank_code"`
	Branch   string `json:"branch"`
	Address  string `json:"address,omitempty"`
	City     string `json:"city,omitempty"`
	State    string `json:"state,omitempty"`
	MICR     string `json:"micr,omitempty"`
	UPI      bool   `json:"upi,omitempty"`
	RTGS     bool   `json:"rtgs,omitempty"`
	NEFT     bool   `json:"neft,omitempty"`
	IMPS     bool   `json:"imps,omitempty"`
}

BankBranch represents metadata for a specific Indian bank branch.

type FallbackResolver

type FallbackResolver struct {
	// contains filtered or unexported fields
}

FallbackResolver chains a primary IFSCResolver (e.g. HTTP live lookup) with a fallback IFSCResolver (e.g. OfflineIFSCResolver) to provide resilient branch resolution.

func NewFallbackResolver

func NewFallbackResolver(primary, fallback IFSCResolver) *FallbackResolver

NewFallbackResolver constructs an IFSCResolver that first tries primary, and on error tries fallback.

func (*FallbackResolver) Resolve

func (r *FallbackResolver) Resolve(ctx context.Context, ifsc string) (*BankBranch, error)

Resolve attempts to resolve using the primary resolver. If primary fails or is nil, it delegates to the fallback resolver.

type FinancialYear

type FinancialYear struct {
	Year int
}

FinancialYear represents an Indian Financial Year starting on April 1 and ending on March 31. The Year field represents the starting calendar year (e.g. 2024 for FY 2024-25).

func CurrentFY

func CurrentFY() FinancialYear

CurrentFY returns the current Indian Financial Year based on system time.

func FYFromDate

func FYFromDate(t time.Time) FinancialYear

FYFromDate computes the Indian Financial Year for the given time.

Example
package main

import (
	"fmt"
	"time"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	date := time.Date(2026, time.May, 15, 0, 0, 0, 0, time.UTC)
	fy := fintechin.FYFromDate(date)
	fmt.Printf("%s (%s), Quarter: Q%d\n", fy.Label(), fy.AssessmentYear(), fy.Quarter(date))

	for _, inst := range fy.AdvanceTaxDueDates() {
		fmt.Printf("Q%d: %s (%d%%)\n", inst.Quarter, inst.DueDate.Format("2006-01-02"), inst.PercentageCum)
	}

}
Output:
FY 2026-27 (AY 2027-28), Quarter: Q1
Q1: 2026-06-15 (15%)
Q2: 2026-09-15 (45%)
Q3: 2026-12-15 (75%)
Q4: 2027-03-15 (100%)

func ParseFY

func ParseFY(s string) (FinancialYear, error)

ParseFY parses a financial year string into a FinancialYear. Supported formats include "FY 2024-25", "FY2024-25", "2024-25", "2024-2025", "AY 2025-26", and "2024".

func (FinancialYear) AdvanceTaxDueDates

func (fy FinancialYear) AdvanceTaxDueDates() []AdvanceTaxInstallment

AdvanceTaxDueDates returns the 4 statutory advance tax installments for this financial year.

func (FinancialYear) AssessmentYear

func (fy FinancialYear) AssessmentYear() string

AssessmentYear returns the corresponding Indian assessment year label (e.g. "AY 2025-26").

func (FinancialYear) Contains

func (fy FinancialYear) Contains(t time.Time) bool

Contains reports whether the given timestamp falls within this financial year.

func (FinancialYear) EndDate

func (fy FinancialYear) EndDate() time.Time

EndDate returns March 31 00:00:00 UTC of the subsequent calendar year.

func (FinancialYear) Label

func (fy FinancialYear) Label() string

Label returns the Indian financial year label (e.g. "FY 2024-25").

func (FinancialYear) Quarter

func (fy FinancialYear) Quarter(t time.Time) int

Quarter returns the Indian financial year quarter (1 to 4) for a given date: Q1: Apr-Jun, Q2: Jul-Sep, Q3: Oct-Dec, Q4: Jan-Mar.

func (FinancialYear) StartDate

func (fy FinancialYear) StartDate() time.Time

StartDate returns April 1 00:00:00 UTC of the financial year.

type HTTPResolver

type HTTPResolver struct {
	// contains filtered or unexported fields
}

HTTPResolver resolves bank branch information via an external REST API (e.g. Razorpay IFSC API).

func NewHTTPResolver

func NewHTTPResolver(opts ...HTTPResolverOption) *HTTPResolver

NewHTTPResolver creates an IFSC resolver that makes HTTP queries against a live registry.

func (*HTTPResolver) Resolve

func (r *HTTPResolver) Resolve(ctx context.Context, ifsc string) (*BankBranch, error)

Resolve queries the HTTP registry to fetch branch details.

type HTTPResolverOption

type HTTPResolverOption func(*HTTPResolver)

HTTPResolverOption configures an HTTPResolver.

func WithBaseURL

func WithBaseURL(url string) HTTPResolverOption

WithBaseURL configures a custom base URL for the HTTP resolver.

func WithHTTPClient

func WithHTTPClient(client *http.Client) HTTPResolverOption

WithHTTPClient configures a custom *http.Client for the HTTP resolver.

type IFSCResolver

type IFSCResolver interface {
	Resolve(ctx context.Context, ifsc string) (*BankBranch, error)
}

IFSCResolver defines the interface for looking up Indian bank branch metadata from an IFSC code.

type Money

type Money struct {
	// contains filtered or unexported fields
}

Money represents a monetary amount in Indian Rupees stored as integer paise. Exact integer arithmetic is guaranteed: 1 INR = 100 paise.

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	// Create Money from Rupees and Paise
	price := fintechin.NewMoneyFromRupees(500) // ₹500.00 (50000 paise)
	fee := fintechin.NewMoney(2550)            // ₹25.50 (2550 paise)
	discount := fintechin.NewMoneyFromRupees(50)

	// Remainder-safe exact integer arithmetic
	total := price.Add(fee)
	net := total.Sub(discount)

	// String formatting with Rupee symbol and standard decimal
	fmt.Printf("Price: %s\n", price)
	fmt.Printf("Fee: %s\n", fee)
	fmt.Printf("Total: %s (Paise: %d)\n", total, total.Paise())
	fmt.Printf("Net: %s (Paise: %d)\n", net, net.Paise())
	fmt.Printf("Formatted: %s\n", fintechin.FormatINRSymbol(net.Paise()))

}
Output:
Price: 500.00
Fee: 25.50
Total: 525.50 (Paise: 52550)
Net: 475.50 (Paise: 47550)
Formatted: ₹475.50

func NewMoney

func NewMoney(paise int64) Money

NewMoney creates a new Money value from raw integer paise.

func NewMoneyFromFloat

func NewMoneyFromFloat(amount float64) Money

NewMoneyFromFloat creates a new Money value from a float amount in rupees, rounding to the nearest paisa (half away from zero).

func NewMoneyFromRupees

func NewMoneyFromRupees(rupees int64) Money

NewMoneyFromRupees creates a new Money value from whole rupees.

func ParseINR

func ParseINR(s string) (Money, error)

ParseINR parses an Indian Rupee string representation into Money. Supports strings with or without currency symbols ("₹", "Rs.", "Rs", "INR"), commas, negative signs, and decimals (e.g. "₹12,34,567.89", "12,34,567.89", "1234567.89", "-₹50,000.00").

func (Money) Abs

func (m Money) Abs() Money

Abs returns the absolute value of Money.

func (Money) Add

func (m Money) Add(other Money) Money

Add returns m + other.

func (Money) Allocate

func (m Money) Allocate(ratios ...int) ([]Money, error)

Allocate divides m across proportional weights (ratios) without any remainder loss. Remainder paise are distributed to elements with the largest fractional parts (Hare-Niemeyer method).

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	// Splitting ₹100 into a 1:1:1 ratio using Hare-Niemeyer largest remainder method
	total := fintechin.NewMoneyFromRupees(100) // 10000 paise
	shares, err := total.Allocate(1, 1, 1)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	for i, share := range shares {
		fmt.Printf("Share %d: %s\n", i+1, share)
	}

}
Output:
Share 1: 33.34
Share 2: 33.33
Share 3: 33.33

func (Money) Float64

func (m Money) Float64() float64

Float64 returns the monetary amount as float64 rupees.

func (Money) IsNegative

func (m Money) IsNegative() bool

IsNegative reports whether the amount is less than zero.

func (Money) IsPositive

func (m Money) IsPositive() bool

IsPositive reports whether the amount is greater than zero.

func (Money) IsZero

func (m Money) IsZero() bool

IsZero reports whether the amount is zero.

func (Money) MarshalJSON

func (m Money) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting {"paise":12345,"inr":"123.45"}.

func (Money) MarshalText

func (m Money) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Money) Mul

func (m Money) Mul(factor int64) Money

Mul returns m * factor.

func (Money) Negate

func (m Money) Negate() Money

Negate returns the negated Money value.

func (Money) Paise

func (m Money) Paise() int64

Paise returns the amount in paise.

func (Money) Rupees

func (m Money) Rupees() int64

Rupees returns the whole rupees component (truncated toward zero).

func (*Money) Scan

func (m *Money) Scan(src any) error

Scan implements database/sql.Scanner, supporting int64, int32, []byte, string, float64, int.

func (Money) Split

func (m Money) Split(n int) ([]Money, error)

Split splits m into n parts as evenly as possible, distributing remainder paise to the earlier elements so that the sum of parts always equals m.

func (Money) String

func (m Money) String() string

String returns formatted INR with two decimal places (e.g. "123.45" or "-123.45").

func (Money) Sub

func (m Money) Sub(other Money) Money

Sub returns m - other.

func (*Money) UnmarshalJSON

func (m *Money) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, supporting {"paise":...}, raw integer paise, float rupees, or string.

func (*Money) UnmarshalText

func (m *Money) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (Money) Value

func (m Money) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer, returning the integer paise.

type OfflineIFSCResolver

type OfflineIFSCResolver struct{}

OfflineIFSCResolver resolves bank branch information offline using the embedded bank directory. It executes with zero network I/O and zero heap allocations on hot paths.

func NewOfflineIFSCResolver

func NewOfflineIFSCResolver() *OfflineIFSCResolver

NewOfflineIFSCResolver creates an offline IFSC resolver.

func (*OfflineIFSCResolver) Resolve

func (r *OfflineIFSCResolver) Resolve(_ context.Context, ifsc string) (*BankBranch, error)

Resolve validates and decomposes an IFSC code using the local directory.

Example
package main

import (
	"context"
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	resolver := fintechin.NewOfflineIFSCResolver()
	branch, err := resolver.Resolve(context.Background(), "HDFC0000123")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Printf("%s: %s (Branch: %s)\n", branch.IFSC, branch.Bank, branch.Branch)

}
Output:
HDFC0000123: HDFC Bank (Branch: 000123)

type PANEntityType

type PANEntityType string

PANEntityType represents the taxpayer entity type classified by the 4th character of the PAN.

func EntityType

func EntityType(pan string) (PANEntityType, error)

EntityType decodes the entity type from the 4th character of the PAN. 'P' -> Individual 'C' -> Company 'H' -> HUF 'F' -> Firm/LLP 'A' -> AOP 'T' -> Trust 'B' -> BOI 'L' -> Local Authority 'J' -> Artificial Juridical Person 'G' -> Government Agency

Example
package main

import (
	"fmt"

	fintechin "github.com/abeta-dev/go-fintech-india"
)

func main() {
	pans := []string{
		"ABCPE1234F", // P = Individual
		"ABCCE1234F", // C = Company
		"ABCFE1234F", // F = Firm/LLP
		"ABCTE1234F", // T = Trust
	}

	for _, pan := range pans {
		entity, err := fintechin.EntityType(pan)
		if err != nil {
			fmt.Printf("Error: %v\n", err)
			continue
		}
		fmt.Printf("%s: %s\n", pan, entity)
	}

}
Output:
ABCPE1234F: Individual
ABCCE1234F: Company
ABCFE1234F: Firm/LLP
ABCTE1234F: Trust

func EntityTypeFromPAN

func EntityTypeFromPAN(pan string) (PANEntityType, error)

EntityTypeFromPAN is an alias for EntityType.

type UPIParams

type UPIParams struct {
	PayeeAddress string // pa: Payee VPA (mandatory)
	PayeeName    string // pn: Payee Name
	Amount       string // am: Amount (e.g. "150.00")
	Currency     string // cu: Currency code (defaults to "INR")
	Note         string // tn: Transaction note / description
	RefID        string // tr: Transaction reference ID (merchant ref)
	MerchantCode string // mc: Merchant Category Code (4 digits)
	URL          string // url: Transaction reference URL
}

UPIParams encapsulates query parameters for generating and parsing UPI QR / Intent URIs.

func ParseUPIURI

func ParseUPIURI(uriStr string) (UPIParams, error)

ParseUPIURI parses a UPI Intent / QR URI ("upi://pay?...") into UPIParams.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL