|
WSFEv1
Domestic/Local Market Electronic Invoice Docummentation
Phase-Implementation Para documentación en español, ver: http://www.sistemasagiles.com.ar/trac/wiki/ManualPyAfipWs (full user manual - documentation) For information in Spanish see: http://www.sistemasagiles.com.ar/trac/wiki/ProyectoWSFEv1
IntroductionWSFEv1 is the webservice to authorize domestic/local invoices according AFIP (Argentina "IRS") regulations. This webservice allows to authorize an invoice (i.e. get the CAE: Electronic Autorization Code) so it can be sent to the customer. Invoice Class:
AFIP General Resolutions:
Webservice:
PyAfipWs Interface options:
Current Installer:
Installers are for evaluation purposes only (testing - homologation). For production, consult our Commercial Support or see InstalacionCodigoFuente (Source Code Installation Instructions) DetailsMost modern programming languages in windows support COM Automation (a.k.a. Component Object Model, ActiveX DLL, similar to OCX controls) via CreateObject or similar function, and this interface exposes WSAA and WSFEv1 objects to be used directly from legacy programs. Some known supported programming languages so far:
If your programming language doesn't support COM, the interface has a Command Line Tool called RECE1 to perform invoice authorization using text files or DBF tables (see bellow). Visual Basic (5/6) COM ExampleThe following code is a detailed example to explain main features and recommended process and data needed to authorize a valid electronic invoice: ' Workflow example COM Interface with new WSFEv1 AFIP webservice
' As of RG2904 Art. 4 Op. B (without detail)
' 2010 (C) Mariano Reingart <reingart@gmail.com>
' License: GPLv3
Sub Main()
Dim WSAA As Object, WSFEv1 As Object
' Create interface object to the Authentication webservice
Set WSAA = CreateObject("WSAA")
' Generate Access Request Ticket (TRA) for WSFEv1 (same as WSFE)
tra = WSAA.CreateTRA("wsfe")
Debug.Print tra
' Set path to the certificate and private key
Path = CurDir() + "\"
' Certificado: certificate signed by AFIP
' ClavePrivada: private key used to generate CSR
Certificado = "..\..\reingart.crt" ' demo cert, change!
ClavePrivada = "..\..\reingart.key" ' demo pk, change!
' Generate Signed Encrypted Message (CMS)
cms = WSAA.SignTRA(tra, Path + Certificado, Path + ClavePrivada)
Debug.Print cms
' Call webservice to get authentication:
' (URL for testing, change for production)
ta = WSAA.CallWSAA(cms, "https://wsaahomo.afip.gov.ar/ws/services/LoginCms")
' Print Access Ticket (TA) containing Token and Sign
Debug.Print ta
Debug.Print "Token:", WSAA.Token
Debug.Print "Sign:", WSAA.Sign
' Once obtained, token and sign can be used for 12 hours
' (this time lapse can be changed, see TTL parameter at CreateTRA)
' Create interface object to Electronic Invoice webservice
' (note WSFEv1 instead of WSFE)
Set WSFEv1 = CreateObject("WSFEv1")
Debug.Print WSFEv1.version
' Set authentication token and sign to be used at WSFE (from WSAA)
WSFEv1.Token = WSAA.Token
WSFEv1.Sign = WSAA.Sign
' Issuer CUIT (must be registered to the certificate at AFIP)
WSFEv1.Cuit = "20267565393"
' Connect to WSFEv1 webservice
' (parameters will change for production)
ok = WSFEv1.Conectar("") ' testing
' Call dumy service to get server status (optional)
WSFEv1.Dummy
Debug.Print "appserver status", WSFEv1.AppServerStatus
Debug.Print "dbserver status", WSFEv1.DbServerStatus
Debug.Print "authserver status", WSFEv1.AuthServerStatus
' --------------------------------------------------
' MAIN Entry Point (routine to authorize an Invoice):
' --------------------------------------------------
StartCAERequest:
' IMPORTANT:
' Ignore COM errors, so normal execution sequence is not altered
' You must check errors manually reading WSFEv1.Excepcion
' after each method call (not shown in this example!)
' If WSFEv1.Excepcion<>"", an unrecoverable error have occurred
' (connection error, data type mismatch), you must check the source
' and restart the whole process.
On Error Resume Next
' Set te invoice data to authorize (get CAE):
tipo_cbte = 1 ' invoice type 1 : Invoice class A, 6: Invoice class B, etc.
punto_vta = 4001# ' point-of-sale number
' Get last invoice number authorized (like WSFE.RecuperaLastCMP)
cbte_nro = WSFEv1.CompUltimoAutorizado(tipo_cbte, punto_vta)
' Set next invoice number:
' (this is illustrative, in a real system you must have invoice number and amounts in a database!)
cbte_nro = cbte_nro + 1
cbt_desde = cbte_nro
cbt_hasta = cbte_nro
fecha = Format(Date, "yyyymmdd") ' valid format is 20110525 (year, month, day)
concepto = 1 ' concept: 1 products, 2 services, 3 products+services
tipo_doc = 80 ' customer identification type 80: CUIT, 86: CUIL, 96: DNI, 99: Final Consumer
nro_doc = "20267565393" ' customer identification number (CUIT)
imp_total = "122.00" ' total invoice amount
imp_neto = "100.00" ' net amount (for VAT)
imp_iva = "21.00" ' VAT amount
imp_trib = "1.00" ' NEW: other taxes total amount
imp_op_ex = "0.00" ' amount of operations VAT free
imp_tot_conc = "0.00" ' total amount not taxed
fecha_cbte = fecha ' invoice issue date
fecha_venc_pago = fecha ' invoice due date
' Dates of service period (only if concept = 2)
fecha_serv_desde = fecha: fecha_serv_hasta = fecha
' NEW: Currency code and quotation (exchange rate)
moneda_id = "PES"
moneda_ctz = "1.000"
' Create an invoice at the interface
' (internally, at this point, no webservice call is performed)
' This call is similar to WSFE.Aut (original webservice)
' Changes:
' * removed ID: sequence identification no longer used
' * added imp_trib: is the sum of all non VAT taxes
' * added currency
ok = WSFEv1.CrearFactura(concepto, tipo_doc, nro_doc, tipo_cbte, punto_vta, _
cbt_desde, cbt_hasta, imp_total, imp_tot_conc, imp_neto, _
imp_iva, imp_trib, imp_op_ex, fecha_cbte, fecha_venc_pago, _
fecha_serv_desde, fecha_serv_hasta, _
moneda_id, moneda_ctz)
' NEW: Add asociated documents: Invoice numbers in case of credit/debit notes
If tipo_cbte = 2 Or tipo_cbte = 7 Or tipo_cbte = 3 Or tipo_cbte = 8 Then
tipo = 19
pto_vta = 2
nro = 1234
ok = WSFEv1.AgregarCmpAsoc(tipo, pto_vta, nro)
End If
' NEW: Add tax (must be repeated for each non VAT tax: federal, provincial or local)
id = 99 ' tax code (see parameter table)
Desc = "Impuesto Municipal Matanza'" ' tax description
base_imp = "100.00" ' tax net amount
alic = "1.00" ' tax percentage
importe = "1.00" ' tax amount
ok = WSFEv1.AgregarTributo(id, Desc, base_imp, alic, importe)
' NEW: Add VAT tax subtotals (must be repeated for each VAT percentage)
id = 5 ' code for 21% VAT (see parameter table)
base_im = "100.00" ' net amount
importe = "21.00" ' VAT amount
ok = WSFEv1.AgregarIva(id, base_imp, importe)
' NEW: CAE Request (perform webservice remote call)
CAE = WSFEv1.CAESolicitar()
Debug.Print "Resultado", WSFEv1.Resultado
Debug.Print "CAE", WSFEv1.CAE
Debug.Print "Numero de comprobante:", WSFEv1.CbteNro
MsgBox "Result:" & WSFEv1.Resultado & _
" CAE: " & CAE & " Due date: " & WSFEv1.Vencimiento & _
" Obs: " & WSFEv1.obs & _
" ErrMsg:" & WSFEv1.ErrMsg, vbInformation + vbOKOnly
Debug.Print
' Save XML messages for further reference:
Debug.Print WSFEv1.XmlRequest
Debug.Print WSFEv1.XmlResponse
If WSFEv1.Excepcion<>"" Then
MsgBox "Exception:" & WSFEv1.Excepcion
' Save Exception Traceback for degugging:
Debug.Print WSFEv1.Traceback
' optionally, you can go to StartCAERequest
' to try to reprocess the invoice
'(if no data errors were found)
Endif
' NEW: show AFIP events (scheduled maintance, etc.)
For Each evento In WSFEv1.Eventos:
MsgBox evento, vbInformation, "Evento"
Next
' NEW WORKFLOW for error detection and retries:
If WSFEv1.Resultado = "A" Then
InvoiceApproved:
' invoice approved!
' WSFEv1.CAE should have the electronic autorization number
' WSFEv1.Vencimiento should have the electronic autorization number due date
' (see WSFEv1.obs for AFIP messages regarding this invoice as it may be observed)
ElseIf WSFEv1.Resultado = "R" Then
' invoice rejected!
' WSFEv1.CAE and WSFEv1.Vencimiento will be null
' Application shoud discard it or correct its errors
' (see WSFEv1.obs for a detailed error message regarding this invoice)
Else
' Invoice status is undetermined (connection error, AFIP internal error, etc.)
' See WSFEv1.Errores or WSFEv1.ErrMsg for error message
' Must consult AFIP the status of the invoice:
cae2 = WSFEv1.CompConsultar(tipo_cbte, punto_vta, cbte_nro)
If WSFEv1.CAE Then
' invoice was authorized, check invoice data registered at AFIP:
Debug.Print "Invoice Date:", WSFEv1.FechaCbte
Debug.Print "CAE Due Date", WSFEv1.Vencimiento
Debug.Print "Invoice Total amount:", WSFEv1.ImpTotal
' proceed as if WSFEv1.Resultado = "A"
GoTo InvoiceApproved
' (goto is used just to illustrate the point)
Else
' invoice was not authorized, retry this process or discard the invoice
GoTo StartCAERequest
' (goto is used just to illustrate the point)
End If
End If
End SubRECE1 Command Line toolSIAP RECE is an interactive AFIP application to process electronic invoices using text files for legacy programming languages that doesn't support Webservice communication or encryption (but it doesn't uses webservices, so the communication process is cumbersome and the results take some time to arrive). RECE1 is our tool that uses similar files but in a simplified way, no user interaction is required, with the advantage that communication is done instantaneously using webservices, so CAE number is returned immediately, no further process is needed, and can be done in background automatically. RECE1 Command line parameters
RECE1 Configuration File (rece.ini)Before start using RECE1 tool, you must generate your private key and certificate files, and then edit the file RECE.INI in the interface folder (i.e. C:\WSFEv1): Section WSAA:
Section WSFEv1:
Section DBF: configure file name of DBF Tables (if /dbf is used) Sample configuration file (minimal): [WSAA] CERT=homo.crt PRIVATEKEY=homo.key ##URL=https://wsaa.afip.gov.ar/ws/services/LoginCms [WSFEv1] CUIT=30000000000 ENTRADA=entrada.txt SALIDA=salida.txt ##URL=https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL RECE1 UsageSample usage (create a test invoice, show debug messages): C:\WSFEv1>RECE1.EXE /debug /prueba
VERSION 1.29c HOMO True
CONFIG_FILE: rece.ini
wsaa_url https://wsaahomo.afip.gov.ar/ws/services/LoginCms
wsfev1_url None
cuit 20267565393
Autorizando usando entrada: entrada.txt
imp_total='122.0'
tipo_cbte='1'
moneda_ctz='1.0'
fecha_cbte='20110525'
imp_iva='21.0'
nro_doc='30628789661'
iva='[{'iva_id': u'5', 'base_imp': 100.0, 'importe': 21.0}]'
punto_vta='4002'
concepto='1'
cbtes_asoc='[]'
tipo_doc='80'
imp_op_ex='0.0'
tributos='[{'base_imp': 100.0, 'tributo_id': u'99', 'importe': 1.0, 'alic': 1.0, 'desc': u'Impuesto Municipal Matanza'}]'
imp_trib='1.0'
imp_neto='100.0'
cbt_desde='72'
moneda_id='PES'
cbt_hasta='72'
imp_tot_conc='0.0'
fecha_venc_pago=''
Facturar?S
NRO: 72 Resultado: A CAE: 61213036448700 Obs: Err: Reproceso: Normal usage (don't show debug messages nor make test invoice, but save XML files): C:\WSFEv1>RECE1.EXE /xml NRO: 72 Resultado: A CAE: 61213036448700 Obs: Err: Reproceso: S Usage to query last invoice informed to AFIP and recover previously sent invoice data (Tipo de Comprobante: invoice type, Punto de Venta: point of sale, Ultimo numero: last invoice number): C:\WSFEv1>RECE1.EXE /ult Consultar ultimo numero: Tipo de comprobante: 1 Punto de venta: 4002 Ultimo numero: 72 C:\WSFEv1>RECE1.EXE /get Recuperar comprobante: Tipo de comprobante: 1 Punto de venta: 4002 Numero de comprobante: 72 FechaCbte = 20110525 CbteNro = 72 PuntoVenta = 4002 ImpTotal = 122.0 CAE = 61213036448700 Vencimiento = 20110604 EmisionTipo = CAE RECE1 File FormatInput and output files have the same format, only returned fields are completed in the output file (cae, fch_venc_cae, resultado, errmsg, etc.) Important: you must check current format with --formato parameter because you can have a another version with different field structure. Records must be separated by line feed (LF) and/or carriage return (CR) depending the operating system convention. Each record have a type in the first character (0: Invoice Header, 1: Other Taxes, 2: VAT Taxes, 3: Related Invoices): Invoice Header record
Other taxes records (Tributos)
VAT Tax records (IVA)
Related invoice records (Comprobante Asociado)
RECE1 WSFEv1 DBF Table StructureThe Optional DBF structure is similar to text file format exposed before, but each record type is stored in a separate table: Table Encabeza.dbf: Invoice header
Table Tributo.dbf
Table Iva.dbf
Table Comproba.dbf
WSFEv1/RECE1 Parameter TablesThis webservice is parametrized with the following tables: Invoice Types (Tipos de Comprobante)
Concept types (Tipos de Concepto)
Taxpayer document type (Tipos de Documento)
VAT TAX Aliquot/percentage (Alicuotas de IVA)
Currencies (Monedas)
Optional Data (Tipos de datos opcionales)
Other Taxes (Tipos de Tributo)
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||