Skip to content
Open
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
*~
.*~
*.pyc
/dist/
/build/
Expand Down Expand Up @@ -66,3 +68,7 @@ localtest.py

#idea
.idea

#Node
node_modules/
NodeJS/recurring_payment/config/settings.js
3 changes: 3 additions & 0 deletions NodeJS/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
recurring_payment: Full Nodejs example for recurring_payment

login_with_amazon.js: Legacy nodejs code fragment
33 changes: 33 additions & 0 deletions NodeJS/recurring_payment/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
NodeJS example for recurring payments.
Adapted from Python/recurring_payment example.

To run:

1. Create file config/settings.js under NodeJS/recurring_payment
with you credentials from Seller Central.

module.exports = {

merchant_id:"XXXXXXXXXXXXXXXXX"

mws_access_key:"XXXXXXXXXXXXXXXX"

mws_secret_key:"XXXXXXXXXXXXXXXXXXXX"

client_id:"XXXXXXXXXXXXXXXXX"

}

2. In Amazon Pay sandbox account, add http://localhost:3000 to Allowed Javascript origins

3. npm install

4. With debug messages: DEBUG=* nodemon bin/www.js

Without debug messages: node bin/www.js

5. Server starts at http://localhost:3000

6. On the first form, just click submit. Settings have been defined in Step 1.

7. Other caveates, some raw output from the API calls will not be displayed. But you can checked the payment went through by looking at 'Manage Transactions' in your Amazon seller sandbox account.
223 changes: 223 additions & 0 deletions NodeJS/recurring_payment/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const swig = require('swig');
const methodOverride = require('method-override');
const axios = require('axios');
const Client = require('amazonpay').amazonPayClient;

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');
app.set('view engine', 'html')
app.engine('html', swig.renderFile);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(methodOverride());
app.use(session({
secret: 'ak987239HKKl;nm3248',
resave: true,
saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req,res) => {
res.render('base.html');
});

app.post('/cart', (req,res) => {

let configSettings = require('./config/settings');
//Taking a shortcut here, and just setting the values from config file
//instead of form
req.session.merchant_id = configSettings['merchant_id'];
req.session.mws_access_key = configSettings['mws_access_key'];
req.session.mws_secret_key = configSettings['mws_secret_key'];
req.session.client_id = configSettings['client_id'];

res.render('cart.html',{session: req.session});

});

app.get('/set', (req,res) => {
req.session.access_token = req.query.access_token;
res.render('set.html',{session:req.session});
});

app.post('/confirm' , (req,res) => {

console.log('/confirm: billingAgreementId = ' + req.session.billing_agreement_id);

const configArgs = {
'merchantId' : req.session.merchant_id,
'accessKey' : req.session.mws_access_key,
'secretKey' : req.session.mws_secret_key,
'clientId' : req.session.client_id,
'region' : 'us',
'currencyCode' : 'USD',
'sandbox' : true,
'jsonResponse' : 'jsonString'
};

const client = new Client(configArgs);

//confirm billing agreement
const reqParam = {
'amazonBillingAgreementId': req.session.billing_agreement_id
};
const response = client.confirmBillingAgreement(reqParam);

response.then( result => {
console.log( '/confirm = ' + result);
let jsonOutput = JSON.parse(result).ConfirmBillingAgreementResult;
console.log("ConfirmBillingAgreementResult jsonOutput = " + JSON.stringify(jsonOutput,null,4));
res.render('confirm.html',{confirm_response: jsonOutput});
})
.catch( err => {
console.log(err.body);
});

});

app.post('/authorize', (req,res) => {
const configArgs = {
'merchantId' : req.session.merchant_id,
'accessKey' : req.session.mws_access_key,
'secretKey' : req.session.mws_secret_key,
'clientId' : req.session.client_id,
'region' : 'us',
'currencyCode' : 'USD',
'sandbox' : true,
'jsonResponse' : 'jsonString'
};

const client = new Client(configArgs);

const uuidv4 = require('uuid/v4');

let reqParam = {
'amazonBillingAgreementId': req.session.billing_agreement_id,
'authorizationReferenceId': uuidv4().toString().replace(/-/g, ''),
'amount': "3.45",
};

const response = client.authorizeOnBillingAgreement(reqParam);

response.then( result => {
console.log( '/authorize = ' + result);

let jsonOutput = JSON.parse(result).AuthorizeOnBillingAgreementResult;
console.log("AuthorizeOnBillingAgreementResult jsonOutput = " + JSON.stringify(jsonOutput,null,4));
const reqParam = {
'accessToken' : req.session.access_token,
'amazonBillingAgreementId': req.session.billing_agreement_id
};
return client.getBillingAgreementDetails(reqParam);
})
.then( result => {
console.log( '/authorize = ' + result);

let jsonOutput = JSON.parse(result).GetBillingAgreementDetailsResult;
console.log("GetBillingAgreementDetailsResult jsonOutput = " + JSON.stringify(jsonOutput,null,4));
res.send(jsonOutput);
})
.catch( err => {
console.log(err.body);
});

});

app.post('/get_details', (req,res) => {

req.session.billing_agreement_id = req.body.billingAgreementId;

const configArgs = {
'merchantId' : req.session.merchant_id,
'accessKey' : req.session.mws_access_key,
'secretKey' : req.session.mws_secret_key,
'clientId' : req.session.client_id,
'region' : 'us',
'currencyCode' : 'USD',
'sandbox' : true,
'jsonResponse' : 'jsonString'
};

const client = new Client(configArgs);

//confirm billing agreement
const reqParam = {
'accessToken' : req.session.access_token,
'amazonBillingAgreementId': req.session.billing_agreement_id,
storeName: "Amazon Pay Nodejs SDK"
};
const response = client.setBillingAgreementDetails(reqParam);

response.then( result => {
console.log( '/get_details = ' + result);

let jsonOutput = JSON.parse(result).SetBillingAgreementDetailsResult;
console.log("SetBillingAgreementDetailsResult jsonOutput = " + JSON.stringify(jsonOutput,null,4));
const reqParam = {
'accessToken' : req.session.access_token,
'amazonBillingAgreementId': req.session.billing_agreement_id
};
return client.getBillingAgreementDetails(reqParam);
})
.then( result => {
console.log( '/get_details = ' + result);

let jsonOutput = JSON.parse(result).GetBillingAgreementDetailsResult;
console.log("GetBillingAgreementDetailsResult jsonOutput = " + JSON.stringify(jsonOutput,null,4));
res.send(jsonOutput);
})
.catch( err => {
console.log(err.body);
});

});


//==============================================================
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});

module.exports = app;
90 changes: 90 additions & 0 deletions NodeJS/recurring_payment/bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('NodeJS:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
Loading