-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathJWPCheckoutService.ts
More file actions
346 lines (298 loc) · 9.78 KB
/
JWPCheckoutService.ts
File metadata and controls
346 lines (298 loc) · 9.78 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import InPlayer, { type AccessFee, type MerchantPaymentMethod } from '@inplayer-org/inplayer.js';
import { inject, injectable, named } from 'inversify';
import { isSVODOffer } from '../../../utils/offers';
import type {
CardPaymentData,
CreateOrder,
CreateOrderArgs,
GetEntitlements,
GetEntitlementsResponse,
GetOffers,
GetPaymentMethods,
GetSubscriptionSwitch,
GetSubscriptionSwitches,
Offer,
Order,
Payment,
PaymentMethod,
PaymentWithAdyen,
PaymentWithoutDetails,
PaymentWithPayPal,
SwitchSubscription,
UpdateOrder,
} from '../../../../types/checkout';
import CheckoutService from '../CheckoutService';
import type { ServiceResponse } from '../../../../types/service';
import { isCommonError } from '../../../utils/api';
import AccountService from '../AccountService';
@injectable()
export default class JWPCheckoutService extends CheckoutService {
private readonly cardPaymentProvider = 'stripe';
private formatPaymentMethod = (method: MerchantPaymentMethod, cardPaymentProvider: string): PaymentMethod => {
return {
id: method.id,
methodName: method.method_name.toLocaleLowerCase(),
provider: cardPaymentProvider,
logoUrl: '',
} as PaymentMethod;
};
private formatEntitlements = (expiresAt: number = 0, accessGranted: boolean = false): ServiceResponse<GetEntitlementsResponse> => {
return {
errors: [],
responseData: {
accessGranted,
expiresAt,
},
};
};
/**
* Format a (Cleeng like) offer id for the given access fee (pricing option). For JWP, we need the asset id and
* access fee id in some cases.
*/
private formatOfferId(offer: AccessFee) {
const ppvOffers = ['ppv', 'ppv_custom'];
return ppvOffers.includes(offer.access_type.name) ? `C${offer.item_id}_${offer.id}` : `S${offer.item_id}_${offer.id}`;
}
/**
* Parse the given offer id and extract the asset id.
* The offer id might be the Cleeng format (`S<assetId>_<pricingOptionId>`) or the asset id as string.
*/
private parseOfferId(offerId: string | number) {
if (typeof offerId === 'string') {
// offer id format `S<assetId>_<pricingOptionId>`
if (offerId.startsWith('C') || offerId.startsWith('S')) {
return parseInt(offerId.slice(1).split('_')[0]);
}
// offer id format `<assetId>`
return parseInt(offerId);
}
return offerId;
}
private formatOffer = (offer: AccessFee): Offer => {
return {
id: offer.id,
offerId: this.formatOfferId(offer),
offerCurrency: offer.currency,
customerPriceInclTax: offer.amount,
customerCurrency: offer.currency,
offerTitle: offer.description,
active: true,
period: offer.access_type.period === 'month' && offer.access_type.quantity === 12 ? 'year' : offer.access_type.period,
freePeriods: offer.trial_period ? 1 : 0,
} as Offer;
};
private formatOrder = (payload: CreateOrderArgs): Order => {
return {
id: payload.offer.id,
customerId: payload.customerId,
offerId: payload.offer.offerId,
totalPrice: payload.offer.customerPriceInclTax,
priceBreakdown: {
offerPrice: payload.offer.customerPriceInclTax,
// @TODO is this correct?
discountAmount: payload.offer.customerPriceInclTax,
discountedPrice: payload.offer.customerPriceInclTax,
paymentMethodFee: 0,
taxValue: 0,
},
taxRate: 0,
currency: payload.offer.offerCurrency || 'EUR',
requiredPaymentDetails: true,
} as Order;
};
constructor(@inject(AccountService) @named('JWP') private readonly accountService: AccountService) {
super();
}
createOrder: CreateOrder = async (payload) => {
return {
errors: [],
responseData: {
message: '',
order: this.formatOrder(payload),
success: true,
},
};
};
getOffers: GetOffers = async (payload) => {
const offers = await Promise.all(
payload.offerIds.map(async (offerId) => {
try {
const { data } = await InPlayer.Asset.getAssetAccessFees(this.parseOfferId(offerId));
return data?.map((offer) => this.formatOffer(offer));
} catch {
throw new Error('Failed to get offers');
}
}),
);
return offers.flat();
};
getPaymentMethods: GetPaymentMethods = async () => {
try {
const response = await InPlayer.Payment.getPaymentMethods();
const paymentMethods: PaymentMethod[] = [];
response.data.forEach((method: MerchantPaymentMethod) => {
if (['card', 'paypal'].includes(method.method_name.toLowerCase())) {
paymentMethods.push(this.formatPaymentMethod(method, this.cardPaymentProvider));
}
});
return {
errors: [],
responseData: {
message: '',
paymentMethods,
status: 1,
},
};
} catch {
throw new Error('Failed to get payment methods');
}
};
paymentWithPayPal: PaymentWithPayPal = async (payload) => {
try {
const response = await InPlayer.Payment.getPayPalParams({
origin: payload.waitingUrl,
accessFeeId: payload.order.id,
paymentMethod: 2,
voucherCode: payload.couponCode,
});
if (response.data?.id) {
return {
errors: ['Already have an active access'],
responseData: {
redirectUrl: payload.errorUrl,
},
};
}
return {
errors: [],
responseData: {
redirectUrl: response.data.endpoint,
},
};
} catch {
throw new Error('Failed to generate PayPal payment url');
}
};
iFrameCardPayment: PaymentWithAdyen = async () => {
return {
errors: [],
responseData: {} as Payment,
};
};
paymentWithoutDetails: PaymentWithoutDetails = async () => {
return {
errors: [],
responseData: {} as Payment,
};
};
updateOrder: UpdateOrder = async ({ order, couponCode }) => {
try {
const response = await InPlayer.Voucher.getDiscount({
voucherCode: `${couponCode}`,
accessFeeId: order.id,
});
const discountAmount = order.totalPrice - response.data.amount;
const updatedOrder: Order = {
...order,
totalPrice: response.data.amount,
priceBreakdown: {
...order.priceBreakdown,
discountAmount,
discountedPrice: discountAmount,
},
discount: {
applied: true,
type: 'coupon',
periods: response.data.discount_duration,
},
};
return {
errors: [],
responseData: {
message: 'successfully updated',
order: updatedOrder,
success: true,
},
};
} catch (error: unknown) {
if (isCommonError(error) && error.response.data.message === 'Voucher not found') {
throw new Error('Invalid coupon code');
}
throw new Error('An unknown error occurred');
}
};
getEntitlements: GetEntitlements = async ({ offerId }) => {
try {
const response = await InPlayer.Asset.checkAccessForAsset(this.parseOfferId(offerId));
return this.formatEntitlements(response.data.expires_at, true);
} catch {
return this.formatEntitlements();
}
};
directPostCardPayment = async (cardPaymentPayload: CardPaymentData, order: Order, referrer: string, returnUrl: string) => {
const payload = {
number: cardPaymentPayload.cardNumber.replace(/\s/g, ''),
cardName: cardPaymentPayload.cardholderName,
expMonth: cardPaymentPayload.cardExpMonth || '',
expYear: cardPaymentPayload.cardExpYear || '',
cvv: cardPaymentPayload.cardCVC,
accessFee: order.id,
paymentMethod: 1,
voucherCode: cardPaymentPayload.couponCode,
referrer,
returnUrl,
};
try {
if (isSVODOffer(order)) {
await InPlayer.Subscription.createSubscription(payload);
} else {
await InPlayer.Payment.createPayment(payload);
}
return true;
} catch {
throw new Error('Failed to make payment');
}
};
getSubscriptionSwitches: GetSubscriptionSwitches = async (payload) => {
const { data } = await InPlayer.Asset.getAssetAccessFees(this.parseOfferId(payload.offerId));
const subscriptionSwitches = data?.filter((accessFee) => accessFee.item.plan_switch_enabled).map((accessFee) => this.formatOffer(accessFee)) || [];
return { responseData: subscriptionSwitches, errors: [] };
};
getOrder = undefined;
switchSubscription: SwitchSubscription = async (payload) => {
const { subscription, toOfferId } = payload;
const accessFeeId = parseInt(toOfferId.split('_')[1]);
try {
const response = await InPlayer.Subscription.changeSubscriptionPlan({
access_fee_id: accessFeeId,
inplayer_token: String(subscription.subscriptionId),
});
await this.accountService.updateCustomer({
metadata: {
[`${subscription.subscriptionId}_pending_downgrade`]: toOfferId,
},
});
return {
errors: [],
responseData: response.data.message,
};
} catch {
throw new Error('Failed to change subscription');
}
};
getSubscriptionSwitch: GetSubscriptionSwitch = async ({ subscription }) => {
if (subscription.pendingSwitchId) {
const offers = await this.getOffers({ offerIds: [subscription.offerId] });
return { responseData: offers.find((offer) => offer.offerId === subscription.pendingSwitchId) || null, errors: [] };
}
return { responseData: null, errors: [] };
};
createAdyenPaymentSession = undefined;
initialAdyenPayment = undefined;
finalizeAdyenPayment = undefined;
updatePaymentMethodWithPayPal = undefined;
deletePaymentMethod = undefined;
addAdyenPaymentDetails = undefined;
finalizeAdyenPaymentDetails = undefined;
getOffer = undefined;
}