UNPKG

lhgetnet

Version:

Implementação da API do GETNET

368 lines (334 loc) 12.7 kB
const https = require('https') const querystring = require('querystring'); const zlib = require('zlib'); class LHGetNet { constructor({ client_id, client_secret, seller_id, ambiente=null, debug=false }){ this.client_id = client_id; this.client_secret = client_secret; this.seller_id = seller_id; this.authorization = null; this.debug = debug; switch(ambiente || process.env.NODE_ENV){ case 'development': case 'desenvolvimento': this.baseUrl = 'https://api-sandbox.getnet.com.br'; this.device_url = 'https://h.online-metrix.net/fp/tags.js?org_id=1snn5n9w&session_id='; break; case 'homologation': case 'homologacao': this.baseUrl = 'https://api-homologacao.getnet.com.br'; this.device_url = 'https://h.online-metrix.net/fp/tags.js?org_id=1snn5n9w&session_id='; break; default: // Production this.baseUrl = 'https://api.getnet.com.br'; this.device_url = 'https://h.online-metrix.net/fp/tags.js?org_id=k8vif92e&session_id='; } } getOAuthToken(){ if(this.authorization){ return Promise.resolve(this.authorization); } return this.doApiRequest({ path: '/auth/oauth/v2/token', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: 'Basic ' + Buffer.from(`${this.client_id}:${this.client_secret}`).toString('base64'), }, data: querystring.stringify({ scope: 'oob', grant_type: 'client_credentials' }) }).then( resp => { this.authorization = resp; return resp; }); } tokenizarCartao({ card_number, customer_id }) { return this.getOAuthToken().then(()=>{ return this.doApiRequest({ path: '/v1/tokens/card', data: JSON.stringify({ card_number, customer_id }) }); }); } armazenarCartaoCofre({ number_token, brand, cardholder_name, expiration_month, expiration_year, customer_id, cardholder_identification, verify_card, security_code }) { return this.getOAuthToken().then(()=>{ return this.doApiRequest({ path: '/v1/cards', data: JSON.stringify({ number_token, brand, cardholder_name, expiration_month, expiration_year, customer_id, cardholder_identification, verify_card, security_code }) }); }); } listarCartoesCofre({ customer_id }) { return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'GET', path: `/v1/cards?customer_id=${customer_id}`, }); }); } obterCartaoCofre({ card_id }) { return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'GET', path: `/v1/cards/${card_id}`, }); }); } removerCartaoCofre({ card_id }) { return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'DELETE', path: `/v1/cards/${card_id}`, }); }); } verificarCartao({ number_token, brand, cardholder_name, expiration_month, expiration_year, security_code }) { return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/cards/verification`, data: JSON.stringify({ number_token, brand, cardholder_name, expiration_month, expiration_year, security_code }) }); }); } pagarCartaoCredito({ seller_id, amount, currency="BRL", order, customer, device, shippings=[], credit }) { return this.getOAuthToken().then(()=>{ return this.registerDeviceId({ device_id: device.device_id }); }).then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/credit`, data: JSON.stringify({ seller_id: seller_id || this.seller_id, amount, currency, order, customer, device, shippings, credit }) }); }); } confirmarPagamentoCartaoCredito({ payment_id, amount }){ return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/credit/${payment_id}/confirm`, data: JSON.stringify({ amount }) }); }); } cancelarPagamento({ payment_id, cancel_amount }){ return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/cancel/request`, data: JSON.stringify({ payment_id, cancel_amount }) }); }); } cancelarPagamentoCartaoCredito({ payment_id }){ return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/credit/${payment_id}/cancel`, }); }); } finalizacaoPagamentoAutenticadoCartaoCredito({ payment_id, payer_authentication_response }){ return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/credit/${payment_id}/authenticated/finalize`, data: JSON.stringify({ payer_authentication_response }) }); }); } ajustarValorTransacaoCreditoPreAutorizada({ payment_id, amount, currency="BRL", soft_descriptor, dynamic_mcc }){ return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/credit/${payment_id}/adjustment`, data: JSON.stringify({ amount, currency, soft_descriptor, dynamic_mcc }) }); }); } pagarCartaoDebito({ seller_id, amount, currency="BRL", order, customer, device, shippings=[], debit }) { return this.getOAuthToken().then(()=>{ return this.registerDeviceId({ device_id: device.device_id }); }).then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/debit`, data: JSON.stringify({ seller_id: seller_id || this.seller_id, amount, currency, order, customer, device, shippings, debit }) }); }); } finalizacaoPagamentoAutenticadoCartaoDebito({ payment_id, payer_authentication_response }) { return this.getOAuthToken().then(()=>{ return this.doApiRequest({ method: 'POST', path: `/v1/payments/debit/${payment_id}/authenticated/finalize`, data: JSON.stringify({ payer_authentication_response }) }); }); } doApiRequest({ path, data=null, headers={}, method='POST' }){ const options = { method, headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': "application/json; charset=utf-8", 'Authorization': this.authorization ? `${this.authorization.token_type} ${this.authorization.access_token}` : null, 'seller_id': this.seller_id, ...headers } }; return new Promise((resolve, reject)=>{ const req = https.request(`${this.baseUrl}${path}`, options, res => { res.lhbuffer = []; res.on('data', d => { switch(res.headers["content-encoding"]){ case "gzip": res.lhbuffer.push(zlib.gunzipSync(d)); break; default: res.lhbuffer.push(d); } }); res.on('end', () => { try { let responseData = null; if(res.lhbuffer.length > 0){ responseData = JSON.parse(res.lhbuffer.toString()); } if(res.statusCode <= 299) { resolve(responseData); } else { if(req.debug) { console.log("API PATH:", path); console.log("OPTIONS :", options); console.log("DATA :", data); console.log("REPLY :", responseData); } const error = new Error(`API ERROR [${res.statusCode}] ${res.statusMessage}`); error.code = res.statusCode; error.request_options = options; error.request_data = data; error.data = responseData; reject(error); } } catch ( E ) { reject(E); } }); }); req.debug = this.debug; req.on('error', error => { reject(error); }); if(data){ req.write(data) } req.end(); }); } registerDeviceId({ device_id }){ const options = { method: 'GET', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': "application/json; charset=utf-8" } }; return new Promise((resolve, reject)=>{ console.log("## GETNET REGISTER DEVICE ID:", `${this.device_url}${device_id}`); const req = https.request(`${this.device_url}${device_id}`, options, res => { res.lhbuffer = []; res.on('data', d => { switch(res.headers["content-encoding"]){ case "gzip": res.lhbuffer.push(zlib.gunzipSync(d)); break; default: res.lhbuffer.push(d); } }); res.on('end', () => { try { let responseData = null; if(res.lhbuffer.length > 0){ responseData = res.lhbuffer.toString(); } if(res.statusCode <= 299) { console.log("## GETNET REGISTER DEVICE ID:", res.statusCode, responseData); resolve(responseData); } else { console.log("## GETNET REGISTER DEVICE ID:", res.statusCode, res); const error = new Error(`API ERROR [${res.statusCode}] ${res.statusMessage}`); error.code = res.statusCode; error.request_options = options; error.request_data = data; error.data = responseData; reject(error); } } catch ( E ) { reject(E); } }); }); req.on('error', error => { reject(error); }); req.end(); }); } } module.exports = LHGetNet;