/
Afip.js
355 lines (300 loc) · 10.2 KB
/
Afip.js
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
const fs = require('fs');
const path = require('path');
const soap = require('soap');
const axios = require('axios');
const forge = require('node-forge');
const xml2js = require('xml2js');
const Mixpanel = require('mixpanel');
// XML parser
var xmlParser = new xml2js.Parser({
normalizeTags: true,
normalize: true,
explicitArray: false,
attrkey: 'header',
tagNameProcessors: [key => key.replace('soapenv:', '')]
});
// Generic Web Service
const AfipWebService = require('./Class/AfipWebService');
// Available Web Services
const ElectronicBilling = require('./Class/ElectronicBilling');
const RegisterScopeFour = require('./Class/RegisterScopeFour');
const RegisterScopeFive = require('./Class/RegisterScopeFive');
const RegisterScopeTen = require('./Class/RegisterScopeTen');
const RegisterScopeThirteen = require('./Class/RegisterScopeThirteen');
/**
* Software Development Kit for AFIP web services
*
* This release of Afip SDK is intended to facilitate
* the integration to other different web services that
* Electronic Billing
*
* @link http://www.afip.gob.ar/ws/ AFIP Web Services documentation
*
* @author Afip SDK afipsdk@gmail.com
* @package Afip
**/
module.exports = Afip;
function Afip(options = {}){
/**
* File name for the WSDL corresponding to WSAA
*
* @var string
**/
this.WSAA_WSDL;
/**
* The url to get WSAA token
*
* @var string
**/
this.WSAA_URL;
/**
* File name for the X.509 certificate in PEM format
*
* @var string
**/
this.CERT;
/**
* File name for the private key correspoding to CERT (PEM)
*
* @var string
**/
this.PRIVATEKEY;
/**
* Afip resources folder
*
* @var string
**/
this.RES_FOLDER;
/**
* The CUIT to use
*
* @var int
**/
this.CUIT;
// Create an Afip instance if it is not
if (!(this instanceof Afip)) {return new Afip(options)}
// Create an instance of the mixpanel client
/** @private */
this.mixpanel = Mixpanel.init('e87ee11c8cc288e5c5dc213c4d957c7e');
/** @private */
this.mixpanelRegister = {};
this.mixpanelRegister['afip_sdk_library'] = 'javascript';
if (!options.hasOwnProperty('CUIT')) {throw new Error("CUIT field is required in options array");}
// Define default options
if (!options.hasOwnProperty('production')) {options['production'] = false;}
if (!options.hasOwnProperty('cert')) {options['cert'] = 'cert';}
if (!options.hasOwnProperty('key')) {options['key'] = 'key';}
if (!options.hasOwnProperty('res_folder')) {options['res_folder'] = __dirname+'/Afip_res/';}
if (!options.hasOwnProperty('ta_folder')) {options['ta_folder'] = __dirname+'/Afip_res/';}
if (options['production'] !== true) {options['production'] = false;}
this.mixpanelRegister['distinct_id'] = options['CUIT'];
this.mixpanelRegister['production'] = options['production'];
try {
this.mixpanel.track('initialized', Object.assign({}, this.mixpanelRegister, options));
} catch (e) {}
this.options = options;
this.CUIT = options['CUIT'];
this.RES_FOLDER = options['res_folder'];
this.TA_FOLDER = options['ta_folder'];
this.CERT = path.resolve(this.RES_FOLDER, options['cert']);
this.PRIVATEKEY = path.resolve(this.RES_FOLDER, options['key']);
this.WSAA_WSDL = path.resolve(__dirname, 'Afip_res/', 'wsaa.wsdl');
if (options['production']) {
this.WSAA_URL = 'https://wsaa.afip.gov.ar/ws/services/LoginCms';
}
else {
this.WSAA_URL = 'https://wsaahomo.afip.gov.ar/ws/services/LoginCms';
}
this.ElectronicBilling = new ElectronicBilling(this);
this.RegisterScopeFour = new RegisterScopeFour(this);
this.RegisterScopeFive = new RegisterScopeFive(this);
this.RegisterInscriptionProof = new RegisterScopeFive(this);
this.RegisterScopeTen = new RegisterScopeTen(this);
this.RegisterScopeThirteen = new RegisterScopeThirteen(this);
}
/**
* Gets token authorization for an AFIP Web Service
*
* @param service Service for token authorization
* @private
**/
Afip.prototype.GetServiceTA = async function(service, firstTry = true) {
// Declare token authorization file path
const taFilePath = path.resolve(
this.TA_FOLDER,
`TA-${this.options['CUIT']}-${service}${this.options['production'] ? '-production' : ''}.json`
);
// Check if token authorization file exists
const taFileAccessError = await new Promise((resolve) => {
fs.access(taFilePath, fs.constants.F_OK, resolve);
});
// If have access to token authorization file
if (!taFileAccessError) {
const taData = require(taFilePath);
const actualTime = new Date(Date.now() + 600000);
const expirationTime = new Date(taData.header[1].expirationtime);
// Delete TA cache
delete require.cache[require.resolve(taFilePath)];
if (actualTime < expirationTime) {
// Return token authorization
return {
token : taData.credentials.token,
sign : taData.credentials.sign
}
}
}
// Throw error if this is not the first try to get token authorization
if (firstTry === false){
throw new Error('Error getting Token Autorization');
}
// Create token authorization file
await this.CreateServiceTA(service).catch(err => {
throw new Error(`Error getting Token Autorization ${err}`)
});
// Try to get token authorization one more time
return await this.GetServiceTA(service, false);
}
/**
* Create an TA from WSAA
*
* Request to WSAA for a tokent authorization for service
* and save this in a json file
*
* @param service Service for token authorization
**/
Afip.prototype.CreateServiceTA = async function(service) {
const date = new Date();
// Tokent request authorization XML
const tra = (`<?xml version="1.0" encoding="UTF-8" ?>
<loginTicketRequest version="1.0">
<header>
<uniqueId>${Math.floor(date.getTime() / 1000)}</uniqueId>
<generationTime>${new Date(date.getTime() - 600000).toISOString()}</generationTime>
<expirationTime>${new Date(date.getTime() + 600000).toISOString()}</expirationTime>
</header>
<service>${service}</service>
</loginTicketRequest>`).trim();
// Get cert file content
const certPromise = new Promise((resolve, reject) => {
fs.readFile(this.CERT, { encoding:'utf8' }, (err, data) => err ? reject(err) : resolve(data));
});
// Get key file content
const keyPromise = new Promise((resolve, reject) => {
fs.readFile(this.PRIVATEKEY, { encoding:'utf8' }, (err, data) => err ? reject(err) : resolve(data));
});
// Wait for cert and key content
const [cert, key] = await Promise.all([certPromise, keyPromise]);
// Sign Tokent request authorization XML
const p7 = forge.pkcs7.createSignedData();
p7.content = forge.util.createBuffer(tra, "utf8");
p7.addCertificate(cert);
p7.addSigner({
authenticatedAttributes: [{
type: forge.pki.oids.contentType,
value: forge.pki.oids.data,
},
{
type: forge.pki.oids.messageDigest
},
{
type: forge.pki.oids.signingTime,
value: new Date()
}],
certificate: cert,
digestAlgorithm: forge.pki.oids.sha256,
key: key,
});
p7.sign();
const bytes = forge.asn1.toDer(p7.toAsn1()).getBytes();
const signedTRA = Buffer.from(bytes, "binary").toString("base64");
// SOAP Client options
const soapClientOptions = { disableCache:true, endpoint: this.WSAA_URL };
// Create SOAP client
const soapClient = await soap.createClientAsync(this.WSAA_WSDL, soapClientOptions);
// Arguments for soap client request
const loginArguments = { in0: signedTRA };
// Call loginCms SOAP method
const [ loginCmsResult ] = await soapClient.loginCmsAsync(loginArguments)
// Parse loginCmsReturn to JSON
const res = await xmlParser.parseStringPromise(loginCmsResult.loginCmsReturn);
// Declare token authorization file path
const taFilePath = path.resolve(
this.TA_FOLDER,
`TA-${this.options['CUIT']}-${service}${this.options['production'] ? '-production' : ''}.json`
);
// Save Token authorization data to json file
await (new Promise((resolve, reject) => {
fs.writeFile(taFilePath, JSON.stringify(res.loginticketresponse), (err) => {
if (err) {reject(err);return;}
resolve();
});
}));
}
/**
* Track SDK usage
*
* @param string web_service ID of the web service used
* @param string operation SOAP operation called
* @param array params Parameters for the ws
* @private
**/
Afip.prototype.TrackUsage = async function(web_service, operation, params = {}) {
options = {};
if (web_service === 'wsfe' && operation === 'FECAESolicitar') {
if (params['FeCAEReq'] && params['FeCAEReq']['FeCabReq'] && params['FeCAEReq']['FeCabReq']['CbteTipo']) {
options['CbteTipo'] = params['FeCAEReq']['FeCabReq']['CbteTipo'];
}
if (params['FeCAEReq'] && params['FeCAEReq']['FeDetReq'] && params['FeCAEReq']['FeDetReq']['FECAEDetRequest'] && params['FeCAEReq']['FeDetReq']['FECAEDetRequest']['ImpTotal']) {
options['ImpTotal'] = params['FeCAEReq']['FeDetReq']['FECAEDetRequest']['ImpTotal'];
}
}
try {
this.mixpanel.track(web_service+'.'+operation, Object.assign({}, this.mixpanelRegister, options));
} catch (e) {}
if (!this.AdminClient && this.options['production'] === true) {
/** @private */
this.AdminClient = axios.create({
baseURL: 'https://app.afipsdk.com/api/',
timeout: 10000
});
this.AdminClient.defaults.headers.common['sdk-version-number'] = '0.7.8';
this.AdminClient.defaults.headers.common['sdk-library'] = 'javascript';
if (this.options['access_token']) {
this.AdminClient.defaults.headers.common['Authorization'] = `Bearer ${this.options['access_token']}`;
}
try {
await this.AdminClient.post('v1/sdk-events', {
"name": "initialized",
"properties": {
"environment": this.options['production'] === true ? "prod" : "dev",
"tax_id": `${this.options['CUIT']}`,
"afip_sdk_library": "javascript"
}
});
} catch (error) {
if (!error.response) {
throw error;
}
else if (error.response.data && error.response.data.message) {
throw Object.assign(new Error(error.response.data.message), error.response.data);
}
else {
throw Object.assign(new Error(error.response.statusText), error.response);
}
}
}
}
/**
* Create generic Web Service
*
* @param string service Web Service name
* @param array options Web Service options
*
* @return AfipWebService Token Authorization for AFIP Web Service
**/
Afip.prototype.WebService = function (service, options)
{
options['service'] = service;
options['generic'] = true;
return new AfipWebService({ afip: this }, options);
}