Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lgaticaq committed Mar 28, 2016
0 parents commit 3555157
Show file tree
Hide file tree
Showing 16 changed files with 443 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
28 changes: 28 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Logs
logs
*.log

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
lib
1 change: 1 addition & 0 deletions .node-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v5
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
src
.*
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v5
7 changes: 7 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
language: node_js
node_js:
- "0.12"
- "4"
- "5"
notifications:
email: false
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2016 Leonardo Gatica

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# tbk-oneclick

[![npm version](https://img.shields.io/npm/v/tbk-oneclick.svg?style=flat-square)](https://www.npmjs.com/package/tbk-oneclick)
[![npm downloads](https://img.shields.io/npm/dm/tbk-oneclick.svg?style=flat-square)](https://www.npmjs.com/package/tbk-oneclick)
[![Build Status](https://img.shields.io/travis/lgaticaq/tbk-oneclick.svg?style=flat-square)](https://travis-ci.org/lgaticaq/tbk-oneclick)
[![dependency Status](https://img.shields.io/david/lgaticaq/tbk-oneclick.svg?style=flat-square)](https://david-dm.org/lgaticaq/tbk-oneclick#info=dependencies)
[![devDependency Status](https://img.shields.io/david/dev/lgaticaq/tbk-oneclick.svg?style=flat-square)](https://david-dm.org/lgaticaq/tbk-oneclick#info=devDependencies)
[![Join the chat at https://gitter.im/lgaticaq/tbk-oneclick](https://img.shields.io/badge/gitter-join%20chat%20%E2%86%92-brightgreen.svg?style=flat-square)](https://gitter.im/lgaticaq/tbk-oneclick?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Node Implementation of Transbank Oneclick API SOAP

Inspired by https://github.com/cornershop/python-oneclick

## Installation

```bash
npm i -S tbk-oneclick
```
83 changes: 83 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
{
"name": "tbk-oneclick",
"version": "0.0.1",
"description": "Node Implementation of Transbank Oneclick API SOAP",
"main": "lib",
"scripts": {
"prepublish": "npm run build -s",
"prebuild": "npm run lint -s && npm run clean -s",
"build": "babel src --out-dir lib --source-maps",
"lint": "eslint src",
"clean": "rimraf lib",
"pretest": "npm run build -s",
"test": "mocha --compilers js:babel-core/register"
},
"engines": {
"node": ">=0.12"
},
"repository": {
"type": "git",
"url": "https://github.com/lgaticaq/tbk-oneclick.git"
},
"keywords": [
"tbk",
"oneclick",
"soap",
"transbank"
],
"author": "Leonardo Gatica <lgatica@protonmail.com> (https://about.me/lgatica)",
"license": "MIT",
"bugs": {
"url": "https://github.com/lgaticaq/tbk-oneclick/issues"
},
"homepage": "https://github.com/lgaticaq/tbk-oneclick#readme",
"dependencies": {
"moment": "^2.12.0",
"node-forge": "^0.6.39",
"soap": "^0.13.0"
},
"devDependencies": {
"babel-cli": "^6.6.5",
"babel-core": "^6.7.4",
"babel-preset-es2015": "^6.6.0",
"chai": "^3.5.0",
"eslint": "2.5.1",
"mocha": "^2.4.5",
"rimraf": "^2.5.2",
"xml2js": "^0.4.16"
},
"eslintConfig": {
"env": {
"es6": true,
"node": true,
"mocha": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
2,
2
],
"linebreak-style": [
2,
"unix"
],
"quotes": [
2,
"single"
],
"semi": [
2,
"always"
]
}
},
"babel": {
"presets": [
"es2015"
]
}
}
34 changes: 34 additions & 0 deletions src/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

import soap from 'soap';
import {Response} from './response';

export class Client {

constructor(testing=false) {
this._testing = testing;
const testingLoc = 'https://tbk.orangepeople.cl/webpayserver/wswebpay/OneClickPaymentService';
const productionLoc = 'https://webpay3g.transbank.cl:443/webpayserver/wswebpay/OneClickPaymentService';
this.location = testing ? testingLoc : productionLoc;
this.client = this.createClient();
}

createClient(cb) {
soap.createClient(this.location, cb);
}

request(action, xml) {
try {
return new Response(this.client[action](xml), action, true);
} catch (err) {
if (err.errno === 'ECONNRESET') {
const responseError = Response('ECONNRESET', action);
responseError.error = 'ECONNRESET';
responseError.error_msg = '[Errno 104] Connection reset by peer';
return responseError;
} else {
throw err;
}
}
}
}
86 changes: 86 additions & 0 deletions src/document.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
'use strict';

import moment from 'moment';
import crypto from 'crypto';
import {pki} from 'node-forge';

export class Document {

constructor(action, params) {
this._action = action;
this._params = params;
this.doc = this.buildDoc();
}

key() {
if (!this._key) this._key = process.env.TBK_COMMERCE_KEY;
return this._key;
}

cert() {
if (!this._cert) this._cert = process.env.TBK_COMMERCE_CRT;
return this._cert;
}

x509() {
if (!this._x509) this._x509 = pki.certificateFromPem(this.cert());
return this._x509;
}

getIssuerName() {
return this.x509().issuer.attributes.map(x => `${x.shortName}=${x.value}`).join(', ');
}

getSerialNumber() {
return parseInt(this.x509().serialNumber, 16);
}

getDigestValue(xml) {
const shasum = crypto.createHash('sha1');
shasum.update(xml);
return shasum.digest('base64');
}

obj2string(obj) {
return `{${Object.keys(obj).map(x => `'${x}': '${obj[x]}'`).join(', ')}}`;
}

getBodyId() {
const data = `${this._action}${this.obj2string(this._params)}${moment().format('YYYY-MM-DD HH:mm:ss ZZ')}`;
return crypto.createHash('md5').update(data).digest('hex');
}

rsaSign(xml) {
const key = this.key().toString('ascii');
const sign = crypto.createSign('RSA-SHA1');
sign.update(xml);
return sign.sign(key, 'base64');
}

buildParamsXml(params) {
let paramsXml = '';
for (let i of Object.keys(params)) {
paramsXml += `<${i}>${params[i]}</${i}>`;
}
return paramsXml;
}

buildDoc() {
const bodyId = this.getBodyId();

// 1) build body
const bodyParams = this.buildParamsXml(this._params);
const body = `<SOAP-ENV:Body xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="${bodyId}"><ns1:${this._action} xmlns:ns1="http://webservices.webpayserver.transbank.com/"><arg0>${bodyParams}</arg0></ns1:${this._action}></SOAP-ENV:Body>`;

// 2) firm with body
const digestValue = this.getDigestValue(body);

// 3) assign
const xmlToSign = `<ds:SignedInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod><ds:Reference URI="#${bodyId}"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><ds:DigestValue>${digestValue}</ds:DigestValue></ds:Reference></ds:SignedInfo>`;
const signatureValue = this.rsaSign(xmlToSign);

// 4) build headers
return `<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" SOAP-ENV:mustUnderstand="1"><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod><ds:Reference URI="#${bodyId}"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><ds:DigestValue>${digestValue}</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>${signatureValue}</ds:SignatureValue><ds:KeyInfo><wsse:SecurityTokenReference><ds:X509Data><ds:X509IssuerSerial><ds:X509IssuerName>${this.getIssuerName()}</ds:X509IssuerName><ds:X509SerialNumber>${this.getSerialNumber()}</ds:X509SerialNumber></ds:X509IssuerSerial></ds:X509Data></wsse:SecurityTokenReference></ds:KeyInfo></ds:Signature></wsse:Security></SOAP-ENV:Header><SOAP-ENV:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="${bodyId}"><ns1:${this._action} xmlns:ns1="http://webservices.webpayserver.transbank.com/"><arg0>${bodyParams}</arg0></ns1:${this._action}></SOAP-ENV:Body></SOAP-ENV:Envelope>`;
}
}

64 changes: 64 additions & 0 deletions src/oneclick.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict';

import Document from './document';
import Request from './request';
import Client from './client';
import logger from './logging';


export class OneClick {

constructor(testing=false) {
this.client = new Client(testing);
}

initInscription(email, responseUrl, username) {
const params = {email: email, username: username, responseURL: responseUrl};
const request = new Request(params);
const d = new Document({action: 'initInscription', params: params});
const response = this.client.request('initInscription', d.doc);
logger.generic('initInscription', request, response);
return response;
}

finishInscription(token) {
const params = {token: token};
const request = new Request(params);
const d = new Document({action: 'finishInscription', params: params});
const response = this.client.request('finishInscription', d.doc);
logger.generic('finishInscription', request, response);
return response;
}

authorize(amount, tbkUser, username, buyOrder) {
const params = {
amount: amount,
tbkUser: tbkUser,
username: username,
buyOrder: buyOrder
};
const request = new Request(params);
const d = new Document({action: 'authorize', params: params});
const response = this.client.request('Authorize', d.doc);
logger.generic('authorize', request, response);
return response;
}

reverse(buyOrder) {
const params = {'buyorder': buyOrder};
const request = new Request(params);
const d = new Document({action: 'codeReverseOneClick', params: params});
const response = this.client.request('codeReverseOneClick', d.doc);
logger.generic('reverse', request, response);
return response;
}

removeUser(tbkUser, username) {
const params = {tbkUser: tbkUser, username: username};
const request = new Request(params);
const d = new Document({action: 'removeUser', params: params});
const response = this.client.request('removeUser', d.doc);
logger.generic('removeUser', request, response);
return response;
}
}
12 changes: 12 additions & 0 deletions src/request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

export class Request {

constructor(params) {
this._params = params;
}

params() {
return this._params;
}
}
Loading

0 comments on commit 3555157

Please sign in to comment.