-
Notifications
You must be signed in to change notification settings - Fork 70
/
stripe.provider.ts
237 lines (226 loc) · 7.93 KB
/
stripe.provider.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {inject, Provider} from '@loopback/core';
import {DataObject, repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
// eslint-disable-next-line @typescript-eslint/naming-convention
import Handlebars from 'handlebars';
import {v4 as uuidv4} from 'uuid';
import {ResponseMessage, Status} from '../../enums';
import {Orders, Subscriptions} from '../../models';
import {
OrdersRepository,
SubscriptionsRepository,
TransactionsRepository,
} from '../../repositories';
import {
stripeCreateTemplate,
stripeSubscriptionCreateTemplate,
} from '../../templates';
import {StripeBindings} from './keys';
import {IStripeConfig, StripePaymentGateway} from './types';
const Stripe = require('stripe');
export class StripeProvider implements Provider<StripePaymentGateway> {
constructor(
@repository(TransactionsRepository)
private readonly transactionsRepository: TransactionsRepository,
@repository(OrdersRepository)
private readonly ordersRepository: OrdersRepository,
@repository(SubscriptionsRepository)
private readonly subscriptionsRepository: SubscriptionsRepository,
@inject(StripeBindings.Config, {
optional: true,
})
private readonly config?: IStripeConfig,
) {
if (this.config) {
this.stripe = Stripe(this.config.dataKey);
} else {
throw new HttpErrors.PreconditionFailed('Stripe Config missing !');
}
}
stripe = Stripe;
value() {
return {
create: async (payorder: Orders, paymentTemplate: string) => {
const orderAmount = payorder.totalamount;
const transactionData = {
id: uuidv4(),
amountPaid: payorder?.totalAmount,
currency: payorder?.currency,
status: Status.Draft,
orderId: payorder?.id,
paymentGatewayId: payorder?.paymentGatewayId,
};
const transactions = await this.transactionsRepository.find({
where: {orderId: payorder.id},
});
if (transactions.length === 0) {
await this.transactionsRepository.create(transactionData);
}
const template = Handlebars.compile(
paymentTemplate || stripeCreateTemplate,
);
const data = {
orderId: payorder?.id,
publishKey: this.config?.publishKey,
orderAmount: orderAmount,
currency: payorder?.currency,
};
return template(data);
},
charge: async (
chargeResponse: DataObject<{
stripeEmail: string;
stripeToken: string;
orderId: string;
}>,
) => {
const order = await this.ordersRepository.findById(
chargeResponse?.orderId,
);
const fetchTransaction = await this.transactionsRepository.find({
where: {orderId: order?.id},
});
const amount = order?.totalAmount;
const currency = order?.currency;
await this.stripe.customers
.create({
email: chargeResponse.stripeEmail,
source: chargeResponse.stripeToken,
})
.then((customer: DataObject<{id: string}>) =>
this.stripe.charges.create({
amount,
currency: currency,
customer: customer.id,
}),
)
.then(async (charge: DataObject<{}>) => {
fetchTransaction[0].status = charge ? Status.Paid : Status.Draft;
fetchTransaction[0].res = {chargeResponse: charge};
await this.transactionsRepository.updateById(
fetchTransaction[0]?.id,
{...fetchTransaction[0]},
);
if (charge) {
order.status = Status.Paid;
await this.ordersRepository.updateById(order.id, {...order});
}
});
return {res: ResponseMessage.Sucess, orderId: order.id};
},
refund: async (transactionId: string) => {
const transaction =
await this.transactionsRepository.findById(transactionId);
const paymentId = await transaction?.res?.chargeResponse?.id;
const refund = await this.stripe.refunds.create({
charge: paymentId,
});
transaction.res.refundDetails = refund;
transaction.status = Status.Refund;
if (refund) {
await this.transactionsRepository.updateById(transactionId, {
...transaction,
});
return refund;
} else {
return {
err: ResponseMessage.NotSucess,
message: 'please check PaymentId',
};
}
},
subscriptionCreate: async (subscription: Subscriptions) => {
const transactionData = {
id: uuidv4(),
amountPaid: subscription?.totalAmount,
status: 'draft',
orderId: subscription?.id,
currency: subscription?.currency,
paymentGatewayId: subscription?.paymentGatewayId,
};
const transactions = await this.transactionsRepository.find({
where: {orderId: subscription.id},
});
if (transactions.length === 0) {
await this.transactionsRepository.create(transactionData);
}
const template = Handlebars.compile(stripeSubscriptionCreateTemplate);
const data = {
publishKey: this.config?.publishKey,
orderAmount: subscription.totalAmount,
subscriptionId: subscription?.id,
currency: subscription?.currency,
};
return template(data);
},
subscriptionCharge: async (
chargeResponse: DataObject<{
stripeEmail: string;
stripeToken: string;
subscriptionId: string;
}>,
) => {
const subscription = await this.subscriptionsRepository.findById(
chargeResponse?.subscriptionId ?? '',
);
const fetchTransaction = await this.transactionsRepository.find({
where: {orderId: subscription?.id},
});
await this.stripe.customers
.create({
email: chargeResponse.stripeEmail,
source: chargeResponse.stripeToken,
})
.then((customer: DataObject<{id: string}>) =>
this.stripe.subscriptions.create({
items: [{price: subscription.planId}],
customer: customer.id,
}),
)
.then(async (charge: DataObject<{id: string}>) => {
fetchTransaction[0].status = charge ? 'paid' : 'draft';
fetchTransaction[0].res = {chargeResponse: charge};
fetchTransaction[0].paidDate = new Date();
await this.transactionsRepository.updateById(
fetchTransaction[0]?.id,
{...fetchTransaction[0]},
);
if (charge) {
const updateSubscription = {
...subscription,
metaData: {gatewaySubRes: charge},
gatewaySubscriptionId: charge.id,
status: 'active',
};
await this.subscriptionsRepository.updateById(subscription.id, {
...updateSubscription,
});
}
});
return {res: ResponseMessage.Sucess, subscriptionId: subscription.id};
},
subscriptionWebHook: async (
sub: DataObject<{
data: DataObject<{
object: DataObject<{subscription: string; status: string}>;
}>;
}>,
) => {
const subId = sub?.data?.object?.subscription ?? '';
const Subscription = await this.subscriptionsRepository.find({
where: {gatewaySubscriptionId: `${subId}`},
});
Subscription[0].status =
sub?.data?.object?.status ?? Subscription[0].status;
await this.subscriptionsRepository.updateById(Subscription[0].id, {
...Subscription[0],
});
return true;
},
};
}
}