-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathservice.js
More file actions
213 lines (190 loc) · 5.58 KB
/
service.js
File metadata and controls
213 lines (190 loc) · 5.58 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
213
import { StatusCodes } from 'http-status-codes'
import { createLogger } from '~/src/server/common/helpers/logging/logger.js'
import { get, post, postJson } from '~/src/server/services/httpService.js'
const PAYMENT_BASE_URL = 'https://publicapi.payments.service.gov.uk'
const PAYMENT_ENDPOINT = '/v1/payments'
const logger = createLogger()
/**
* @param {string} apiKey
* @returns {{ Authorization: string }}
*/
function getAuthHeaders(apiKey) {
return {
Authorization: `Bearer ${apiKey}`
}
}
export class PaymentService {
/** @type {string} */
#apiKey
/**
* @param {string} apiKey - API key to use (global config for test value, per-form config for live value)
*/
constructor(apiKey) {
this.#apiKey = apiKey
}
/**
* Creates a payment with delayed capture (pre-authorisation)
* @param {number} amount - in pence
* @param {string} description
* @param {string} returnUrl
* @param {string} reference
* @param {{ formId: string, slug: string }} metadata
*/
async createPayment(amount, description, returnUrl, reference, metadata) {
const response = await this.postToPayProvider({
amount,
description,
reference,
metadata,
return_url: returnUrl,
delayed_capture: true
})
logger.info(
{
event: {
module: 'payment',
action: 'create-payment',
outcome: 'success',
reason: `amount=${amount}`,
reference: response.payment_id
}
},
`[payment] Created payment and user taken to enter pre-auth details for paymentId=${response.payment_id}`
)
return {
paymentId: response.payment_id,
paymentUrl: response._links.next_url.href
}
}
/**
* @param {string} paymentId
* @returns {Promise<GetPaymentResponse>}
*/
async getPaymentStatus(paymentId) {
const getByType = /** @type {typeof get<GetPaymentApiResponse>} */ (get)
try {
const response = await getByType(
`${PAYMENT_BASE_URL}${PAYMENT_ENDPOINT}/${paymentId}`,
{
headers: getAuthHeaders(this.#apiKey),
json: true
}
)
if (response.error) {
const errorMessage =
response.error instanceof Error
? response.error.message
: JSON.stringify(response.error)
throw new Error(`Failed to get payment status: ${errorMessage}`)
}
const state = response.payload.state
logger.info(
{
event: {
module: 'payment',
action: 'get-payment-status',
outcome:
state.status === 'capturable' || state.status === 'success'
? 'success'
: 'failure',
reason: `status:${state.status} code:${state.code ?? 'N/A'} message:${state.message ?? 'N/A'}`,
reference: paymentId
}
},
`[payment] Got payment status for paymentId=${paymentId}: status=${state.status}`
)
return {
state,
_links: response.payload._links,
email: response.payload.email,
paymentId: response.payload.payment_id,
amount: response.payload.amount
}
} catch (err) {
const error = /** @type {Error} */ (err)
logger.error(
error,
`[payment] Error getting payment status for paymentId=${paymentId}: ${error.message}`
)
throw err
}
}
/**
* Captures a payment that is in 'capturable' status
* @param {string} paymentId
* @param {number} amount
* @returns {Promise<boolean>}
*/
async capturePayment(paymentId, amount) {
try {
const response = await post(
`${PAYMENT_BASE_URL}${PAYMENT_ENDPOINT}/${paymentId}/capture`,
{
headers: getAuthHeaders(this.#apiKey)
}
)
const statusCode = response.res.statusCode
if (
statusCode === StatusCodes.OK ||
statusCode === StatusCodes.NO_CONTENT
) {
logger.info(
{
event: {
module: 'payment',
action: 'capture-payment',
outcome: 'success',
reason: `amount=${amount}`,
reference: paymentId
}
},
`[payment] Successfully captured payment for paymentId=${paymentId}`
)
return true
}
logger.error(
`[payment] Capture failed for paymentId=${paymentId}: HTTP ${statusCode}`
)
return false
} catch (err) {
const error = /** @type {Error} */ (err)
logger.error(
error,
`[payment] Error capturing payment for paymentId=${paymentId}: ${error.message}`
)
throw err
}
}
/**
* @param {CreatePaymentRequest} payload
*/
async postToPayProvider(payload) {
const postJsonByType =
/** @type {typeof postJson<CreatePaymentResponse>} */ (postJson)
try {
const response = await postJsonByType(
`${PAYMENT_BASE_URL}${PAYMENT_ENDPOINT}`,
{
payload,
headers: getAuthHeaders(this.#apiKey)
}
)
if (response.payload?.state.status !== 'created') {
throw new Error(
`Failed to create payment for reference=${payload.reference}`
)
}
return response.payload
} catch (err) {
const error = /** @type {Error} */ (err)
logger.error(
error,
`[payment] Error creating payment for reference=${payload.reference}: ${error.message}`
)
throw err
}
}
}
/**
* @import { CreatePaymentRequest, CreatePaymentResponse, GetPaymentApiResponse, GetPaymentResponse } from '~/src/server/plugins/payment/types.js'
*/