/
payment.ts
258 lines (218 loc) · 7.12 KB
/
payment.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { isDefined, MedusaError } from "medusa-core-utils"
import { EntityManager } from "typeorm"
import { PaymentRepository } from "./../repositories/payment"
import { TransactionBaseService } from "../interfaces"
import { Payment, Refund } from "../models"
import { FindConfig } from "../types/common"
import { buildQuery } from "../utils"
import EventBusService from "./event-bus"
import { PaymentProviderService } from "./index"
type InjectedDependencies = {
manager: EntityManager
paymentProviderService: PaymentProviderService
eventBusService: EventBusService
paymentRepository: typeof PaymentRepository
}
export type PaymentDataInput = {
currency_code: string
provider_id: string
amount: number
data: Record<string, unknown>
}
export default class PaymentService extends TransactionBaseService {
protected readonly eventBusService_: EventBusService
protected readonly paymentProviderService_: PaymentProviderService
protected readonly paymentRepository_: typeof PaymentRepository
static readonly Events = {
CREATED: "payment.created",
UPDATED: "payment.updated",
PAYMENT_CAPTURED: "payment.payment_captured",
PAYMENT_CAPTURE_FAILED: "payment.payment_capture_failed",
REFUND_CREATED: "payment.payment_refund_created",
REFUND_FAILED: "payment.payment_refund_failed",
}
constructor({
paymentRepository,
paymentProviderService,
eventBusService,
}: InjectedDependencies) {
// eslint-disable-next-line prefer-rest-params
super(arguments[0])
this.paymentRepository_ = paymentRepository
this.paymentProviderService_ = paymentProviderService
this.eventBusService_ = eventBusService
}
/**
* Retrieves a payment by id.
* @param paymentId - the id of the payment
* @param config - the config to retrieve the payment
* @return the payment.
*/
async retrieve(
paymentId: string,
config: FindConfig<Payment> = {}
): Promise<Payment> {
if (!isDefined(paymentId)) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`"paymentId" must be defined`
)
}
const paymentRepository = this.activeManager_.withRepository(
this.paymentRepository_
)
const query = buildQuery({ id: paymentId }, config)
const payment = await paymentRepository.find(query)
if (!payment.length) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`Payment with id ${paymentId} was not found`
)
}
return payment[0]
}
/**
* Created a new payment.
* @param paymentInput - info to create the payment
* @return the payment created.
*/
async create(paymentInput: PaymentDataInput): Promise<Payment> {
return await this.atomicPhase_(async (manager: EntityManager) => {
const { data, currency_code, amount, provider_id } = paymentInput
const paymentRepository = manager.withRepository(this.paymentRepository_)
const created = paymentRepository.create({
provider_id,
amount,
currency_code,
data,
})
const saved = await paymentRepository.save(created)
await this.eventBusService_
.withTransaction(manager)
.emit(PaymentService.Events.CREATED, saved)
return saved
})
}
/**
* Updates a payment in order to link it to an order or a swap.
* @param paymentId - the id of the payment
* @param data - order_id or swap_id to link the payment
* @return the payment updated.
*/
async update(
paymentId: string,
data: { order_id?: string; swap_id?: string }
): Promise<Payment> {
return await this.atomicPhase_(async (manager: EntityManager) => {
const payment = await this.retrieve(paymentId)
const paymentRepository = manager.withRepository(this.paymentRepository_)
if (data?.order_id) {
payment.order_id = data.order_id
}
if (data?.swap_id) {
payment.swap_id = data.swap_id
}
const updated = await paymentRepository.save(payment)
await this.eventBusService_
.withTransaction(manager)
.emit(PaymentService.Events.UPDATED, updated)
return updated
})
}
/**
* Captures a payment.
* @param paymentOrId - the id or the class instance of the payment
* @return the payment captured.
*/
async capture(paymentOrId: string | Payment): Promise<Payment> {
const payment =
typeof paymentOrId === "string"
? await this.retrieve(paymentOrId)
: paymentOrId
if (payment?.captured_at) {
return payment
}
return await this.atomicPhase_(async (manager: EntityManager) => {
let captureError: Error | null = null
const capturedPayment = await this.paymentProviderService_
.withTransaction(manager)
.capturePayment(payment)
.catch((err) => {
captureError = err
})
if (!capturedPayment) {
await this.eventBusService_
.withTransaction(manager)
.emit(PaymentService.Events.PAYMENT_CAPTURE_FAILED, {
...payment,
error: captureError,
})
throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE,
`Failed to capture Payment ${payment.id}`
)
}
await this.eventBusService_
.withTransaction(manager)
.emit(PaymentService.Events.PAYMENT_CAPTURED, capturedPayment)
return capturedPayment
})
}
/**
* refunds a payment.
* @param paymentOrId - the id or the class instance of the payment
* @param amount - the amount to be refunded from the payment
* @param reason - the refund reason
* @param note - additional note of the refund
* @return the refund created.
*/
async refund(
paymentOrId: string | Payment,
amount: number,
reason: string,
note?: string
): Promise<Refund> {
const payment =
typeof paymentOrId === "string"
? await this.retrieve(paymentOrId)
: paymentOrId
return await this.atomicPhase_(async (manager: EntityManager) => {
if (!payment.captured_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
`Payment ${payment.id} is not captured`
)
}
const refundable = payment.amount - payment.amount_refunded
if (amount > refundable) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
`Only ${refundable} can be refunded from Payment ${payment.id}`
)
}
let refundError: Error | null = null
const refund = await this.paymentProviderService_
.withTransaction(manager)
.refundFromPayment(payment, amount, reason, note)
.catch((err) => {
refundError = err
})
if (!refund) {
await this.eventBusService_
.withTransaction(manager)
.emit(PaymentService.Events.REFUND_FAILED, {
...payment,
error: refundError,
})
throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE,
`Failed to refund Payment ${payment.id}`
)
}
await this.eventBusService_
.withTransaction(manager)
.emit(PaymentService.Events.REFUND_CREATED, refund)
return refund
})
}
}