Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Brian poc #125

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -69,6 +69,7 @@
"dependencies": {
"atob": "2.1.2",
"csrf": "^3.0.4",
"dotenv": "^16.0.0",
"jsonwebtoken": "^8.3.0",
"popsicle": "10.0.1",
"query-string": "^6.12.1",
39 changes: 39 additions & 0 deletions sample/TokenSaver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const {Client} = require('pg')
const {v4: uuidv4} = require('uuid');

module.exports = class TokenSaver {
async saveAuthToken(tokenData, yardId) {
console.log('saving auth token')

const client = new Client()
await client.connect()

const query = `
INSERT INTO erp_tool_credentials
(erp_system_id, qb_access_token, qb_refresh_token, qb_expires_in,
qb_refresh_token_expires_in, created_at, yard_id)
VALUES ($1, $2, $3, $4, $5, to_timestamp($6), $7)
ON CONFLICT
ON CONSTRAINT erp_tool_credentials_pkey
DO UPDATE
SET erp_system_id = $1,
qb_access_token = $2,
qb_refresh_token = $3,
qb_expires_in = $4,
qb_refresh_token_expires_in = $5,
created_at = to_timestamp($6),
yard_id = $7
RETURNING *
`
const values = [tokenData.realmId, tokenData.access_token, tokenData.refresh_token, tokenData.expires_in, tokenData.x_refresh_token_expires_in, tokenData.createdAt / 1000, yardId]

try {
const res = await client.query(query, values)
console.log('saved credentials')
console.log(res.rows[0])
} catch (err) {
console.log(err.stack)
}
await client.end()
}
}
211 changes: 115 additions & 96 deletions sample/app.js
Original file line number Diff line number Diff line change
@@ -7,24 +7,27 @@ require('dotenv').config();
* @type {*|createApplication}
*/
const express = require('express');
const TokenSaver = require('./TokenSaver')

const app = express();
const path = require('path');
const OAuthClient = require('intuit-oauth');
const bodyParser = require('body-parser');
const ngrok = process.env.NGROK_ENABLED === 'true' ? require('ngrok') : null;
const querystring = require("querystring");
const tokenSaver = new TokenSaver()

/**
* Configure View and Handlebars
*/
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, '/public')));
app.engine('html', require('ejs').renderFile);

app.set('view engine', 'html');
app.use(bodyParser.json());

const urlencodedParser = bodyParser.urlencoded({ extended: false });
const urlencodedParser = bodyParser.urlencoded({extended: false});

/**
* App Variables
@@ -39,151 +42,167 @@ let redirectUri = '';
*/

let oauthClient = null;
let yardId = null;

/**
* Home Route
*/
app.get('/', function (req, res) {
res.render('index');
res.render('index');
});

/**
* Get the AuthorizeUri
*/
app.get('/authUri', urlencodedParser, function (req, res) {
oauthClient = new OAuthClient({
clientId: req.query.json.clientId,
clientSecret: req.query.json.clientSecret,
environment: req.query.json.environment,
redirectUri: req.query.json.redirectUri,
});

const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting],
state: 'intuit-test',
});
res.send(authUri);

yardId = req.query.json.yardId
console.log('yardId is ', yardId)

//? configure the client with our app creds
oauthClient = new OAuthClient({
clientId: process.env.QB_CLIENT_ID,
clientSecret: process.env.QB_CLIENT_SECRET,
environment: req.query.json.environment,
redirectUri: process.env.REDIRECT_URI,
});

const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.Payment],
state: 'intuit-test',
});
//? send the auth URI back to the client
res.send(authUri);
});

/**
* Handle the callback to extract the `Auth Code` and exchange them for `Bearer-Tokens`
*/
app.get('/callback', function (req, res) {
oauthClient
.createToken(req.url)
.then(function (authResponse) {
oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2);
})
.catch(function (e) {
console.error(e);
});

res.send('');
oauthClient
.createToken(req.url)
.then(function (authResponse) {
console.log("got auth response. raw QB token is: \n")
console.log(JSON.stringify(authResponse.token))
console.log('-------')
console.log('-------')
oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2);
return authResponse
})
.then(function (authResponse) {
//? save the returned token to the DB
return tokenSaver.saveAuthToken(authResponse.token, yardId)
})
.catch(function (e) {
console.error(e);
});

res.send('');
});

/**
* Display the token : CAUTION : JUST for sample purposes
*/
app.get('/retrieveToken', function (req, res) {
res.send(oauth2_token_json);
res.send(oauth2_token_json);
});

/**
* Refresh the access-token
*/
app.get('/refreshAccessToken', function (req, res) {
oauthClient
.refresh()
.then(function (authResponse) {
console.log(`The Refresh Token is ${JSON.stringify(authResponse.getJson())}`);
oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2);
res.send(oauth2_token_json);
})
.catch(function (e) {
console.error(e);
});
oauthClient
.refresh()
.then(function (authResponse) {
console.log(`The Refresh Token is ${JSON.stringify(authResponse.getJson())}`);
oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2);
res.send(oauth2_token_json);
})
.catch(function (e) {
console.error(e);
});
});

/**
* getCompanyInfo ()
*/
app.get('/getCompanyInfo', function (req, res) {
const companyID = oauthClient.getToken().realmId;

const url =
oauthClient.environment == 'sandbox'
? OAuthClient.environment.sandbox
: OAuthClient.environment.production;

oauthClient
.makeApiCall({ url: `${url}v3/company/${companyID}/companyinfo/${companyID}` })
.then(function (authResponse) {
console.log(`The response for API call is :${JSON.stringify(authResponse)}`);
res.send(JSON.parse(authResponse.text()));
})
.catch(function (e) {
console.error(e);
});
const companyID = oauthClient.getToken().realmId;

const url =
oauthClient.environment == 'sandbox'
? OAuthClient.environment.sandbox
: OAuthClient.environment.production;

oauthClient
.makeApiCall({url: `${url}v3/company/${companyID}/companyinfo/${companyID}`})
.then(function (authResponse) {
console.log(`The response for API call is :${JSON.stringify(authResponse)}`);
res.send(JSON.parse(authResponse.text()));
})
.catch(function (e) {
console.error(e);
});
});

/**
* disconnect ()
*/
app.get('/disconnect', function (req, res) {
console.log('The disconnect called ');
const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.OpenId, OAuthClient.scopes.Email],
state: 'intuit-test',
});
res.redirect(authUri);
console.log('The disconnect called ');
const authUri = oauthClient.authorizeUri({
scope: [OAuthClient.scopes.OpenId, OAuthClient.scopes.Email],
state: 'intuit-test',
});
res.redirect(authUri);
});

/**
* Start server on HTTP (will use ngrok for HTTPS forwarding)
*/
const server = app.listen(process.env.PORT || 8000, () => {
console.log(`💻 Server listening on port ${server.address().port}`);
if (!ngrok) {
redirectUri = `${server.address().port}` + '/callback';
console.log(
`💳 Step 1 : Paste this URL in your browser : ` +
'http://localhost:' +
`${server.address().port}`,
);
console.log(
'💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com',
);
console.log(
`💳 Step 3 : Copy Paste this callback URL into redirectURI :` +
'http://localhost:' +
`${server.address().port}` +
'/callback',
);
console.log(
`💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com`,
);
}
console.log(`💻 Server listening on port ${server.address().port}`);
if (!ngrok) {
redirectUri = `${server.address().port}` + '/callback';
console.log(
`💳 Step 1 : Paste this URL in your browser : ` +
'http://localhost:' +
`${server.address().port}`,
);
console.log(
'💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com',
);
console.log(
`💳 Step 3 : Copy Paste this callback URL into redirectURI :` +
'http://localhost:' +
`${server.address().port}` +
'/callback',
);
console.log(
`💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com`,
);
}
});

/**
* Optional : If NGROK is enabled
*/
if (ngrok) {
console.log('NGROK Enabled');
ngrok
.connect({ addr: process.env.PORT || 8000 })
.then((url) => {
redirectUri = `${url}/callback`;
console.log(`💳 Step 1 : Paste this URL in your browser : ${url}`);
console.log(
'💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com',
);
console.log(`💳 Step 3 : Copy Paste this callback URL into redirectURI : ${redirectUri}`);
console.log(
`💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com`,
);
})
.catch(() => {
process.exit(1);
});
console.log('NGROK Enabled');
ngrok
.connect({addr: process.env.PORT || 8000})
.then((url) => {
redirectUri = `${url}/callback`;
console.log(`💳 Step 1 : Paste this URL in your browser : ${url}`);
console.log(
'💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com',
);
console.log(`💳 Step 3 : Copy Paste this callback URL into redirectURI : ${redirectUri}`);
console.log(
`💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com`,
);
})
.catch(() => {
process.exit(1);
});
}
3 changes: 2 additions & 1 deletion sample/package.json
Original file line number Diff line number Diff line change
@@ -19,7 +19,8 @@
"express-session": "^1.14.2",
"intuit-oauth": "^3.0.1",
"ngrok": "^3.2.5",
"path": "^0.12.7"
"path": "^0.12.7",
"pg": "^8.7.3"
},
"devDependencies": {
"snyk": "^1.316.1"
101 changes: 52 additions & 49 deletions sample/public/index.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<!DOCTYPE html>
<html>
<head>
<link rel="apple-touch-icon icon shortcut" type="image/png" href="https://plugin.intuitcdn.net/sbg-web-shell-ui/6.3.0/shell/harmony/images/QBOlogo.png">
<link rel="apple-touch-icon icon shortcut" type="image/png"
href="https://plugin.intuitcdn.net/sbg-web-shell-ui/6.3.0/shell/harmony/images/QBOlogo.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
@@ -27,91 +28,93 @@ <h1>intuit-nodejsclient sample application</h1>
<h2>OAuth2.0</h2><h4>( Please enter the client credentials below )</h4><br>
<form>
<div class="form-group">
<label for="clientId">ClientID</label>
<input type="text" class="form-control" placeholder="enter the clientId" id="clientId" />
</div>
<div class="form-group">
<label for="clientSecret">ClientSecret</label>
<input type="text" class="form-control" placeholder="enter the clientSecret" id="clientSecret" />
<label for="yardId">Yard ID</label>
<input type="text" class="form-control" placeholder="enter the yardId" id="yardId"/>
</div>
<div class="form-group">
<label for="environment">Environment</label>
<select id="environment" class="form-control">
<option value="sandbox" selected="selected">Sandbox</option>
<option value="production">Production</option>
<option value="sandbox" selected="selected">Sandbox</option>
<option value="production">Production</option>
</select>
</div>
<div class="form-group">
<label for="redirectUri">Redirect URI</label>
<input type="text" class="form-control" placeholder="enter the redirectUri" id="redirectUri" /><br>
</div>

</form>
<p>Now click the <b>Connect to QuickBooks</b> button below.</p>
<pre id="accessToken"></pre>
<a class="imgLink" href="#" id="authorizeUri" ><img src="./images/C2QB_green_btn_lg_default.png" width="178" /></a>
<button type="button" id="retrieveToken" class="btn btn-success">Display Access Token</button>
<button type="button" id="refreshToken" class="btn btn-success">Refresh Token</button>
<hr />

<h2>Make an API call</h2><h4>( Please refer to our <a target="_balnk" href="https://developer.intuit.com/v2/apiexplorer?apiname=V3QBO#?id=Account">API Explorer</a> )</h4>
<p>If there is no access token or the access token is invalid, click either the <b>Connect to QucikBooks</b> or <b>Sign with Intuit</b> button above.</p>
<a class="imgLink" href="#" id="authorizeUri"><img src="./images/C2QB_green_btn_lg_default.png" width="178"/></a>
<button type="button" id="retrieveToken" class="btn btn-success">Display Access Token</button>
<button type="button" id="refreshToken" class="btn btn-success">Refresh Token</button>
<hr/>

<h2>Make an API call</h2><h4>( Please refer to our <a target="_balnk"
href="https://developer.intuit.com/v2/apiexplorer?apiname=V3QBO#?id=Account">API
Explorer</a> )</h4>
<p>If there is no access token or the access token is invalid, click either the <b>Connect to QucikBooks</b> or <b>Sign
with Intuit</b> button above.</p>
<pre id="apiCall"></pre>
<button type="button" id="makeAPICall" class="btn btn-success">Get Company Info</button>
<button type="button" id="makeAPICall" class="btn btn-success">Get Company Info</button>

<hr />
<hr/>

<p>More info:</p>
<ul>
<li><a href="https://developer.intuit.com/docs">Intuit API Developer Guide</a></li>
<li><a href="https://developer.intuit.com/docs/00_quickbooks_online/2_build/50_sample_apps_and_code">Intuit Sample Apps and Code</a></li>
<li><a href="https://developer.intuit.com/docs/00_quickbooks_online/2_build/40_sdks">Intuit Official SDK's</a></li>
<li><a href="https://developer.intuit.com/docs/00_quickbooks_online/2_build/50_sample_apps_and_code">Intuit
Sample Apps and Code</a></li>
<li><a href="https://developer.intuit.com/docs/00_quickbooks_online/2_build/40_sdks">Intuit Official SDK's</a>
</li>
</ul>
<hr>
<p class="text-center text-muted">
&copy; 2018 Intuit&trade;, Inc. All rights reserved. Intuit and QuickBooks are registered trademarks of Intuit Inc.
&copy; 2018 Intuit&trade;, Inc. All rights reserved. Intuit and QuickBooks are registered trademarks of Intuit
Inc.
</p>

</div>

<script type="text/javascript">
(function() {
(function () {
let yardId = null;

function authorizeUri() {

yardId = $('#yardId').val();
console.warn('yardId ', yardId)
// Generate the authUri
var jsonBody = {};
jsonBody.clientId = $('#clientId').val();
jsonBody.clientSecret = $('#clientSecret').val();

jsonBody.environment = $('#environment').val();
jsonBody.redirectUri = $('#redirectUri').val();
jsonBody.yardId = $('#yardId').val();

$.get('/authUri', {json:jsonBody}, function (uri) {
console.log('The Auth Uris is :'+uri);
$.get('/authUri', {json: jsonBody}, function (uri) {
console.log('The Auth Uris is :' + uri);
})
.then(function (authUri) {
// Launch Popup using the JS window Object
var parameters = "location=1,width=800,height=650";
parameters += ",left=" + (screen.width - 800) / 2 + ",top=" + (screen.height - 650) / 2;
var win = window.open(authUri, 'connectPopup', parameters);
var pollOAuth = window.setInterval(function () {
try {
if (win.document.URL.indexOf("code") != -1) {
window.clearInterval(pollOAuth);
win.close();
location.reload();
.then(function (authUri) {
// Launch Popup using the JS window Object
var parameters = "location=1,width=800,height=650";
parameters += ",left=" + (screen.width - 800) / 2 + ",top=" + (screen.height - 650) / 2;
//? open an iframe with QB auth modal
var win = window.open(authUri, 'connectPopup', parameters);
var pollOAuth = window.setInterval(function () {
try {
if (win.document.URL.indexOf("code") != -1) {
window.clearInterval(pollOAuth);
win.close();
location.reload();
}
} catch (e) {
console.log(e)
}
} catch (e) {
console.log(e)
}
}, 100);
});
}, 100);
});
}

function retrieveToken() {

// Generate the authUri
$.get('/retrieveToken', function (token) {
var token = (token!=null) ? token : 'Please Authorize Using Connect to Quickbooks first !';
var token = (token != null) ? token : 'Please Authorize Using Connect to Quickbooks first !';
$("#accessToken").html(token);
});
}
@@ -120,7 +123,7 @@ <h2>Make an API call</h2><h4>( Please refer to our <a target="_balnk" href="http

// Generate the authUri
$.get('/refreshAccessToken', function (token) {
var token = (token!=null) ? token : 'Please Authorize Using Connect to Quickbooks first !';
var token = (token != null) ? token : 'Please Authorize Using Connect to Quickbooks first !';
$("#accessToken").html(token);
});
}
24 changes: 24 additions & 0 deletions sample/runner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

require('dotenv').config()
const querystring = require('querystring');

const TokenSaver = require('./TokenSaver');

const saver = new TokenSaver();

// const tokenData = {
// realmId: '4625319964620848278',
// token_type: 'bearer',
// access_token: 'eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..wLdClMRLM6QjRLArR-CqqA.898qnGtVO5c3w6ylZv19zhvAJPOhr-hW-jjToIK2OxMz18CrJ1HCKdDAWuYQfb6dBd1-ObG8mw2Xi8SeRes8GDcNWG-tKbkVe9c15WE6BHwH_3JK3i2OW1ZIDLCA0raBg5YYcdhZEUyJCXMXhmzWtEWDPOUk69fd1lX4W0TMzdI5LlZ2UQ5AsNSQO2oeqNCa5_g6oMnJtts2nRS5FEb7Tk_Rjo0IB9LyJdqz_J4HjBSuuXCBUMgwMnwlHRiQTm0iZzjErsED4A8YaFjf5IqTK3xMO-n_1e-FDg_SC3Mr_AStGyQvAIGBYYds5MZ8m0MeRqKHECzdeo2hRfa9Mdy1B6Vew-xvTNTMjnjyREz_5pkJKGDCrWfISRF5kn8NC2eVWp1zgrmC2K1I8ugiFpcENzfO3KyMyFpnDyjwzRmjDBGUBBqtdBdt12hG34RzOQ-jde17q5YHrH6D4ObhSzALfZbKIlhr2b8z46NWI2x36KZKeu9uhjpvpxksOQ05XvQOvNG72LOxYrfuTQ-gRrk8-lPHArwsXS09L6xBKqc1F2dD2ucrM2CrdsdoHuejrMNKQ3N1JDyiPOYbw6IlDO6qlDLAMV-jKMBb1Pgcq_G6qGOg4EdWVOJjzd4Kf1YA6azhGp4RefibuNJKxWn7cskh2FkSGSBJlPqrPDdsj0vtp_Ueolh80dXjYMrVSQGFBzmq5eUNQVaEMvxagVQRWDD26RlPNZXunCoMnvKJNUAnctnCF5idTJadgJeaoNtfH_xE.kY9waBRHrpiK3HlD6ShydQ',
// refresh_token: 'AB11654363506sQAc20kr5ZARdEG0urk1IkoXIgZUx5b6F6sk0',
// expires_in: 3600,
// x_refresh_token_expires_in: 8726400,
// createdAt: 1645637106335
// }
//
// saver.saveAuthToken(tokenData, '00000000-0000-0000-0000-000000000000')

// const url = 'http:localhost:8080/callback?code=AB11645664094OC4uY1U4v4guoEPpyrUGPZv5uwHhBoxbZdFs1&state=intuit-test&realmId=4625319964620848278'
// const parsedUrl = querystring.parse(url)


10 changes: 10 additions & 0 deletions sampleToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// eslint-disable-next-line strict
const data = {
realmId: '4625319964620848278',
token_type: 'bearer',
access_token: 'eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..wLdClMRLM6QjRLArR-CqqA.898qnGtVO5c3w6ylZv19zhvAJPOhr-hW-jjToIK2OxMz18CrJ1HCKdDAWuYQfb6dBd1-ObG8mw2Xi8SeRes8GDcNWG-tKbkVe9c15WE6BHwH_3JK3i2OW1ZIDLCA0raBg5YYcdhZEUyJCXMXhmzWtEWDPOUk69fd1lX4W0TMzdI5LlZ2UQ5AsNSQO2oeqNCa5_g6oMnJtts2nRS5FEb7Tk_Rjo0IB9LyJdqz_J4HjBSuuXCBUMgwMnwlHRiQTm0iZzjErsED4A8YaFjf5IqTK3xMO-n_1e-FDg_SC3Mr_AStGyQvAIGBYYds5MZ8m0MeRqKHECzdeo2hRfa9Mdy1B6Vew-xvTNTMjnjyREz_5pkJKGDCrWfISRF5kn8NC2eVWp1zgrmC2K1I8ugiFpcENzfO3KyMyFpnDyjwzRmjDBGUBBqtdBdt12hG34RzOQ-jde17q5YHrH6D4ObhSzALfZbKIlhr2b8z46NWI2x36KZKeu9uhjpvpxksOQ05XvQOvNG72LOxYrfuTQ-gRrk8-lPHArwsXS09L6xBKqc1F2dD2ucrM2CrdsdoHuejrMNKQ3N1JDyiPOYbw6IlDO6qlDLAMV-jKMBb1Pgcq_G6qGOg4EdWVOJjzd4Kf1YA6azhGp4RefibuNJKxWn7cskh2FkSGSBJlPqrPDdsj0vtp_Ueolh80dXjYMrVSQGFBzmq5eUNQVaEMvxagVQRWDD26RlPNZXunCoMnvKJNUAnctnCF5idTJadgJeaoNtfH_xE.kY9waBRHrpiK3HlD6ShydQ',
refresh_token: 'AB11654363506sQAc20kr5ZARdEG0urk1IkoXIgZUx5b6F6sk0',
expires_in: 3600,
x_refresh_token_expires_in: 8726400,
createdAt: 1645637106335,
}