-
Notifications
You must be signed in to change notification settings - Fork 27
/
app.js
118 lines (95 loc) · 3.17 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* Copyright (c) 2015 Salama AB
* All rights reserved
* Contact: [email protected]
* Website: http://www.aksalj.com
*
* Project : pesajs
* File : app
* Date : 9/5/15 1:14 PM
* Description :
*
*/
'use strict';
const express = require("express");
const bodyParser = require('body-parser');
const randomstring = require("randomstring");
const morgan = require('morgan');
const PesaJs = require("../index");
const paymentService = new PesaJs.LipaNaMpesa({
merchant: "898998",
passkey: "a8eac82d7ac1461ba0348b0cb24d3f8140d3afb9be864e56a10d7e8026eaed66",
debug: true
});
const app = express();
app.use(morgan("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('static'));
app.post('/checkout/:action(request|confirm)', function (req, res, next) {
switch(req.params.action) {
case "request":
let cart = {
transaction: randomstring.generate(),
ref: req.body.reference,
account: req.body.phone,
amount: req.body.amount,
callbackUrl: "http://awesome-store.co.ke/ipn",
details: "Additional transaction details if any"
};
paymentService.requestPayment(cart).then((data) => {
console.info(data);
// Now if ok show message to user and allow them to confirm
// ...
res.send({
transaction: cart.transaction,
mpesa_txn: data.mpesa_txn,
message: data.message
});
}).catch((function(err) {
console.error(err);
res.status(500).send(err);
}));
break;
case "confirm":
let args = {
transaction: req.body.transaction,
mpesa_txn: req.body.mpesa_transaction
};
paymentService.confirmPayment(args).then(function(err, data) {
if(err) {
console.error(err);
res.sendStatus(500);
return;
}
console.info(data);
res.send({
message: "Thank you for doing business with us. Buy some more stuff while we wait for payment to be processed!"
});
});
break;
default:
next();
break;
}
});
app.post("/ipn", paymentService.paymentNotification, function(req, res) {
// Do whatever with payment info like confirm purchase, init shipping, send download link, etc.
let ipn = req.payment;
console.log(ipn);
});
app.get("/status/:transaction", function(req, res) {
let args = {
transaction: req.params.transaction,
mpesa_txn: null
};
paymentService.getPaymentStatus(args).then(function(err, data) {
console.error(err);
console.error(data);
res.send(data);
});
});
var server = app.listen(process.env.PORT || 3000, function () {
let host = server.address().address;
let port = server.address().port;
console.log('Shopping app listening at http://%s:%s', host, port);
});