-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpayments.js
225 lines (179 loc) · 7.75 KB
/
payments.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
'use strict'
const fs = require('fs')
const template = require('./lib/TemplateRenderer')
const Response = require('./lib/Response')
const BaseHandler = require('./lib/BaseHandler')
const querystring = require('querystring')
const mustache = require('mustache')
const moment = require('moment')
const AWS = require('aws-sdk')
const PaymentRequest = require('./lib/PaymentRequest.js').PaymentRequest
const EmailNotification = require('./lib/SESEmailNotification.js').SESEmailNotification
const BigNumber = require('bignumber.js');
const Hook = require('./lib/Hook')
const Logger = require('./lib/Logger/log')
const setCustomerFacing = require('./middleware/customer-endpoint');
const loadPaymentRequest = require('./middleware/load-existing-payment-request');
const rejectIfPaid = require('./middleware/reject-if-paid');
const rejectIfExpired = require('./middleware/reject-if-expired');
const FormTemplateValidator = require('./lib/FormTemplateValidator');
const FormTemplate = FormTemplateValidator.FormTemplate;
const validator = new FormTemplateValidator();
// The company name from the settings, for the email notifications.
const company = process.env.COMPANY_NAME
// Send the form.
let getHandler = new BaseHandler("get").willDo(
async function (event, context) {
try {
var paymentRequest = global.handler.paymentRequest;
var templateParameters = paymentRequest
templateParameters.assets_host =
process.env.ASSETS_HOST ||
'//' + (event.headers.Host.replace(/\:\d+$/g, '') + ':8081')
templateParameters.stripe_publishable_key =
process.env.STRIPE_PUBLISHABLE_KEY
templateParameters.amount = paymentRequest.amount
templateParameters.description = paymentRequest.description
templateParameters.paid_at_moment = function () {
return moment(this.paid_at).fromNow()
}
// Stripe only accepts payment amounts as integers.
// You can't simply mulitply the amount by 100 because it's a floating-point number.
// Example: Try entering the expression "32.12 * 100" into the Node REPL.
// You will get: 32.12 * 100 = 3211.9999999999995
// templateParameters.integer_amount =
// The solution is to use fixed-point arithmetic.
// (new BigNumber(32.12)).times(100).toString()
let routes = await template.getRoutes();
templateParameters.additional_fields_partial = "";
if(
templateParameters.additional_fields &&
templateParameters.additional_fields != "none"
&& routes.forms.partials[templateParameters.additional_fields]
){
templateParameters.additional_fields_partial = await template.renderPartial("forms/"+templateParameters.additional_fields,templateParameters);
}
return new Response('200').send(
await template.render('payment-form', templateParameters))
}
catch (error) {
Logger.error(['Error in payment get handler: ',error]);
return new Response('200').send(
await template.render('error', { 'error': error }))
}
}
)
getHandler.middleware([
setCustomerFacing,
loadPaymentRequest,
rejectIfPaid,
rejectIfExpired
]);
// Process a payment.
let postHandler = new BaseHandler("post").willDo(
async function (event, context) {
const params = querystring.parse(event.body)
// Look up the payment request record in DynamoDB.
const paymentRequest = global.handler.paymentRequest;
Logger.debug(["paymentRequest",paymentRequest]);
// Create the payment at Stripe.
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY)
const stripeToken = params.stripeToken
const metadata = {};
global.handler.stripeAmount = parseInt( paymentRequest.total.replace(/\./gi,"") )
// GATHER ADDITIONAL FIELDS
Logger.debug(["GATHER ADDITIONAL FIELDS"]);
if(
paymentRequest.additional_fields
){
let routes = await template.getRoutes();
Logger.debug(["routes",routes]);
let fieldsPartials = await template.renderPartial("forms/"+paymentRequest.additional_fields,Object.assign({customer_facing : false},paymentRequest));
Logger.debug(["fieldsPartials",fieldsPartials]);
let fieldsModel = new FormTemplate(fieldsPartials);
Logger.debug(["fieldsModel",fieldsModel]);
Logger.debug(["fields",fieldsModel.fields]);
let errors = validator.validate(fieldsModel,params);
Logger.debug([errors]);
if(errors.length == 0){
fieldsModel.fields.forEach(field =>{
let key = field.name;
if(!field.readonly && params[key]){
paymentRequest[key] = params[key];
}
metadata[key] = paymentRequest[key];
});
}else{
return new Response('200').send(
await template.render('error', { 'error': errors.join("<br>") }))
}
}
try {
Logger.debug(["Starting stripe payment"]);
metadata.payment_request_id = paymentRequest.id;
metadata.payment_request_created_at = paymentRequest.created_at;
metadata.account_id = paymentRequest.account;
global.handler.stripePayload = {
amount: global.handler.stripeAmount,
description: paymentRequest.description,
metadata: metadata,
currency: "usd",
source: stripeToken
};
await Hook.execute('before-sending-to-stripe');
paymentRequest.payment = await stripe.charges.create(global.handler.stripePayload);
Logger.info(["Payment completed"]);
paymentRequest.params = params;
await Hook.execute('after-sending-to-stripe');
if(paymentRequest.payment.status == "succeeded"){
await Hook.execute('after-successful-payment');
paymentRequest.paid = true;
paymentRequest.paid_at = new Date().toISOString()
}else{
await Hook.execute('after-unsuccessful-payment');
}
try {
await Hook.execute('before-updating-dynamodb');
await PaymentRequest.putPayment(paymentRequest);
await Hook.execute('after-updating-dynamodb');
}
catch (error) {
Logger.error(['Error Before Sending Payment confirmation email',error]);
return new Response('200').send(
await template.render('error', { 'error': error }))
}
var templateParameters = paymentRequest
// This notification goes to the customer.
templateParameters.subject = "Payment to " + company
templateParameters.to = paymentRequest.email
var templateName = 'payment-email-to-customer'
global.handler.emailToCustomerParameters = templateParameters
await Hook.execute('before-sending-confirmation-email-to-customer')
await EmailNotification.sendEmail(templateName, global.handler.emailToCustomerParameters)
// This notification goes to the requestor.
templateParameters.subject = "Payment from " + paymentRequest.email
templateParameters.to = paymentRequest.requestor
templateName = 'payment-email-to-requestor'
global.handler.emailToRequestorParameters = templateParameters
await Hook.execute('before-sending-confirmation-email-to-requestor')
await EmailNotification.sendEmail(templateName, global.handler.emailToRequestorParameters)
await Hook.execute('after-sending-email-notifications');
return new Response('200').send(
await template.render('payment-confirmation', templateParameters))
}
catch (error) {
Logger.error(['Error starting the process of stripe payment: ',error]);
return new Response('200').send(
await template.render('payment-error', { 'error': error }))
}
}
)
postHandler.middleware([
loadPaymentRequest,
rejectIfPaid
]);
// * ====================================== *
// * EXPORTS
// * ====================================== *
exports.get = getHandler.do
exports.post = postHandler.do