Getting started overview

Integrating with Brazil Receita WS involves a structured process that begins with establishing an authenticated identity within the Brazilian government's digital ecosystem. Unlike many commercial APIs that rely on simple API keys, access to Receita Federal services often requires digital certificates (e-CPF or e-CNPJ) or a validated Gov.br account, reflecting the secure nature of tax and fiscal data. The primary objective is to enable programmatic interaction with various services offered by the Receita Federal do Brasil (RFB), such as querying company (CNPJ) or individual (CPF) registration data, managing tax documents, and ensuring fiscal compliance. This guide outlines the essential steps from creating an identity and obtaining credentials to executing your initial API request. Understanding the specific authentication requirements and service endpoints is crucial for a successful integration with the Brazilian tax authorities' systems.

The Receita Federal do Brasil provides a range of web services designed to support businesses and individuals in fulfilling their tax obligations and accessing relevant fiscal information. These services are critical for operations requiring real-time validation of corporate entities or individuals, processing electronic invoices, and managing tax declarations. The foundational requirement for interaction is securing appropriate access credentials, which are tightly coupled with the Brazilian Public Key Infrastructure (ICP-Brasil) for digital certificates or the centralized Gov.br authentication system. For developers, this means preparing an environment capable of handling certificate-based authentication or OAuth 2.0 flows if utilizing newer Gov.br-integrated services. The services themselves are often based on SOAP, though newer initiatives may offer RESTful interfaces, requiring familiarity with both architectural styles.

Create an account and get keys

Access to Brazil Receita WS typically relies on one of two primary authentication methods: digital certificates (e-CPF or e-CNPJ) or a Gov.br account. The choice depends on the specific service you intend to use and whether you are accessing it as an individual or a legal entity.

1. Gov.br Account Creation and Leveling

  1. Access the Gov.br Portal: Navigate to the official Gov.br portal. This is the centralized platform for accessing various Brazilian government services, including those of the Receita Federal.
  2. Create an Account: If you do not have one, register for a new Gov.br account. Follow the on-screen instructions, providing personal identification details.
  3. Increase Account Level: For most Receita Federal services requiring API access, your Gov.br account will need to be at least a Silver or Gold level. This involves additional verification steps, such as biometric facial recognition via the Gov.br app (Silver) or linking to a digital certificate (e-CPF/e-CNPJ) or bank account (Gold). Detailed instructions for increasing your Gov.br account level are available on the portal.
  4. Enable Two-Factor Authentication (2FA): While not strictly an API key, enabling 2FA for your Gov.br account enhances security and may be required for certain higher-level service access.

2. Obtaining Digital Certificates (e-CPF / e-CNPJ)

Digital certificates are the traditional and often most robust method for authenticating with Receita Federal web services, especially for legal entities and complex operations. They are issued by Certification Authorities (ACs) accredited by ICP-Brasil, the Brazilian Public Key Infrastructure. You cannot generate these keys directly through the Receita Federal website; you must purchase and obtain them from a certified provider.

  1. Choose a Certification Authority: Select an ICP-Brasil accredited Certification Authority (e.g., Serasa Experian, Certisign, etc.). A list of accredited CAs is typically found on the ICP-Brasil website or through the Gov.br portal's related sections.
  2. Purchase and Validate: Purchase the appropriate certificate (e-CPF for individuals, e-CNPJ for legal entities). The process involves identity verification, which may include in-person validation or video conferencing, depending on the CA and certificate type.
  3. Install the Certificate: Once issued, install the digital certificate on your system or secure hardware token (e.g., smart card). This typically involves importing a .PFX or .P12 file into your operating system's certificate store. For programmatic access, you'll need to configure your application to use this certificate for SSL/TLS client authentication.

3. API Key Analogs and Service-Specific Access

For some newer or specific services, particularly those integrated with the Gov.br platform, you might encounter more traditional API key or OAuth 2.0 based access. These are less common for core Receita Federal tax services, which prioritize certificate-based authentication for strong non-repudiation. When available, these keys or tokens are generated within the specific service's administrative interface after authentication via Gov.br.

Your first request

After securing your authentication credentials, the next step is to make your first request to Brazil Receita WS. Given the prevalence of SOAP-based services, this example focuses on using a digital certificate for authentication, which is a common scenario. For newer services utilizing Gov.br OAuth, the process would involve obtaining an access token via an OAuth 2.0 flow.

Prerequisites:

  • A valid digital certificate (e-CPF or e-CNPJ) installed on your system.
  • A programming environment capable of making HTTPS requests with client-side certificate authentication (e.g., Python with requests, Java with HttpClient, .NET with HttpClient).
  • Knowledge of the WSDL URL for the specific Receita Federal service you wish to consume. These are often published on specific service pages within the Receita Federal documentation.

Example: Querying CNPJ Data (Illustrative Python Example with SOAP)

This example assumes a hypothetical SOAP web service for querying CNPJ data, using the zeep library in Python, which simplifies SOAP client generation and certificate handling.


import requests
from zeep import Client, Transport
from zeep.exceptions import Fault

# --- Configuration ---
# Replace with the actual WSDL URL for the specific Receita Federal service
WSDL_URL = "https://www.receita.fazenda.gov.br/ws/ConsultaCNPJ.asmx?wsdl" 
# Path to your digital certificate (PFX/P12 file)
CERT_FILE = "/path/to/your/certificate.pfx"
# Password for your digital certificate
CERT_PASSWORD = "your_certificate_password"

# --- Client-side Certificate Authentication ---
# Zeep requires a custom transport to handle client certificates
# requests.Session is used to manage the certificate for HTTP requests

session = requests.Session()
session.verify = True # Verify SSL certificates of the server
session.cert = (CERT_FILE, CERT_PASSWORD) # Client certificate for authentication

transport = Transport(session=session)

# --- Initialize Zeep Client ---
try:
    client = Client(WSDL_URL, transport=transport)
    print("SOAP client initialized successfully.")
except Exception as e:
    print(f"Error initializing SOAP client: {e}")
    exit()

# --- Make your first request (Illustrative example) ---
# The exact method name and parameters depend on the WSDL
# This is a hypothetical call to a 'GetCNPJData' method

try:
    # Example parameters - replace with actual required parameters for your service
    cnpj_number = "00000000000191" # Example CNPJ
    
    # Invoke the web service method
    # Replace 'GetCNPJData' and parameters with the actual method and arguments from the WSDL
    response = client.service.GetCNPJData(CNPJ=cnpj_number)
    
    print("\n--- First Request Successful ---")
    print("Response:")
    print(response)
    
    # Further processing of the response object
    # For example, accessing specific fields:
    # print(f"Company Name: {response.CompanyName}")
    # print(f"Status: {response.Status}")

except Fault as e:
    print(f"\nSOAP Fault Error: {e.message}")
    print("Check your request parameters, authentication, and the service's WSDL documentation.")
except Exception as e:
    print(f"\nAn unexpected error occurred: {e}")
    print("Ensure WSDL URL is correct, certificate is valid, and network connectivity is active.")

Explanation:

  • requests.Session and ssl_context: The requests library is used to manage HTTP connections. For client-side certificate authentication, you configure the session.cert attribute with the path to your .pfx file and its password.
  • zeep.Client: This initializes the SOAP client, pointing to the service's WSDL (Web Services Description Language) URL. The WSDL defines the available operations and their message structures.
  • transport=transport: This tells zeep to use your custom requests.Session for handling the HTTP communication, including the client certificate.
  • client.service.GetCNPJData(...): This line invokes a method on the SOAP web service. The method name and its parameters are dynamically generated by zeep based on the WSDL. You will need to consult the specific Receita Federal service documentation for the exact method names and required input parameters.

For services offering RESTful interfaces or Gov.br OAuth, the process would involve making standard HTTP requests to the defined endpoints, including an Authorization header with a bearer token obtained from the OAuth flow. Refer to the Google OAuth 2.0 documentation for general concepts on OAuth flows, which are often similar across different providers.

Common next steps

After successfully making your first request, consider these common next steps to further your integration with Brazil Receita WS:

  1. Explore Additional Services: The Receita Federal offers a variety of web services beyond basic CNPJ/CPF queries. Investigate other services relevant to your application, such as those for electronic invoicing (NF-e, NFS-e), tax declarations, or specific fiscal compliance checks. Each service will have its own WSDL and documentation.
  2. Error Handling and Logging: Implement robust error handling and logging in your application. Receita Federal web services can return detailed fault messages, and proper logging will aid in debugging and compliance. Pay attention to specific error codes and messages returned by the services.
  3. Production Environment Setup: Transition from development to a production environment. This often involves using production-grade certificates, ensuring secure storage of credentials, and configuring your application for high availability and performance. Review any rate limits or usage policies defined by the Receita Federal.
  4. Security Best Practices: Continuously review and apply security best practices. This includes regularly updating certificates, securing your application's environment, encrypting sensitive data, and adhering to data privacy regulations like the Lei Geral de Proteção de Dados (LGPD) in Brazil.
  5. Stay Updated with Documentation: The Receita Federal documentation for its web services can be updated periodically. Regularly check the official Gov.br and Receita Federal portals for changes to WSDLs, service endpoints, authentication requirements, or new service offerings.
  6. Monitor Service Availability: Implement monitoring for the Receita Federal web services your application depends on. Government services can experience maintenance windows or intermittent issues, and proactive monitoring helps identify and respond to these.
  7. Consider API Gateways: For complex integrations or if you are consuming multiple Receita Federal services, consider using an API gateway (e.g., Kong API Gateway). An API gateway can help manage authentication, rate limiting, logging, and transformation across various services, simplifying your application's interaction layer.

Troubleshooting the first call

Encountering issues during your first call to Brazil Receita WS is common, especially given the specific authentication requirements. Here's a quick reference table and common troubleshooting steps:

Quick Reference Troubleshooting Table

Step What to do Where to check
1. Certificate Validity Verify your digital certificate (e-CPF/e-CNPJ) is valid and not expired. Operating system certificate manager, CA's website.
2. Certificate Password Ensure the certificate password is correct and securely provided to your application. Your application code, secure configuration.
3. WSDL URL Accuracy Confirm the WSDL URL for the specific service is correct and accessible. Official Receita Federal documentation, test in browser.
4. Network Connectivity Check for network issues or firewall blocks preventing access to the service endpoint. Ping/traceroute to service host, firewall rules, proxy settings.
5. Request Parameters Ensure all required parameters in your SOAP request match the WSDL specification. Service's WSDL documentation, your request payload.
6. Gov.br Account Level If using Gov.br authentication, verify your account is at the required Silver/Gold level. Gov.br portal.
7. SSL/TLS Handshake Check for SSL/TLS handshake failures, often related to certificate installation or trust. Application logs, network packet capture (e.g., Wireshark).

Further Troubleshooting Tips:

  • Check Server Status: The Receita Federal may have scheduled maintenance or temporary outages. Check the official Gov.br portal or Receita Federal news for announcements.
  • Detailed Error Messages: Pay close attention to the exact error message received. SOAP faults often contain specific codes or descriptions that point to the root cause. If using a library, enable verbose logging to see the full SOAP request and response XML.
  • Test with a SOAP Client Tool: Use a dedicated SOAP client tool (e.g., SoapUI, Postman with SOAP support) to test the WSDL and make requests independently of your code. This helps isolate whether the issue is with your application logic or the service interaction itself. Configure the client tool with your digital certificate.
  • Review Documentation: Re-read the specific documentation for the Receita Federal web service you are trying to consume. There might be nuances in parameter formatting, data types, or security headers.
  • Certificate Chain Issues: Ensure your system trusts the entire certificate chain of the Receita Federal's SSL certificate. Sometimes, intermediate certificates might be missing from your trust store.
  • Time Synchronization: In rare cases, significant time differences between your server and the Receita Federal server can cause authentication issues with digital certificates. Ensure your system's time is synchronized.