A Go-based microservice that bridges Frappe/ERPNext with the NFe.io API for generating Brazilian electronic invoices (Nota Fiscal EletrΓ΄nica).
This service provides a clean, maintainable bridge between Frappe/ERPNext and the NFe.io API for Brazilian electronic invoice generation. It handles:
- β Complete NFe.io API integration (create, retrieve, cancel, corrections)
- β Brazilian tax calculations (ICMS, PIS, COFINS, IPI, DIFAL)
- β Frappe custom app integration
- β CFOP determination and fiscal rules
- β Address and transport data handling
- β PDF and XML document generation
nfe-go/
βββ cmd/
β βββ main.go # Application entry point
βββ internal/
β βββ handler/
β β βββ invoice_hdl.go # HTTP handlers
β βββ middleware/
β β βββ auth.go # Authentication middleware
β βββ models/
β β βββ frappe.go # Frappe DocType models
β β βββ invoice.go # NFe.io models
β βββ repository/
β β βββ frappe.go # Frappe API client
β β βββ nfeio.go # NFe.io API client
β βββ router/
β β βββ nfeio.go # Route definitions
β βββ service/
β βββ builder.go # CFOP & address building
β βββ issuer.go # Main invoice orchestration
β βββ tax.go # Tax calculation engine
βββ docs/
β βββ frappe_brazil_invoice/ # Frappe custom app (reference)
βββ FRAPPE_INTEGRATION.md # Detailed integration guide
βββ README.md # This file
- Go 1.x or higher
- Access to NFe.io API (API key and Company ID)
- Frappe/ERPNext instance with Brazil Invoice app
- PostgreSQL (optional, for local development)
-
Clone the repository:
git clone https://github.com/AnyGridTech/frappe-nfe-bridge.git cd frappe-nfe-bridge -
Install dependencies:
go mod download
-
Configure environment: Create a
.envfile:# Frappe Configuration FRAPPE_URL=https://your-frappe-site.com FRAPPE_API_KEY=your_api_key FRAPPE_API_SECRET=your_api_secret # NFe.io Configuration NFEIO_API_KEY=your_nfeio_api_key COMPANY_ID=your_company_id NFE_ENDPOINT=https://api.nfe.io/v2/companies/{company_id}/productinvoices NFE_ENDPOINT_CONSULT=https://api.nfe.io/v2/companies/{company_id}/productinvoices # Server Configuration PORT=3000 ENVIRONMENT=development # or production
-
Run the service:
go run cmd/main.go
The service will start on
http://localhost:3000
# Build image
docker build -t nfe-go .
# Run container
docker run -p 3000:3000 --env-file .env nfe-goPOST /issue
Content-Type: application/json
{
"invoice_id": "INV-2025-0001"
}Response:
{
"id": "nfe_io_invoice_id",
"status": "waiting",
"environment": "production",
"flowStatus": "pending",
"pdf": "https://api.nfe.io/.../pdf",
"xml": "https://api.nfe.io/.../xml"
}GET /invoice/:idGET /invoice/:id/pdfGET /invoice/:id/xmlDELETE /invoice/:idPOST /invoice/:id/correction
Content-Type: application/json
{
"correction": "Correction text here"
}βββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP Handlers β
β (invoice_hdl.go) β
ββββββββββββββββββββ¬βββββββββββββββββββββββββββ
β
ββββββββββββββββββββΌβββββββββββββββββββββββββββ
β Issuer Service β
β β’ Orchestrates invoice creation β
β β’ Coordinates between services β
β β’ Maps data between systems β
ββββββββ¬ββββββββββββ¬βββββββββββββββ¬ββββββββββββ
β β β
βββββΌβββββ ββββΌβββββββ βββββΌββββββ
β Tax β β Builder β β Frappe β
βService β β Service β β Repo β
ββββββββββ βββββββββββ βββββββββββ
β
ββββββΌββββββ
β NFe.io β
β Repo β
ββββββββββββ
Main orchestrator that:
- Fetches invoice data from Frappe
- Retrieves tax templates and carrier info
- Maps Frappe data to NFe.io format
- Calculates taxes
- Sends to NFe.io
- Updates Frappe with response
Handles all Brazilian tax calculations:
- ICMS: State tax with various situations (00, 10, 20, 30, 40, 41, 50, 51, 60, 70, 90)
- PIS: Social Integration Program tax
- COFINS: Social Security Financing tax
- IPI: Industrialized Products Tax
- DIFAL: Interstate tax difference for final consumers
Utility functions for:
- CFOP determination based on operation type and location
- Address building and formatting
- Transport information structuring
Frappe API client with methods:
GetInvoice(id)- Fetch invoice dataGetTax(name)- Fetch tax templateGetCarrier(name)- Fetch carrier informationUpdateInvoice(id, data)- Update invoice with NFe.io response
NFe.io API client with 10 methods:
CreateProductInvoice()- Create new invoiceGetInvoice()- Retrieve invoice detailsGetInvoiceByAccessKey()- Query by access keyDeleteInvoice()- Cancel invoiceGetInvoicePDF()- Download PDFGetInvoiceXML()- Download XMLCreateCorrectionLetter()- Create correctionGetCorrectionLetterPDF()- Download correction PDFGetCorrectionLetterXML()- Download correction XML
type Invoices struct {
Name string // INV-YYYY-####
OperationType string // Natureza de OperaΓ§Γ£o
ClientType string // PF or PJ
ClientName string // Nome / RazΓ£o Social
ClientIDNumber string // CPF / CNPJ
ClientEmail string
TaxTemplate string // Link to Tax DocType
Carrier string // Link to Carrier DocType
InvoicesTable []ItemInvoice // Child table with items
// Delivery Address
DeliveryAddress string
DeliveryCEP string
DeliveryState string
City string
// NFe.io Response (auto-filled)
InvoiceID string // NFe.io invoice ID
InvoiceLink string // PDF URL
InvoiceSerie string // Serie number
// Totals
Total float64 // Subtotal
TotalTax float64 // Total with taxes
}The service automatically calculates:
ICMS: Base Calculation Γ (ICMS Rate / 100)
PIS: Base Calculation Γ (PIS Rate / 100)
COFINS: Base Calculation Γ (COFINS Rate / 100)
IPI: Base Calculation Γ (IPI Rate / 100)
Where Base Calculation = Item Value Γ Quantity
-
Install the Frappe app:
cd ~/frappe-bench bench get-app https://github.com/AnyGridTech/frappe_brazil_invoice.git bench --site your-site install-app frappe_brazil_invoice bench migrate
-
Configure site: Add to
site_config.json:{ "nfe_go_api_url": "http://localhost:3000" } -
Restart bench:
bench restart
- Create a new Invoice document
- Fill in client information (CPF/CNPJ, name, email)
- Add delivery address (use CEP lookup for auto-fill)
- Select Tax Template
- Add items to the invoices_table
- Select Carrier (optional)
- Submit the document
- Click "Create NFe Invoice" button
- Wait for success message
- Click "View NFe PDF" to see the generated invoice
- Create NFe Invoice: Sends invoice to NFe.io for processing
- Check NFe Status: Queries current status from NFe.io
- View NFe PDF: Opens generated PDF in new tab
Create tax templates in Frappe with the following structure:
| Field | Description | Example |
|---|---|---|
| ICMS | ||
| CST ICMS | Tax situation code | 00, 10, 20, etc. |
| Aliq ICMS | ICMS rate (%) | 18.00 |
| Origin ICMS | Product origin | 0 (Nacional) |
| IPI | ||
| CST IPI | IPI situation | 50, 99 |
| Aliquota IPI | IPI rate (%) | 10.00 |
| PIS | ||
| CST PIS | PIS situation | 01, 02 |
| Aliquota PIS | PIS rate (%) | 1.65 |
| COFINS | ||
| CST COFINS | COFINS situation | 01, 02 |
| Aliquota COFINS | COFINS rate (%) | 7.60 |
# Run all tests
go test ./...
# Run with coverage
go test -cover ./...
# Run specific package
go test ./internal/serviceUse the provided Postman collection or test manually:
# Health check
curl http://localhost:3000/health
# Create invoice (replace with actual invoice ID from Frappe)
curl -X POST http://localhost:3000/issue \
-H "Content-Type: application/json" \
-d '{"invoice_id": "INV-2025-0001"}'
# Get invoice status
curl http://localhost:3000/invoice/{nfe_io_id}- API authentication using Frappe API keys
- NFe.io API key secured via environment variables
- HTTPS recommended for production
- Token-based auth middleware available
| Variable | Required | Description | Example |
|---|---|---|---|
FRAPPE_URL |
Yes | Frappe site URL | https://mysite.erpnext.com |
FRAPPE_API_KEY |
Yes | Frappe API key | abc123... |
FRAPPE_API_SECRET |
Yes | Frappe API secret | def456... |
NFEIO_API_KEY |
Yes | NFe.io API key | xyz789... |
COMPANY_ID |
Yes | NFe.io company ID | 123456 |
NFE_ENDPOINT |
Yes | NFe.io API endpoint | https://api.nfe.io/v2/... |
PORT |
No | Server port | 3000 (default) |
ENVIRONMENT |
No | Environment | development or production |
The service automatically determines CFOP codes based on:
- Operation type (sale, return, transfer, etc.)
- Location (internal state vs interstate)
- Client type (PF vs PJ)
Common CFOPs:
5101/6101: Sale to consumers5102/6102: Sale for resale5405/6405: Sale of fixed assets5949/6949: Other outbound operations
1. "Could not connect to Go API"
- Check if service is running:
curl http://localhost:3000/health - Verify
nfe_go_api_urlin Frappe config - Check firewall rules
2. "Invalid tax number"
- Ensure CPF has 11 digits (remove formatting)
- Ensure CNPJ has 14 digits (remove formatting)
- Use only numeric characters
3. "Failed to get tax template"
- Verify Tax template exists in Frappe
- Check template name spelling
- Ensure proper permissions
4. NFe.io API errors
- Check API key validity
- Verify company ID is correct
- Check NFe.io service status
- Review NFe.io documentation for error codes
Enable verbose logging:
// In cmd/main.go
app.Use(logger.New(logger.Config{
Format: "[${time}] ${status} - ${method} ${path}\n",
}))- FRAPPE_INTEGRATION.md: Detailed integration guide with architecture, data flow, and field mappings
- QUICK_START.md: Step-by-step setup guide
- ADAPTATION_SUMMARY.md: How legacy code was adapted
- NFEIO_ENHANCEMENT.md: NFe.io API enhancements
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- AnyGridTech Team - Initial work
- NFe.io for the Brazilian electronic invoice API
- Frappe/ERPNext for the excellent ERP framework
- Go community for the amazing tools and libraries
- Issues: GitHub Issues
- Email: support@anygridtech.com
- Documentation: Wiki
- Add support for service invoices (NFSe)
- Implement batch invoice processing
- Add webhook support for NFe.io events
- Create admin dashboard
- Add invoice preview before sending
- Support for multiple companies
- Advanced tax scenario handling
- Integration with other ERP systems
Made with β€οΈ for the Brazilian market by AnyGridTech