-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaeat-nif.go
209 lines (185 loc) · 4.89 KB
/
aeat-nif.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package aeatnif
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"net/http"
"text/template"
"github.com/clbanning/mxj"
)
// VNifV2 object for identification id
type VNifV2 struct {
url string
certFile string
certPassword string
}
// NewVNifV2 create an object to consult oficial identification for spanish government
func NewVNifV2(url string, certFile string, certPassword string) *VNifV2 {
if url == "" {
url = ""
}
return &VNifV2{
url: url,
certFile: certFile,
certPassword: certPassword,
}
}
func generateRequestContent(nif string, name string) string {
type QueryData struct {
NIF string
NAME string
}
const getTemplate = `
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:vnif="http://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/burt/jdit/ws/VNifV2Ent.xsd">
<soapenv:Header/>
<soapenv:Body>
<vnif:VNifV2Ent>
<vnif:Contribuyente>
<vnif:Nif>{{.NIF}}</vnif:Nif>
<vnif:Nombre>{{.NAME}}</vnif:Nombre>
</vnif:Contribuyente>
</vnif:VNifV2Ent>
</soapenv:Body>
</soapenv:Envelope>`
querydata := QueryData{
NIF: nif,
NAME: name,
}
tmpl, err := template.New("requestTemplate").Parse(getTemplate)
if err != nil {
panic(err)
}
var doc bytes.Buffer
err = tmpl.Execute(&doc, querydata)
if err != nil {
panic(err)
}
return doc.String()
}
func convertResults(soapResponse *mxj.Map) (*string, *string, error) {
successStatus, _ := soapResponse.ValueForPath("Envelope.Body.VNifV2Sal.Contribuyente.Resultado")
if successStatus != nil {
success := successStatus.(string) == "IDENTIFICADO"
if success {
xmlNombre, _ := soapResponse.ValueForPath("Envelope.Body.VNifV2Sal.Contribuyente.Nombre")
if xmlNombre == nil {
return nil, nil, errors.New("Contribuyente.Nombre no encontrado")
}
xmlNif, _ := soapResponse.ValueForPath("Envelope.Body.VNifV2Sal.Contribuyente.Nif")
if xmlNif == nil {
return nil, nil, errors.New("Contribuyente.Nif no encontrado")
}
nombreResult := xmlNombre.(string)
nifResult := xmlNif.(string)
return &nombreResult, &nifResult, nil
}
return nil, nil, errors.New("Identificador fiscal o nombre inválido")
}
errorMessage, err := soapResponse.ValueForPath("Envelope.Body.Fault.faultstring") //.#text
if err != nil {
return nil, nil, errors.New("Certificado erróneo o expirado o servicio de la Agencia Tributaria inaccesible" + err.Error())
}
return nil, nil, errors.New(errorMessage.(string))
}
func verify(cert *x509.Certificate) error {
_, err := cert.Verify(x509.VerifyOptions{})
if err == nil {
return nil
}
switch e := err.(type) {
case x509.CertificateInvalidError:
switch e.Reason {
case x509.Expired:
return ErrExpired
default:
return err
}
case x509.UnknownAuthorityError:
// Apple cert isn't in the cert pool
// ignoring this error
return nil
default:
return err
}
}
// SoapCall Call the server to identifycheck if nif and name are valid
func (service *VNifV2) SoapCall(nif string, name string) (*string, *string, error) {
// External certificate
pemByte, err := ioutil.ReadFile(service.certFile)
if err != nil {
return nil, nil, err
}
var pemBlocks []*pem.Block
var v *pem.Block
var pkey []byte
for {
v, pemByte = pem.Decode(pemByte)
if v == nil {
break
}
/* encrypted certificate
if v.Type == "RSA PRIVATE KEY" {
if x509.IsEncryptedPEMBlock(v) {
pkey, _ = x509.DecryptPEMBlock(v, []byte(service.certPassword))
pkey = pem.EncodeToMemory(&pem.Block{
Type: v.Type,
Bytes: pkey,
})
} else {
pkey = pem.EncodeToMemory(v)
}
} else {
pemBlocks = append(pemBlocks, v)
}
*/
if v.Type == "PRIVATE KEY" {
pkey = pem.EncodeToMemory(v)
} else {
pemBlocks = append(pemBlocks, v)
}
}
cert, _ := tls.X509KeyPair(pem.EncodeToMemory(pemBlocks[0]), pkey)
/*err = verify(cert)
if err != nil {
return nil, nil, err
}*/
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
},
}
sRequestContent := generateRequestContent(nif, name)
requestContent := []byte(sRequestContent)
req, err := http.NewRequest("POST", service.url, bytes.NewBuffer(requestContent))
if err != nil {
return nil, nil, err
}
req.Header.Add("SOAPAction", `""`)
req.Header.Add("Content-Type", "text/xml; charset=UTF-8")
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, nil, errors.New("Fallo al llamar a la agencia tributaria " + resp.Status)
}
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, nil, err
}
s := string(contents[:len(contents)])
fmt.Println(s)
m, _ := mxj.NewMapXml(contents, true)
return convertResults(&m)
}
// Certificate errors
var (
ErrExpired = errors.New("El certificado no es válido")
)