PyAfipWs: facilitating, extending and releasing AFIP Web Services (Electronic Bill and others)
|
Author: Mariano Reingart Programmer Analyst and Teacher. Enthusiast of Free Software and Python, PostgreSQL and in particular. Blog: http://reingart.blogspot.com Company: http://www.sistemasagiles.com.ar |
Introduction
PyAfipWs <http://www.pyafipws.com.ar/>_ is a free software interface to AFIP Web Services, developed in Python.
It was born around year 2008 in some email exchanges in the mailing list of PyAr!, when with Mr Marcelo Alaniz, consulting about some problems with Python and webservices, we started to build a library adapted to the requirements and environments of AFIP (which by the way, are assorted and no tool in Python worked 100% on them).
The interface was "inspired" in the official examples of AFIP for PHP, which were the simplest ones to understand and closer to another language like Python. There were examples for Java but they were incomplete (some of them had difficulties with dependencies and incompatibilities with XML/SOAP) and in .NET (which were more complete but only for Windows). Anyway, for our taste, these two examples were pretty hard to follow, they used to generate code ("artifacts"), etc. etc.
Additionally, we inspired ourselves from PHP in some libraries of simple management of XML and SOAP, which led to its counterpart in Python because they seemed simple and intuitive.
Initially we developed it for the web services of authentication (electronic signature and others) and electronic bill, but with the passage of time we started to add other AFIP services such as capital goods - electronic tax bonus, export bills, grain traceability code, faithful depositary and the new services for domestic market.
The project has matured and some libraries we develop or adapt have been freed separately:
- PySimpleSoap: for simple yet complete management of webservices
- PyFPDF: for PDF generation in an easier and fluid way.
Both have been integrated in web2py to have a complete framework for developing management web applications.
Electronic bill in Python:
As an example, we will show how to authorize an electronic bill in few lines.
First and foremost an access ticket must be requested (using a certificate and private key previously requested), which will allow us to use the electronic bill web service:
from pyafip.ws import wsaa # create access ticket, sign it and call the ws tra = wsaa.create_tra() cms = wsaa.sign_tra(tra, "homo.crt", "homo.key") ta_xml = call_wsaa(cms, wsaa.WSAAURL)
Behind the scene M2Crypto is used (which is the binding of OpenSSL for encryption in Python), needed to sign the request to access in XML.
From the ticket we extract the Token and Sign (using SimpleXMLElement to analyze and convert the XML in Python objects and data structure), which contain the security codes required in other webservices:
# process xml ta = SimpleXMLElement(ta_xml) token = str(ta.credentials.token) sign = str(ta.credentials.sign)
Once the authentication to access the web services is obtained, shall we proceed to request authorization to emit an electronic bill.
For that we create a connection to the server and call remotely the authorization procedure:
from pyafip.ws import wsfe # create SOAP client client = wsfe.SoapClient(wsfe.WSFEURL, action = wsfe.SOAP_ACTION, namespace = wsfe.SOAP_NS) # authorize electronic bill (obtain CAE) res = wsfe.aut(client, token, sign, CUIT=20234567393, tipo_cbte=1, punto_vta=1, cbt_desde=1, cbt_hasta=1, tipo_doc=80, nro_doc=23111111113, imp_total=121, imp_neto=100, impto_liq=21) print res['cae'], res['motivo']
If everything went well, this will return the CAE (Electronic Authorization Code in Spanish), needed to make the electronic bill.
That would be all for webservices in Python. For generation of the bill (for example in PDF), email delivery and such, see PyRece below.
Legacy languages
Beyond the applications in Python, this library is compatible with languages such as Visual Basic, ASP, Fox Pro, Cobol, Delphi, Genexus, PowerBuilder, PHP, .Net, Java, ABAP (SAP), etc. and with any language/application capable of creating Component Object Model in Windows (for example Excel or Access).
This is easily accomplished using PythonCOM (part of the win32 extensions), wrapping a common class of python to be exposed to other applications, defining the methods and public attributes, the exposed name and other, for example:
class WSAA: "Interface to the WebService of Authentication and Authorization" _public_methods_ = ['CreateTRA', 'SignTRA', 'CallWSAA'] _public_attrs_ = ['Token', 'Sign', 'Version', 'XmlResponse'] _readonly_attrs_ = _public_attrs_ _reg_progid_ = "WSAA" _reg_clsid_ = "{6268820C-8900-4AE9-8A2D-F0A1EBD4CAC5}"
Once the interface is registered, it can be called from any other application with this technology, for example, in Visual Basic it would be:
Set WSAA = CreateObject("WSAA")
tra = WSAA.CreateTRA()
cms = WSAA.SignTRA(tra, "homo.crt", "homo.key")
ta = WSAA.CallWSAA(cms, url)
Set WSFE = CreateObject("WSFE")
WSFE.Token = WSAA.Token ' set token and sign of wsaa
WSFE.Sign = WSAA.Sign
WSFE.Cuit = "3000000000" ' issuer CUIT
ok = WSFE.Conectar(url)
cae = WSFE.Aut(id, presta_serv, tipo_doc, ...
imp_tot_conc, imp_neto, impto_liq, ...)
In our case this was very useful and made possible to many applications contemplate these new features (webservices, encryption, etc.) with minor modifications, which otherwise would have been difficult or even impossible.
Text Files and Command Line
Even though the COM interface is very useful for relatively modern applications, there are still very difficult to access languages or environments, where practically the only way of interoperatibility are text files.
Languages as Cobol handle files with fields of fixed length (this was already supported by the RECE of SIAP app), we went down that road, which with Python was quite straightforward.
The interface includes tools like RECE.PY and RECEX.PY which receive and process input files by command line, saving results in output files. This behavior es controlled by a configuration file (RECE.INI) which defines URLs, certificates and paths to use.
PyRece: free SIAP?
The history doesn't end here, some difficulties of the RECE Application or the online services to make electronic bills (limited functionality, delays or complexities, etc., especially for the contributors that do not posess management system) have been seen, we developed a visual application ("desktop") to facilitate and extend the possibilities brought by AFIP:
User interface is a simple screen but it contemplates:
- CSV spreadsheet reading (instead of fixed width file)
- Real-time online Authentication and Authorisation
- Customised PDF generation (texts, logos, lines, etc.) with picture of the bill
- Email delivery to the customer of the PDF (with a brief configurable message)
All these features are not available (together) in the application or web site of AFIP (some of them can be done with limitations, but not in an agile and transparent way).
This application turns to show that PyRece has a concrete possibility of being developed in Python with a free Integrated Applications System (SIAP), in this case as alternative to the RECE application of electronic bill, but there are other cases where the same could have been done if web services were available (eg, IVA for DD.JJ., SICOSS for social security, etc.).
FE.py
Finally, we developed a tool that unifies the different webservices (national electronic bill, export, capital goods, etc.) and integrates all the aforementioned, using a database to store and exchange the information, generating the bills in PDF, enabling them to load from and to text files, deliver by email or FTP, amongst others.
In general it uses PostgreSQL, but other databases can be used (PyOBDC or SqLite).
The Project
Finalizing the article, we have included some comments about how the project was developed.
An already solved topic was the business model, especially knowing that there are other closed alternatives and we decided to keep ourselves in the path of free software, finding the right combination to be able to compete was not a minor issue.
For those who don't know Python and are eager to evaluate the interface, we provide an installer with a fully functional demo for testing environments. We offer paid commercial support for those who need to ask questions, request corrections and adjustments and want to have access to the installer for production environments and upcoming updates we might release.
All the source code is published in the repository of GoogleCode under GPL3 license, with all the needed scripts and installation instructions.
We think the result was quite satisfactory, allowing to extend and support financially the project, contributing to free software and the community with alternative and powerful tools, and beginning to create a developers group interested in the topic.
The interface has thousands of downloads from the project's web site, and many important companies hired us for commercial support.
This has not been done entirely without setbacks or effort, therefore to finalize there are some comments and recommendations:
- Installers and packages were critical to make people able to evaluate the products, especially for not widely spread technologies like Python, and mainly for Windows, which has been the largest market for this interface.
- Documentation and examples were another strong spot, and the experience says that is a constantly deepen topic, even in cases that it seems to be enough (we include frequently asked questions, code snippets, important remarks, etc.)
- Training curses and workshops are also very productive (we have had 2 in the ACP, to whom we are thankful), allowing to dig deeper on the topic and meet the interested people.
- For the dissemination we've been helped by blogs, news, free software events, etc. As the project appeared in the search engines, its popularity and real utility for the users grew.
- The community support in our case was not effective, mailing list and ticketing/issues systems were not heavily used, neither were there a lot of contributions or source code revisions, maybe for the sensitive and/or particular character of the topic (although the phisolophy of free software has not been widely spread in some environments).
We hope this article will be useful for a general overview of the topic, any additional information might you need can be found in the following addresses:
- Web site of the project: www.pyafipws.com.ar
- Newsgroup: groups.google.com.ar/group/pyafipws
- Commercial support and Documentation: www.sistemasagiles.com.ar/trac/wiki/PyAfipWs
- Minisite AFIP electronic bill: www.afip.gov.ar/fe
Help PET: Donate
blog comments powered by Disqus