Skip to content

Commit

Permalink
feat: Create application
Browse files Browse the repository at this point in the history
  • Loading branch information
Bezouro committed Jun 16, 2022
0 parents commit b739c1e
Show file tree
Hide file tree
Showing 29 changed files with 5,933 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
NUBANK_CARD_PASSWORD=1234 #Used to make transfers
NU_USERNAME=01234567890 #Your CPF used to login in app
NU_PASSWORD=******** #Your password used to login in app
44 changes: 44 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/* eslint-disable no-undef */
module.exports = {
'env': {
'browser': true,
'es2021': true
},
'extends': [
'eslint:recommended',
'plugin:@typescript-eslint/recommended'
],
'parser': '@typescript-eslint/parser',
'parserOptions': {
'ecmaVersion': 'latest',
'sourceType': 'module'
},
'plugins': [
'@typescript-eslint'
],
'rules': {
'indent': [
'error',
2
],
'linebreak-style': [
'error',
'unix'
],
'no-multiple-empty-lines': [
'error',
{
'max': 1,
'maxBOF': 0
}
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
]
}
};
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
*.p12
.env
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
src
tsconfig.json
.eslintrc.js
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"files.eol": "\n",
}
16 changes: 16 additions & 0 deletions examples/checkAccountBallance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import NubankJS from '../src';
import path from 'path';
import fs from 'fs';

const USERNAME = process.env.NUBANK_USERNAME || '';
const PASSWORD = process.env.NUBANK_PASSWORD || '';

const cert = fs.readFileSync(path.join(__dirname, '..', 'cert.p12'));
const nubankjs = new NubankJS(USERNAME, PASSWORD, cert);

async function run() {
const { data } = await nubankjs.accountBalance();
console.log(`Saldo atual: ${data.netAmount}`);
}

run();
39 changes: 39 additions & 0 deletions examples/transferOutPix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import NubankJS from '../src';
import path from 'path';
import fs from 'fs';

const USERNAME = process.env.NUBANK_USERNAME || '';
const PASSWORD = process.env.NUBANK_PASSWORD || '';

const cert = fs.readFileSync(path.join(__dirname, '..', 'cert.p12'));
const nubankjs = new NubankJS(USERNAME, PASSWORD, cert);

async function run(pixKey: string, value: number) {
const { data } = await nubankjs.addPixContact(pixKey);

const account = data.bankAccount;
const transferOutRequest = await nubankjs.transferOutPix(account.id, value);

const success = transferOutRequest.__typename === 'TransferOutRequestSuccess';
let error;

if (!success) {
console.log(transferOutRequest);
error = transferOutRequest.errorHandler.description;
}

const result = {
success,
bank: account.singleBank.number,
bankName: account.singleBank.shortName,
agency: account.branch,
account: account.number,
digit: account.digit,
destinatary: account.name,
error
};

console.log(result);
}

run('11999999999', 0.01);
59 changes: 59 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "nubank.js",
"version": "1.0.0",
"description": "Nubank api module for node.js",
"readmeFilename": "README.md",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint src --fix",
"build": "tsc --project ./",
"start": "node dist/index.js",
"dev": "nodemon -r dotenv/config src/index.ts",
"cli": "nodemon -r dotenv/config src/cli/index.ts",
"patch-release": "npm version patch && npm publish && git push --follow-tags"
},
"bin": {
"nubank.js": "dist/cli/index.js"
},
"dependencies": {
"axios": "^0.26.1",
"browser-env": "^3.3.0",
"dotenv": "^16.0.0",
"firebase": "^9.8.3",
"fs-extra": "^10.1.0",
"mock-browser": "^0.92.14",
"navigator": "^1.0.1",
"node-forge": "^1.3.1",
"pem": "^1.14.6",
"rimraf": "^3.0.2"
},
"devDependencies": {
"@types/fs-extra": "^9.0.13",
"@types/node": "^17.0.22",
"@types/node-forge": "^1.0.2",
"@types/rimraf": "^3.0.2",
"@typescript-eslint/eslint-plugin": "^5.28.0",
"@typescript-eslint/parser": "^5.28.0",
"eslint": "^8.17.0",
"jest": "^28.1.1",
"nodemon": "^2.0.15",
"ts-node": "^10.7.0",
"typescript": "^4.6.2"
},
"keywords": [
"nubank.js",
"nubank",
"nubank api"
],
"author": {
"name": "Bruno Bezouro",
"email": "[email protected]",
"homepage": "https://www.bezouro.com.br/"
},
"repository": {
"type": "git",
"url": "https://github.com/Bezouro/nubank.js.git"
},
"license": "MIT"
}
69 changes: 69 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Nubank.JS
Realize operações que você faz no app do nubank pelo node.js Baseado na ([versão python](https://github.com/Astrocoders/nubank-api) que é baseada nessa outra [versão js](https://github.com/Astrocoders/nubank-api))

## Instalação
Instale por meio do npm:

`npm install nubank.js`

> AVISO: Este não é um modulo oficial de Nu Pagamentos S.A, Este modulo utiliza da [API Publica do Nubank](https://twitter.com/nubank/status/766665014161932288)
> AVISO²: Este projeto ainda está em desenvolvimento e podem ocorrer mudanças na estrutura do codigo
# Exemplo

```typescript
import NubankJS from 'nubank.js';
import path from 'path';
import fs from 'fs';

const USERNAME = process.env.NUBANK_USERNAME || '';
const PASSWORD = process.env.NUBANK_PASSWORD || '';

const cert = fs.readFileSync(path.join(__dirname, '..', 'cert.p12'));
const nubankjs = new NubankJS(USERNAME, PASSWORD, cert);

async function run(pixKey: string, value: number) {
const { data } = await nubankjs.addPixContact(pixKey);

const account = data.bankAccount;
const transferOutRequest = await nubankjs.transferOutPix(account.id, value);

const success = transferOutRequest.__typename === 'TransferOutRequestSuccess';
let error;

if (!success) {
console.log(transferOutRequest);
error = transferOutRequest.errorHandler.description;
}

const result = {
success,
bank: account.singleBank.number,
bankName: account.singleBank.shortName,
agency: account.branch,
account: account.number,
digit: account.digit,
destinatary: account.name,
error
};

console.log(result);
}

run('11999999999', 0.01);
```

Output:
```js
{
success: true,
bank: null,
bankName: 'NEON PAGAMENTOS',
agency: '0000',
account: '123456',
digit: '7',
destinatary: 'Bruno Bezouro',
error: undefined
}
```
58 changes: 58 additions & 0 deletions src/cli/createCert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { createInterface } from 'readline';
import Forge, { asn1 } from 'node-forge';
import fs, { unlinkSync } from 'fs';
import Discovery from '../utils/discovery';
import Axios from 'axios';
import CertificateGenerator from '../utils/certificateGenerator';

const rl = createInterface({ input: process.stdin, output: process.stdout });
function prompt(question: string): Promise<string> {
return new Promise(resolve => rl.question(question, resolve));
}

const client = Axios.create({
baseURL: 'https://prod-s0-webapp-proxy.nubank.com.br/api/',
headers: {
'Content-Type': 'application/json',
'X-Correlation-Id': 'WEB-APP.pewW9',
'User-Agent': 'nubank.js',
},
});

function generateRandomId() {
return Math.random().toString(36).substring(2, 15);
}

function saveCert(cert: asn1.Asn1, name: string) {
const path = `${process.cwd()}/${name}`;
const cert_file = fs.createWriteStream(path);
cert_file.write(Forge.asn1.toDer(cert).getBytes(), 'binary');
}

export default async function run() {
try {
console.log('Starting Nubank.JS certificate creation...');

const discovery = new Discovery(client);
await discovery.updateProxyUrls();
const cpf = await prompt('CPF (only numbers): ');
const password = await prompt('Password (same used in app): ');

const certificateGenerator = (fs.existsSync('.loginstate')) ?
CertificateGenerator.fromState(discovery, password)
: new CertificateGenerator(discovery, cpf, password, generateRandomId());

const { email, expiresAt, codeSentAt } = await certificateGenerator.requestCode();
console.log(`Email sent to ${email} at ${codeSentAt}`);
console.log(`Valid until ${expiresAt}`);

const code = await prompt('Code: ');
const { cert1 } = await certificateGenerator.exchangeCerts(code);
saveCert(cert1, 'cert.p12');
unlinkSync('.loginstate');
console.log(`Logged successfully. Certificate saved to ${process.cwd()}/cert.p12`);
} catch (e) {
console.error(e.message);
}
rl.close();
}
24 changes: 24 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env node

import CreateCert from './createCert';

const args = process.argv.slice(2);

if (args.length === 0) {
console.log('Usage: nubankjs <command>');
console.log('Commands:');
console.log(' create-cert');
process.exit(0);
}

const command = args.shift();

switch (command) {
case 'create-cert':
CreateCert();
break;

default:
console.log('Unknown command:', command);
process.exit(1);
}
Loading

0 comments on commit b739c1e

Please sign in to comment.