-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
212 lines (184 loc) · 8.63 KB
/
Copy pathserver.js
File metadata and controls
212 lines (184 loc) · 8.63 KB
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
const express = require('express');
const process = require('process');
const bodyParser = require('body-parser');
const pagarme = require('pagarme');
const R = require('ramda');
const {Pool} = require('pg');
const Raven = require('raven');
const crypto = require('crypto');
if(process.env.SENTRY_DSN) {
Raven.config(process.env.SENTRY_DSN).install();
};
function raven_report(e, context_opts) {
if(process.env.SENTRY_DSN) {
Raven.context(function () {
if(context_opts) {
Raven.setContext(context_opts);
};
Raven.captureException(e, (sendErr, event) => {
if(sendErr) {
console.log('error on log to sentry')
} else {
console.log('raven logged event', event);
}
});
});
};
};
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
statement_timeout: (process.env.STATEMENT_TIMEOUT || 5000)
});
const verifyKondutoSignature = (req) => {
const kondutoSecret = process.env.ANTIFRAUD_API_KEY
const string = `${req.body.order_id}#${req.body.timestamp}#${req.body.status}`
const hash = crypto.createHmac('sha256', kondutoSecret).update(string).digest('hex')
return hash === req.body.signature
}
const server = express();
server.use(bodyParser.json({
verify: function(req, res, buf, encoding) {
req.rawBody = buf.toString(encoding);
}
})); // to support JSON-encoded bodies
server.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true,
verify: function(req, res, buf, encoding) {
req.rawBody = buf.toString(encoding);
}
}));
server.get('/', (req, res) => {
res.send("hooks :D");
});
server.post('/webhooks/konduto', async (req, resp) => {
try {
if (verifyKondutoSignature(req)) {
console.log('received valid koduto postback ', req.body);
let client = await pagarme.client.connect({ api_key: process.env.GATEWAY_API_KEY });
if (req.body.status === 'APPROVED') {
await client.withVersion('2019-09-01').transactions.capture({ id: req.body.order_id })
} else if (req.body.status === 'DECLINED') {
await client.withVersion('2019-09-01').transactions.refund({ id: req.body.order_id })
}
resp.setHeader('Content-Type', 'application/json')
resp.status(200).send(JSON.stringify({ status: 'ok' }));
} else {
resp.status(400).send("invalid signature");
}
} catch (err) {
raven_report(err, {});
console.log('Error on konduto webhook processing ', err);
}
})
server.post('/postbacks/:gateway_name', async (req, resp) => {
if(req.params.gateway_name === 'pagarme') {
try {
let gateway_client = await pagarme.client.connect({
api_key: process.env.GATEWAY_API_KEY
});
// check if postback is from gateway
if(gateway_client.security.verify(req.rawBody, req.headers['x-hub-signature'].split('=')[1])) {
console.log('received valid pagarme postback ', req.body);
// fetch payment and user data to build context
const res = await pool.query(
`select
row_to_json(cp.*) as payment_data,
row_to_json(u.*) as user_data,
row_to_json(p.*) as project_data,
row_to_json(o.*) as project_owner_data,
row_to_json(s.*) as subscription_data,
row_to_json(last_payment.*) as last_payment_data
from payment_service.catalog_payments cp
join community_service.users u on u.id = cp.user_id
join project_service.projects p on p.id = cp.project_id
join community_service.users o on o.id = p.user_id
left join payment_service.subscriptions s on s.id = cp.subscription_id
left join lateral (
select cp2.*
from payment_service.catalog_payments cp2
where cp2.subscription_id = s.id
and s.id is not null
order by cp2.created_at desc
limit 1
) as last_payment on true
where cp.id = $1::uuid`
, [req.body.transaction.metadata.payment_id]);
if(R.isEmpty(res.rows) || res.rows == null) {
exit(1, 'payment not found');
}
const payment = res.rows[0].payment_data;
const user = res.rows[0].user_data;
const project = res.rows[0].project_data;
const project_owner = res.rows[0].project_owner_data;
const subscription = res.rows[0].subscription_data;
const last_payment = res.rows[0].last_payment_data;
if (req.body.old_status === 'authorized' && req.body.current_status === 'refunded') {
req.body.current_status = 'refused'
}
const current_status = req.body.current_status;
const transaction = req.body.transaction;
// transaction payment to status
if (!['authorized', 'processing', 'waiting_payment', 'pending_review','pending_refund'].includes(current_status)) {
const payables = await gateway_client.
payables.find({ transactionId: transaction.id});
const result_transaction_data = {
transaction: transaction,
payables: payables
};
// update payment with gateway payable and transaction data
await pool.query(
`update payment_service.catalog_payments
set gateway_cached_data = $2::json,
gateway_general_data = payment_service.__extractor_for_pagarme($2::json) where id = $1::uuid`
, [
payment.id,
JSON.stringify(result_transaction_data)
]);
// transition payment to current_status
await pool.query(
`select
payment_service.transition_to(p, ($2)::payment_service.payment_status, $3::json)
from payment_service.catalog_payments p
where p.id = ($1)::uuid
`, [
payment.id,
current_status,
JSON.stringify(req.body)
]);
// check if has subscription and last_payment is the same of payment to perform subscription transition
if(!R.isEmpty(subscription) && subscription != null && last_payment.id === payment.id && !['canceling', 'canceled'].includes(subscription.status)) {
const subscription_transition_sql = `
select
payment_service.transition_to(s, ($2)::payment_service.subscription_status, $3::json)
from payment_service.subscriptions s
where s.id = ($1)::uuid
`;
if(current_status === 'paid' && subscription.status != 'active') {
// active subscription when current_status is paid
await pool.query(subscription_transition_sql
, [subscription.id, 'active', JSON.stringify(req.body)]);
} else if (current_status === 'refused') {
// NOTE: now we have a retries before inactive on first refused
// inactive subscription when payment is refused
// await pool.query(subscription_transition_sql
// , [subscription.id, 'inactive', JSON.stringify(req.body)]);
} else if (current_status === 'chargedback') {
// inactive subscription when payment is chargedback
await pool.query(subscription_transition_sql
, [subscription.id, 'inactive', JSON.stringify(req.body)]);
}
}
}
resp.send("ok");
} else {
resp.status(400).send("invalid signature");
}
} catch (err) {
raven_report(err, {});
console.log('Error on get pagarme client ', err);
}
};
});
server.listen(process.env.PORT || '4444', () => {
console.log('start server');
});