Trigger to consult CNPJ in the registration of customers or suppliers in Protheus using ADVPL and the CNPJ.ws API with data from Receita Federal, Sintegra, and Suframa.
Registering customers or suppliers in Protheus can be easier if we consult the CNPJ in the API.
With the integration, we can use the API to query the address, state registration, registration status, CNAE, and many other information that may be important when registering a customer or supplier.
We have already created a class in ADVPL to integrate Protheus with in the post: .
In this post, we will use this ADVPL class to develop a trigger that we will use both in the customer registration and in the supplier registration. Remember that you can use our free API to consult CNPJ, but with a limitation of 3 queries per minute, or you can purchase one of our commercial plans.
Function getCNPJ
Let's start by creating a user function that we will call in our triggers. Note that it receives two parameters:
cTab: SA1 or SA2, indicating whether we are working with customers or suppliers
cCNPJ: the CNPJ number
We also handled the case using the isBlind function in case the trigger is called via execauto, without the user interface. And we used the FWMsgRun function so that the user has visual feedback and not just a "frozen" screen while the process is running.
#include 'totvs.ch'
user function getCNPJ(cTab,cCNPJ)
local aArea:= getArea()
local cRet := ''
default cTab := 'SA1'
default cCNPJ:= ''
cCNPJ:= allTrim(cCNPJ)
if !empty(cTab) .and. len(cCNPJ) == 14
if isBlind()
cRet:= consulta(cTab,cCNPJ)
else
FWMsgRun(,{||cRet:= consulta(cTab,cCNPJ)},'CNPJ.ws','Consultando...')
endif
endif
restArea(aArea)
return cRet
Below is the configuration of the trigger for the A1_CGC field, where we call the user function u_getcnpj passing as parameters SA1 and the CNPJ:
Trigger A2_CGC
Below is the configuration of the trigger for the A2_CGC field, where we call the user function u_getcnpj passing as parameters SA2 and the CNPJ:
Conclusion
See you soon!
Let's create a static function that will be responsible for communicating with . You should review this code carefully to meet your company's needs. Here, I filled in all the fields that came to mind, but feel free to make changes:
The result should be as shown in the gif below. When you type the CNPJ, Protheus will query and automatically fill in the fields:
You can check the source code of this project on , the mentioned class is also in this repository.
To learn more about our plans and payment methods, visit .