-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstripe-service.ts
213 lines (191 loc) · 7.28 KB
/
stripe-service.ts
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
/**
* SudoSOS back-end API service.
* Copyright (C) 2020 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import Stripe from 'stripe';
import { Dinero } from 'dinero.js';
import { getLogger, Logger } from 'log4js';
import User from '../entity/user/user';
import StripeDeposit from '../entity/deposit/stripe-deposit';
import DineroTransformer from '../entity/transformer/dinero-transformer';
import StripeDepositStatus, { StripeDepositState } from '../entity/deposit/stripe-deposit-status';
import {
StripeDepositResponse,
StripeDepositStatusResponse,
StripePaymentIntentResponse,
} from '../controller/response/stripe-response';
import TransferService from './transfer-service';
import { IsNull } from 'typeorm';
import { parseUserToBaseResponse } from '../helpers/revision-to-response';
export const STRIPE_API_VERSION = '2022-08-01';
export default class StripeService {
private stripe: Stripe;
private logger: Logger;
constructor() {
this.stripe = new Stripe(process.env.STRIPE_PRIVATE_KEY, {
apiVersion: STRIPE_API_VERSION,
});
this.logger = getLogger('StripeController');
}
private static asStripeDepositStatusResponse(status: StripeDepositStatus): StripeDepositStatusResponse {
return {
id: status.id,
createdAt: status.createdAt.toISOString(),
updatedAt: status.updatedAt.toISOString(),
version: status.version,
state: status.state,
};
}
public static asStripeDepositResponse(deposit: StripeDeposit): StripeDepositResponse {
return {
id: deposit.id,
createdAt: deposit.createdAt.toISOString(),
updatedAt: deposit.updatedAt.toISOString(),
version: deposit.version,
stripeId: deposit.stripeId,
depositStatus: deposit.depositStatus.map((s) => this.asStripeDepositStatusResponse(s)),
amount: deposit.amount.toObject(),
to: parseUserToBaseResponse(deposit.to, true),
};
}
public static async getProcessingStripeDepositsFromUser(userId: number): Promise<StripeDepositResponse[]> {
const deposits = await StripeDeposit.find({
where: {
to: {
id: userId,
},
transfer: IsNull(),
depositStatus: {
state: StripeDepositState.PROCESSING,
},
},
relations: ['to'],
});
return deposits.filter((d) => !d.depositStatus.some(
(s) => s.state === StripeDepositState.SUCCEEDED
|| s.state === StripeDepositState.FAILED))
.map((d) => this.asStripeDepositResponse(d));
}
public static async getStripeDeposit(id: number, relations: string[] = []) {
return StripeDeposit.findOne({
where: { id },
relations: ['depositStatus'].concat(relations),
});
}
/**
* Create a payment intent and save it to the database
* @param user User that wants to deposit some money into their account
* @param amount The amount to be deposited
*/
public async createStripePaymentIntent(
user: User, amount: Dinero,
): Promise<StripePaymentIntentResponse> {
const paymentIntent = await this.stripe.paymentIntents.create({
amount: DineroTransformer.Instance.to(amount),
currency: amount.getCurrency(),
automatic_payment_methods: { enabled: true },
});
const stripeDeposit = Object.assign(new StripeDeposit(), {
stripeId: paymentIntent.id,
to: user,
amount,
});
await stripeDeposit.save();
return {
id: stripeDeposit.id,
createdAt: stripeDeposit.createdAt.toISOString(),
updatedAt: stripeDeposit.updatedAt.toISOString(),
stripeId: stripeDeposit.stripeId,
clientSecret: paymentIntent.client_secret,
};
}
/**
* Validate a Stripe webhook event
* @param body
* @param signature
*/
public async constructWebhookEvent(
body: any, signature: string | string[],
): Promise<Stripe.Event> {
return this.stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET);
}
/**
* Create a new deposit status
* @param depositId
* @param state
*/
public static async createNewDepositStatus(
depositId: number, state: StripeDepositState,
): Promise<StripeDepositStatus> {
let deposit = await StripeService.getStripeDeposit(depositId);
const states = deposit.depositStatus.map((status) => status.state);
if (states.includes(state)) throw new Error(`Status ${state} already exists.`);
if (state === StripeDepositState.SUCCEEDED && states.includes(StripeDepositState.FAILED)) {
throw new Error('Cannot create status SUCCEEDED, because FAILED already exists');
}
if (state === StripeDepositState.FAILED && states.includes(StripeDepositState.SUCCEEDED)) {
throw new Error('Cannot create status FAILED, because SUCCEEDED already exists');
}
const depositStatus = Object.assign(new StripeDepositStatus(), { deposit, state });
await depositStatus.save();
// If payment has succeeded, create the transfer
if (state === StripeDepositState.SUCCEEDED) {
deposit = await StripeService.getStripeDeposit(depositId, ['to']);
deposit.transfer = await TransferService.createTransfer({
amount: {
amount: deposit.amount.getAmount(),
precision: deposit.amount.getPrecision(),
currency: deposit.amount.getCurrency(),
},
toId: deposit.to.id,
description: deposit.stripeId,
fromId: undefined,
});
await deposit.save();
}
return depositStatus;
}
/**
* Handle the event by making the appropriate database additions
* @param event {Stripe.Event} Event received from Stripe webhook
*/
public async handleWebhookEvent(event: Stripe.Event) {
try {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
const deposit = await StripeDeposit.findOne({
where: { stripeId: paymentIntent.id },
});
switch (event.type) {
case 'payment_intent.created':
await StripeService.createNewDepositStatus(deposit.id, StripeDepositState.CREATED);
break;
case 'payment_intent.processing':
await StripeService.createNewDepositStatus(deposit.id, StripeDepositState.PROCESSING);
break;
case 'payment_intent.succeeded':
await StripeService.createNewDepositStatus(deposit.id, StripeDepositState.SUCCEEDED);
break;
case 'payment_intent.payment_failed':
await StripeService.createNewDepositStatus(deposit.id, StripeDepositState.FAILED);
break;
default:
this.logger.warn('Tried to process event', event.type, 'but processing method is not defined');
}
} catch (error) {
this.logger.error('Could not process Stripe webhook event with ID', event.id, error);
}
}
}