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 ¶
- Constants
- Variables
- func AppendINR(dst []byte, paise int64) []byte
- func AppendINRSymbol(dst []byte, paise int64) []byte
- func BankCode(ifsc string) string
- func BankNameFromIFSC(ifsc string) string
- func BranchCode(ifsc string) string
- func CalculateGSTINChecksum(first14 string) (byte, error)
- func CalculateVerhoeffCheckDigit(num string) (int, error)
- func ExtractPAN(gstin string) string
- func FormatAadhaar(s string) string
- func FormatE164(s string) string
- func FormatINR(paise int64) string
- func FormatINRSymbol(paise int64) string
- func GenerateUPIURI(params UPIParams) (string, error)
- func InWords(m Money) string
- func IsKnownPSPHandle(handle string) bool
- func IsValidAadhaar(s string) bool
- func IsValidBankAccount(accountNumber string) bool
- func IsValidGSTIN(s string) bool
- func IsValidGSTStateCode(code string) bool
- func IsValidIFSC(s string) bool
- func IsValidMICR(s string) bool
- func IsValidMobile(s string) bool
- func IsValidPAN(s string) bool
- func IsValidUPI(vpa string) bool
- func MICRBankCode(micr string) string
- func MICRBranchCode(micr string) string
- func MICRCityCode(micr string) string
- func MaskAadhaar(s string) string
- func MaskBankAccount(acc string) string
- func MaskPAN(pan string) string
- func MatchesSurname(pan, surname string) bool
- func NormalizeMobile(s string) (string, error)
- func NumberToIndianWords(n int64) string
- func Quarter(t time.Time) int
- func StateCode(gstin string) string
- func StateName(stateCode string) (string, error)
- func TDSRateBps(section TDSSection) (int64, error)
- func ValidateAadhaar(s string) error
- func ValidateBankAccount(accountNumber string) error
- func ValidateCashfreeWebhook(payload []byte, signature, timestamp, secret string, tolerance time.Duration) error
- func ValidateGSTIN(s string) error
- func ValidateIFSC(s string) error
- func ValidateMICR(s string) error
- func ValidateMobile(s string) error
- func ValidatePAN(s string) error
- func ValidatePhonePeWebhook(responseBase64, checksum, saltKey string, saltIndex int) error
- func ValidateRazorpayWebhook(payload []byte, signature, secret string) error
- func ValidateUPI(vpa string) error
- func VerifyCashfreeWebhook(payload []byte, signature, timestamp, secret string, tolerance time.Duration) bool
- func VerifyPhonePeWebhook(responseBase64, checksum, saltKey string, saltIndex int) bool
- func VerifyRazorpayWebhook(payload []byte, signature, secret string) bool
- type AdvanceTaxInstallment
- type AgingBucket
- type AgingItem
- type AgingReport
- func (r *AgingReport) Add(dueDate time.Time, amount Money)
- func (r *AgingReport) AddInvoice(invoiceID string, dueDate time.Time, amount Money)
- func (r *AgingReport) BucketAmount(bucket AgingBucket) Money
- func (r *AgingReport) Count() int
- func (r *AgingReport) Percentage(bucket AgingBucket) float64
- func (r *AgingReport) TotalAmount() Money
- type BankBranch
- type FallbackResolver
- type FinancialYear
- func (fy FinancialYear) AdvanceTaxDueDates() []AdvanceTaxInstallment
- func (fy FinancialYear) AssessmentYear() string
- func (fy FinancialYear) Contains(t time.Time) bool
- func (fy FinancialYear) EndDate() time.Time
- func (fy FinancialYear) Label() string
- func (fy FinancialYear) Quarter(t time.Time) int
- func (fy FinancialYear) StartDate() time.Time
- type GSTBreakdown
- type HTTPResolver
- type HTTPResolverOption
- type IFSCResolver
- type Money
- func (m Money) Abs() Money
- func (m Money) Add(other Money) Money
- func (m Money) Allocate(ratios ...int) ([]Money, error)
- func (m Money) Float64() float64
- func (m Money) IsNegative() bool
- func (m Money) IsPositive() bool
- func (m Money) IsZero() bool
- func (m Money) MarshalJSON() ([]byte, error)
- func (m Money) MarshalText() ([]byte, error)
- func (m Money) Mul(factor int64) Money
- func (m Money) Negate() Money
- func (m Money) Paise() int64
- func (m Money) Rupees() int64
- func (m *Money) Scan(src any) error
- func (m Money) Split(n int) ([]Money, error)
- func (m Money) String() string
- func (m Money) Sub(other Money) Money
- func (m *Money) UnmarshalJSON(data []byte) error
- func (m *Money) UnmarshalText(text []byte) error
- func (m Money) Value() (driver.Value, error)
- type OfflineIFSCResolver
- type PANEntityType
- type SupplyType
- type TDSBreakdown
- type TDSSection
- type UPIParams
Examples ¶
- CalculateGST
- CalculateGSTByState
- CalculateTDS
- EntityType
- FYFromDate
- FormatINR
- GenerateUPIURI
- InWords
- MaskAadhaar
- Money
- Money.Allocate
- NewAgingReport
- NormalizeMobile
- OfflineIFSCResolver.Resolve
- ValidateAadhaar
- ValidateBankAccount
- ValidateGSTIN
- ValidateIFSC
- ValidateMICR
- ValidatePAN
- ValidateRazorpayWebhook
Constants ¶
const ( GSTSlab0 int64 = 0 GSTSlab5 int64 = 500 GSTSlab12 int64 = 1200 GSTSlab18 int64 = 1800 GSTSlab28 int64 = 2800 )
Standard Indian GST tax rate slabs expressed in basis points (100 bps = 1.00%).
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 )
const Section206AARateBps int64 = 2000
Section206AARateBps is the statutory higher TDS rate (20.00% = 2000 bps) under Section 206AA of the Income Tax Act when the deductee fails to furnish a valid PAN.
Variables ¶
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") )
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") )
var ( // ErrInvalidGSTRate indicates the GST rate in basis points is outside [0, 10000]. ErrInvalidGSTRate = errors.New("gst: rate in basis points must be between 0 and 10000") // ErrNegativeTaxableAmount indicates the taxable amount in paise is negative. ErrNegativeTaxableAmount = errors.New("gst: taxable amount cannot be negative") )
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") )
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") )
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") )
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") )
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") )
var ( // ErrUnsupportedTDSSection indicates the provided TDSSection is not recognized. ErrUnsupportedTDSSection = errors.New("tds: unsupported statutory TDS section") // ErrNegativeTDSAmount indicates the gross payment amount in paise is negative. ErrNegativeTDSAmount = errors.New("tds: gross payment amount cannot be negative") )
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") )
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") )
var AllAgingBuckets = []AgingBucket{ Bucket0To30, Bucket31To60, Bucket61To90, Bucket91To180, BucketAbove180, }
AllAgingBuckets returns the standard MCA Schedule III aging buckets in ascending duration order.
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 ¶
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 ¶
AppendINRSymbol appends the Indian Numbering Format with Rupee symbol ("₹") to dst. Performs zero heap allocations when dst has sufficient capacity.
func BankNameFromIFSC ¶
BankNameFromIFSC returns the full bank name for major Indian banks, or an empty string if unrecognized.
func BranchCode ¶
BranchCode extracts the 6-character branch code suffix from an IFSC code.
func CalculateGSTINChecksum ¶
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 ¶
CalculateVerhoeffCheckDigit computes the Verhoeff check digit for any numeric string without allocating.
func ExtractPAN ¶
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 ¶
FormatAadhaar formats an Aadhaar string into the standard UIDAI visual pattern "1234 5678 9012".
func FormatE164 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
IsKnownPSPHandle reports whether the given handle is recognized among major Indian PSP bank handles.
func IsValidAadhaar ¶
IsValidAadhaar reports whether the given string is a valid Aadhaar number.
func IsValidBankAccount ¶
IsValidBankAccount reports whether the given string is a valid bank account number.
func IsValidGSTIN ¶
IsValidGSTIN reports whether the given string is a valid GSTIN.
func IsValidGSTStateCode ¶ added in v0.5.0
IsValidGSTStateCode reports whether code is a recognized 2-digit Indian GST State or Union Territory code (01-38, 97, 99).
func IsValidIFSC ¶
IsValidIFSC reports whether the given string is a valid IFSC code.
func IsValidMICR ¶
IsValidMICR reports whether the given string is a valid MICR code.
func IsValidMobile ¶
IsValidMobile reports whether the given string is a valid Indian mobile number.
func IsValidPAN ¶
IsValidPAN reports whether the given string is a valid PAN.
func IsValidUPI ¶
IsValidUPI reports whether the given string is a valid UPI VPA.
func MICRBankCode ¶
MICRBankCode extracts the 3-digit bank code from a MICR code.
func MICRBranchCode ¶
MICRBranchCode extracts the 3-digit branch code suffix from a MICR code.
func MICRCityCode ¶
MICRCityCode extracts the 3-digit city code prefix from a MICR code.
func MaskAadhaar ¶
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 ¶
MaskBankAccount masks an Indian bank account number, hiding all leading digits and revealing only the last 4: e.g. "123456789012" -> "XXXXXXXX9012".
func MaskPAN ¶
MaskPAN returns the masked PAN representation "XXXXX1234X" preserving the 4 numeric digits.
func MatchesSurname ¶
MatchesSurname checks if the 5th character of the PAN matches the first letter of the surname / entity name. Matches case-insensitively.
func NormalizeMobile ¶
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 ¶
NumberToIndianWords converts an integer into words according to Indian numbering convention (Crores, Lakhs, Thousands, Hundreds, Units).
func Quarter ¶
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 StateName ¶
StateName returns the Indian State or Union Territory name for a 2-digit GST state code.
func TDSRateBps ¶ added in v0.5.0
func TDSRateBps(section TDSSection) (int64, error)
TDSRateBps returns the statutory base TDS rate in basis points (100 bps = 1.00%) for a TDSSection.
func ValidateAadhaar ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ValidateMobile validates an Indian 10-digit mobile number according to DoT allocation rules.
func ValidatePAN ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 GSTBreakdown ¶ added in v0.5.0
type GSTBreakdown struct {
TaxableAmount Money
RateBps int64
SellerStateCode string
BuyerStateCode string
SupplyType SupplyType
CGST Money
SGST Money
IGST Money
TotalTax Money
TotalInvoiceAmount Money
}
GSTBreakdown holds the deterministic integer-paise GST tax split (CGST + SGST or IGST) and total invoice amount for a supply.
func CalculateGST ¶ added in v0.5.0
func CalculateGST(taxable Money, rateBps int64, sellerGSTIN, buyerGSTIN string) (GSTBreakdown, error)
CalculateGST validates both sellerGSTIN and buyerGSTIN (including Mod-36 checksums) and computes the deterministic intra-state (CGST + SGST) or inter-state (IGST) tax breakdown.
Example ¶
package main
import (
"fmt"
fintechin "github.com/abeta-dev/go-fintech-india"
)
func main() {
taxable := fintechin.NewMoneyFromRupees(10000) // ₹10,000.00
sellerGSTIN := "29AACCG0527D1Z0" // Karnataka (29)
buyerIntra := "29AACCG0527D1Z0" // Karnataka (29)
buyerInter := "27AACCG0527D1Z4" // Maharashtra (27)
intra, _ := fintechin.CalculateGST(taxable, fintechin.GSTSlab18, sellerGSTIN, buyerIntra)
fmt.Printf("%s: CGST=%s, SGST=%s, IGST=%s, Total=%s\n",
intra.SupplyType, intra.CGST, intra.SGST, intra.IGST, intra.TotalInvoiceAmount)
inter, _ := fintechin.CalculateGST(taxable, fintechin.GSTSlab18, sellerGSTIN, buyerInter)
fmt.Printf("%s: CGST=%s, SGST=%s, IGST=%s, Total=%s\n",
inter.SupplyType, inter.CGST, inter.SGST, inter.IGST, inter.TotalInvoiceAmount)
}
Output: INTRA_STATE: CGST=900.00, SGST=900.00, IGST=0.00, Total=11800.00 INTER_STATE: CGST=0.00, SGST=0.00, IGST=1800.00, Total=11800.00
func CalculateGSTByState ¶ added in v0.5.0
func CalculateGSTByState(taxable Money, rateBps int64, sellerStateCode, buyerStateCode string) (GSTBreakdown, error)
CalculateGSTByState computes the GST tax breakdown (CGST + SGST for intra-state or IGST for inter-state) from a taxable Money amount, a tax rate in basis points (e.g. GSTSlab18 = 1800 for 18%), and 2-digit seller and buyer Indian GST state codes.
Remainder paise on odd total tax amounts in intra-state supplies are assigned to SGST so that CGST + SGST == TotalTax and TaxableAmount + TotalTax == TotalInvoiceAmount with zero paise drift.
Example ¶
package main
import (
"fmt"
fintechin "github.com/abeta-dev/go-fintech-india"
)
func main() {
taxable := fintechin.NewMoneyFromRupees(1000) // ₹1,000.00
breakdown, _ := fintechin.CalculateGSTByState(taxable, fintechin.GSTSlab18, "29", "29")
fmt.Printf("Supply=%s CGST=%s SGST=%s TotalTax=%s\n",
breakdown.SupplyType, breakdown.CGST, breakdown.SGST, breakdown.TotalTax)
}
Output: Supply=INTRA_STATE CGST=90.00 SGST=90.00 TotalTax=180.00
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 NewMoneyFromFloat ¶
NewMoneyFromFloat creates a new Money value from a float amount in rupees, rounding to the nearest paisa (half away from zero).
func NewMoneyFromRupees ¶
NewMoneyFromRupees creates a new Money value from whole rupees.
func ParseINR ¶
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) Allocate ¶
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) IsNegative ¶
IsNegative reports whether the amount is less than zero.
func (Money) IsPositive ¶
IsPositive reports whether the amount is greater than zero.
func (Money) MarshalJSON ¶
MarshalJSON implements json.Marshaler, emitting {"paise":12345,"inr":"123.45"}.
func (Money) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Money) Scan ¶
Scan implements database/sql.Scanner, supporting int64, int32, []byte, string, float64, int.
func (Money) Split ¶
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 ¶
String returns formatted INR with two decimal places (e.g. "123.45" or "-123.45").
func (*Money) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler, supporting {"paise":...}, raw integer paise, float rupees, or string.
func (*Money) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
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 SupplyType ¶ added in v0.5.0
type SupplyType string
SupplyType represents whether a GST supply is Intra-State (CGST + SGST) or Inter-State (IGST).
const ( // SupplyIntraState indicates seller and buyer are in the same Indian State/UT (CGST + SGST). SupplyIntraState SupplyType = "INTRA_STATE" // SupplyInterState indicates seller and buyer are in different Indian States/UTs (IGST). SupplyInterState SupplyType = "INTER_STATE" )
type TDSBreakdown ¶ added in v0.5.0
type TDSBreakdown struct {
GrossAmount Money
Section TDSSection
BaseRateBps int64
EffectiveRateBps int64
Section206AAApplied bool
TDSAmount Money
NetPayable Money
}
TDSBreakdown holds the deterministic integer-paise TDS deduction and net payable amount.
func CalculateTDS ¶ added in v0.5.0
func CalculateTDS(gross Money, section TDSSection, deducteePAN string) (TDSBreakdown, error)
CalculateTDS computes the statutory Tax Deducted at Source (TDS) and net payable amount in exact integer paise. If deducteePAN is missing or fails ValidatePAN, Section 206AA higher withholding (20.00% = 2000 bps) is applied.
Example ¶
package main
import (
"fmt"
fintechin "github.com/abeta-dev/go-fintech-india"
)
func main() {
gross := fintechin.NewMoneyFromRupees(50000) // ₹50,000.00
// Valid PAN: 194J Professional Services (10% = 1000 bps)
withPAN, _ := fintechin.CalculateTDS(gross, fintechin.TDSSection194JProfessional, "ABCDE1234F")
fmt.Printf("With PAN: Rate=%dbps TDS=%s Net=%s 206AA=%t\n",
withPAN.EffectiveRateBps, withPAN.TDSAmount, withPAN.NetPayable, withPAN.Section206AAApplied)
// Missing PAN: Section 206AA higher withholding (20% = 2000 bps)
noPAN, _ := fintechin.CalculateTDS(gross, fintechin.TDSSection194CIndividual, "")
fmt.Printf("No PAN: Rate=%dbps TDS=%s Net=%s 206AA=%t\n",
noPAN.EffectiveRateBps, noPAN.TDSAmount, noPAN.NetPayable, noPAN.Section206AAApplied)
}
Output: With PAN: Rate=1000bps TDS=5000.00 Net=45000.00 206AA=false No PAN: Rate=2000bps TDS=10000.00 Net=40000.00 206AA=true
type TDSSection ¶ added in v0.5.0
type TDSSection string
TDSSection represents an Indian Income Tax Act Section for Tax Deducted at Source (TDS).
const ( // TDSSection194CIndividual is Section 194C for Individual/HUF contractors (1.00% = 100 bps). TDSSection194CIndividual TDSSection = "194C_IND" // TDSSection194COther is Section 194C for Company/Firm/other contractors (2.00% = 200 bps). TDSSection194COther TDSSection = "194C_OTH" // TDSSection194JTechnical is Section 194J for fees for technical services / royalty (2.00% = 200 bps). TDSSection194JTechnical TDSSection = "194J_TECH" // TDSSection194JProfessional is Section 194J for professional services (10.00% = 1000 bps). TDSSection194JProfessional TDSSection = "194J_PROF" // TDSSection194HCommission is Section 194H for commission or brokerage (2.00% = 200 bps). TDSSection194HCommission TDSSection = "194H" // TDSSection194IPlant is Section 194I(a) for rent of plant, machinery, or equipment (2.00% = 200 bps). TDSSection194IPlant TDSSection = "194I_PLANT" // TDSSection194ILandBuilding is Section 194I(b) for rent of land, building, or furniture (10.00% = 1000 bps). TDSSection194ILandBuilding TDSSection = "194I_LAND" // TDSSection194QPurchase is Section 194Q for purchase of goods above statutory threshold (0.10% = 10 bps). TDSSection194QPurchase TDSSection = "194Q" // TDSSection194OECommerce is Section 194O for e-commerce operator payments to participants (0.10% = 10 bps). TDSSection194OECommerce TDSSection = "194O" )
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 ¶
ParseUPIURI parses a UPI Intent / QR URI ("upi://pay?...") into UPIParams.