1 import Stripe from "stripe"
2 import { setTimeout } from "timers/promises"
3 import {
4 AuthorizePaymentInput,
5 AuthorizePaymentOutput,
6 CancelPaymentInput,
7 CancelPaymentOutput,
8 CapturePaymentInput,
9 CapturePaymentOutput,
10 CreateAccountHolderInput,
11 CreateAccountHolderOutput,
12 DeleteAccountHolderInput,
13 DeleteAccountHolderOutput,
14 DeletePaymentMethodInput,
15 DeletePaymentMethodOutput,
16 DeletePaymentInput,
17 DeletePaymentOutput,
18 GetPaymentStatusInput,
19 GetPaymentStatusOutput,
20 InitiatePaymentInput,
21 InitiatePaymentOutput,
22 ListPaymentMethodsInput,
23 ListPaymentMethodsOutput,
24 ProviderWebhookPayload,
25 RefundPaymentInput,
26 RefundPaymentOutput,
27 RetrievePaymentInput,
28 RetrievePaymentOutput,
29 SavePaymentMethodInput,
30 SavePaymentMethodOutput,
31 UpdateAccountHolderInput,
32 UpdateAccountHolderOutput,
33 UpdatePaymentInput,
34 UpdatePaymentOutput,
35 WebhookActionResult,
36 } from "@medusajs/framework/types"
37 import {
38 AbstractPaymentProvider,
39 isDefined,
40 isPresent,
41 PaymentActions,
42 PaymentSessionStatus,
43 } from "@medusajs/framework/utils"
44 import {
45 ErrorCodes,
46 ErrorIntentStatus,
47 PaymentIntentOptions,
48 StripeOptions,
49 } from "../types"
50 import {
51 getAmountFromSmallestUnit,
52 getSmallestUnit,
53 } from "../utils/get-smallest-unit"
54
55 type StripeIndeterminateState = {
56 indeterminate_due_to: string
57 }
58
59 type StripeErrorData = Stripe.PaymentIntent | StripeIndeterminateState
60 type HandledErrorType =
61 | { retry: true }
62 | { retry: false; data: StripeErrorData }
63
64 abstract class StripeBase extends AbstractPaymentProvider<StripeOptions> {
65 protected readonly options_: StripeOptions
66 protected stripe_: Stripe
67 protected container_: Record<string, unknown>
68
69 // All Stripe provider variants share the same options, so warn only once
70 // even though the loader validates each registered service.
71 protected static hasWarnedMissingWebhookSecret = false
72
73 static validateOptions(options: StripeOptions): void {
74 if (!isDefined(options.apiKey)) {
75 throw new Error("Required option `apiKey` is missing in Stripe plugin")
76 }
77
78 if (
79 !isDefined(options.webhookSecret) &&
80 !StripeBase.hasWarnedMissingWebhookSecret
81 ) {
82 StripeBase.hasWarnedMissingWebhookSecret = true
83 console.warn(
84 "Option `webhookSecret` is missing in Stripe plugin. Webhook signature verification will fail, so webhook-dependent payment flows (e.g. 3D Secure, Klarna/Affirm redirects, async capture) will not be able to update orders, leaving them pending after successful charges. Set `webhookSecret` if you rely on Stripe webhooks."
85 )
86 }
87 }
88
89 protected constructor(
90 cradle: Record<string, unknown>,
91 options: StripeOptions
92 ) {
93 // @ts-ignore
94 super(...arguments)
95
96 this.container_ = cradle
97 this.options_ = options
98
99 this.stripe_ = new Stripe(options.apiKey)
100 }
101
102 abstract get paymentIntentOptions(): PaymentIntentOptions
103
104 get options(): StripeOptions {
105 return this.options_
106 }
107
108 normalizePaymentIntentParameters(
109 extra?: Record<string, unknown>
110 ): Partial<Stripe.PaymentIntentCreateParams> {
111 const res = {} as Partial<Stripe.PaymentIntentCreateParams>
112
113 const paymentMethodTypes =
114 (extra?.payment_method_types as string[] | undefined) ??
115 (this.paymentIntentOptions.payment_method_types as string[] | undefined)
116
117 res.description = (extra?.payment_description ??
118 this.options_?.paymentDescription) as string
119
120 res.capture_method =
121 (extra?.capture_method as "automatic" | "manual") ??
122 this.paymentIntentOptions.capture_method ??
123 (this.options_.capture ? "automatic" : "manual")
124
125 res.setup_future_usage =
126 (extra?.setup_future_usage as "off_session" | "on_session" | undefined) ??
127 this.paymentIntentOptions.setup_future_usage
128
129 res.payment_method_types = paymentMethodTypes
130
131 res.payment_method_data =
132 extra?.payment_method_data as Stripe.PaymentIntentCreateParams.PaymentMethodData
133
134 res.payment_method_options =
135 (extra?.payment_method_options as Stripe.PaymentIntentCreateParams.PaymentMethodOptions) ??
136 this.paymentIntentOptions.payment_method_options
137
138 res.automatic_payment_methods =
139 (extra?.automatic_payment_methods as { enabled: true } | undefined) ??
140 (this.options_?.automaticPaymentMethods ? { enabled: true } : undefined)
141
142 res.off_session = extra?.off_session as boolean | undefined
143
144 res.confirm = extra?.confirm as boolean | undefined
145
146 res.payment_method = extra?.payment_method as string | undefined
147
148 res.return_url = extra?.return_url as string | undefined
149
150 // @ts-expect-error - Need to update Stripe SDK
151 res.shared_payment_token = extra?.shared_payment_token as string | undefined
152
153 if (!paymentMethodTypes?.length) {
154 res.payment_method_configuration =
155 (extra?.payment_method_configuration as string | undefined) ??
156 this.options_?.paymentMethodConfiguration
157 }
158
159 return res
160 }
161
162 handleStripeError(error: any): HandledErrorType {
163 switch (error.type) {
164 case "StripeCardError":
165 // Stripe has created a payment intent but it failed
166 // Extract and return paymentIntent object to be stored in payment_session
167 // Allows for reference to the failed intent and potential webhook reconciliation
168 const stripeError = error.raw as Stripe.errors.StripeCardError
169 if (stripeError.payment_intent) {
170 return {
171 retry: false,
172 data: stripeError.payment_intent,
173 }
174 } else {
175 throw this.buildError(
176 "An error occurred in InitiatePayment during creation of stripe payment intent",
177 error
178 )
179 }
180
181 case "StripeConnectionError":
182 case "StripeRateLimitError":
183 // Connection or rate limit errors indicate an uncertain result
184 // Retry the operation
185 return {
186 retry: true,
187 }
188 case "StripeAPIError": {
189 // API errors should be treated as indeterminate per Stripe documentation
190 // Rely on webhooks rather than assuming failure
191 return {
192 retry: false,
193 data: {
194 indeterminate_due_to: "stripe_api_error",
195 },
196 }
197 }
198 default:
199 // For all other errors, there was likely an issue creating the session
200 // on Stripe's servers. Throw an error which will trigger cleanup
201 // and deletion of the payment session.
202 throw this.buildError(
203 "An error occurred in InitiatePayment during creation of stripe payment intent",
204 error
205 )
206 }
207 }
208
209 async executeWithRetry<T>(
210 apiCall: () => Promise<T>,
211 maxRetries: number = 3,
212 baseDelay: number = 1000,
213 currentAttempt: number = 1
214 ): Promise<T | StripeErrorData> {
215 try {
216 return await apiCall()
217 } catch (error) {
218 const handledError = this.handleStripeError(error)
219
220 if (!handledError.retry) {
221 // If retry is false, we know data exists per the type definition
222 return handledError.data
223 }
224
225 if (handledError.retry && currentAttempt <= maxRetries) {
226 // Logic for retrying
227 const delay =
228 baseDelay *
229 Math.pow(2, currentAttempt - 1) *
230 (0.5 + Math.random() * 0.5)
231 await setTimeout(delay)
232 return this.executeWithRetry(
233 apiCall,
234 maxRetries,
235 baseDelay,
236 currentAttempt + 1
237 )
238 }
239 // Retries are exhausted
240 throw this.buildError(
241 "An error occurred in InitiatePayment during creation of stripe payment intent",
242 error
243 )
244 }
245 }
246
247 async getPaymentStatus(
248 input: GetPaymentStatusInput
249 ): Promise<GetPaymentStatusOutput> {
250 const id = input?.data?.id as string
251 if (!id) {
252 throw this.buildError(
253 "No payment intent ID provided while getting payment status",
254 new Error("No payment intent ID provided")
255 )
256 }
257
258 const paymentIntent = await this.stripe_.paymentIntents.retrieve(id, {
259 expand: ["payment_method"],
260 })
261 const statusResponse = this.getStatus(paymentIntent)
262
263 return statusResponse as unknown as GetPaymentStatusOutput
264 }
265
266 async initiatePayment({
267 currency_code,
268 amount,
269 data,
270 context,
271 }: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
272 const additionalParameters = this.normalizePaymentIntentParameters(data)
273
274 const intentRequest: Stripe.PaymentIntentCreateParams = {
275 amount: getSmallestUnit(amount, currency_code),
276 currency: currency_code,
277 metadata: {
278 ...(data?.metadata ?? {}),
279 session_id: data?.session_id as string,
280 },
281 ...additionalParameters,
282 expand: ["payment_method"],
283 }
284
285 intentRequest.customer = context?.account_holder?.data?.id as
286 | string
287 | undefined
288
289 const sessionData = await this.executeWithRetry<Stripe.PaymentIntent>(() =>
290 this.stripe_.paymentIntents.create(intentRequest, {
291 idempotencyKey: context?.idempotency_key,
292 })
293 )
294 const isPaymentIntent = "id" in sessionData
295 return {
296 id: isPaymentIntent ? sessionData.id : (data?.session_id as string),
297 ...(this.getStatus(
298 sessionData as unknown as Stripe.PaymentIntent
299 ) as unknown as Pick<InitiatePaymentOutput, "data" | "status">),
300 }
301 }
302
303 async authorizePayment(
304 input: AuthorizePaymentInput
305 ): Promise<AuthorizePaymentOutput> {
306 return this.getPaymentStatus(input)
307 }
308
309 async cancelPayment({
310 data,
311 context,
312 }: CancelPaymentInput): Promise<CancelPaymentOutput> {
313 try {
314 const id = data?.id as string
315
316 if (!id) {
317 return { data: data }
318 }
319
320 const res = await this.stripe_.paymentIntents.cancel(id, {
321 idempotencyKey: context?.idempotency_key,
322 })
323 return { data: res as unknown as Record<string, unknown> }
324 } catch (error) {
325 if (error.payment_intent?.status === ErrorIntentStatus.CANCELED) {
326 return { data: error.payment_intent }
327 }
328
329 throw this.buildError("An error occurred in cancelPayment", error)
330 }
331 }
332
333 async capturePayment({
334 data,
335 context,
336 }: CapturePaymentInput): Promise<CapturePaymentOutput> {
337 const id = data?.id as string
338
339 try {
340 const intent = await this.stripe_.paymentIntents.capture(id, {
341 idempotencyKey: context?.idempotency_key,
342 })
343 return { data: intent as unknown as Record<string, unknown> }
344 } catch (error) {
345 if (error.code === ErrorCodes.PAYMENT_INTENT_UNEXPECTED_STATE) {
346 if (error.payment_intent?.status === ErrorIntentStatus.SUCCEEDED) {
347 return { data: error.payment_intent }
348 }
349 }
350
351 throw this.buildError("An error occurred in capturePayment", error)
352 }
353 }
354
355 async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {
356 return await this.cancelPayment(input)
357 }
358
359 async refundPayment({
360 amount,
361 data,
362 context,
363 }: RefundPaymentInput): Promise<RefundPaymentOutput> {
364 const id = data?.id as string
365 if (!id) {
366 throw this.buildError(
367 "No payment intent ID provided while refunding payment",
368 new Error("No payment intent ID provided")
369 )
370 }
371
372 try {
373 const currencyCode = data?.currency as string
374 await this.stripe_.refunds.create(
375 {
376 amount: getSmallestUnit(amount, currencyCode),
377 payment_intent: id as string,
378 },
379 {
380 idempotencyKey: context?.idempotency_key,
381 }
382 )
383 } catch (e) {
384 if (e.code !== ErrorCodes.CHARGE_ALREADY_REFUNDED) {
385 throw this.buildError("An error occurred in refundPayment", e)
386 }
387 }
388
389 return { data }
390 }
391
392 async retrievePayment({
393 data,
394 }: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
395 try {
396 const id = data?.id as string
397 const intent = await this.stripe_.paymentIntents.retrieve(id)
398
399 intent.amount = getAmountFromSmallestUnit(intent.amount, intent.currency)
400
401 return { data: intent as unknown as Record<string, unknown> }
402 } catch (e) {
403 throw this.buildError("An error occurred in retrievePayment", e)
404 }
405 }
406
407 async updatePayment({
408 data,
409 currency_code,
410 amount,
411 context,
412 }: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
413 const amountNumeric = getSmallestUnit(amount, currency_code)
414 if (isPresent(amount) && data?.amount === amountNumeric) {
415 return this.getStatus(
416 data as unknown as Stripe.PaymentIntent
417 ) as unknown as UpdatePaymentOutput
418 }
419
420 try {
421 const id = data?.id as string
422 const sessionData = (await this.stripe_.paymentIntents.update(
423 id,
424 {
425 amount: amountNumeric,
426 expand: ["payment_method"],
427 },
428 {
429 idempotencyKey: context?.idempotency_key,
430 }
431 )) as unknown as Record<string, unknown>
432
433 return this.getStatus(
434 sessionData as unknown as Stripe.PaymentIntent
435 ) as unknown as UpdatePaymentOutput
436 } catch (e) {
437 throw this.buildError("An error occurred in updatePayment", e)
438 }
439 }
440
441 async createAccountHolder({
442 context,
443 }: CreateAccountHolderInput): Promise<CreateAccountHolderOutput> {
444 const { account_holder, customer, idempotency_key } = context
445
446 if (account_holder?.data?.id) {
447 return { id: account_holder.data.id as string }
448 }
449
450 if (!customer) {
451 throw this.buildError(
452 "No customer in context",
453 new Error("No customer provided while creating account holder")
454 )
455 }
456
457 const shipping = customer.billing_address
458 ? ({
459 address: {
460 city: customer.billing_address.city,
461 country: customer.billing_address.country_code,
462 line1: customer.billing_address.address_1,
463 line2: customer.billing_address.address_2,
464 postal_code: customer.billing_address.postal_code,
465 state: customer.billing_address.province,
466 },
467 } as Stripe.CustomerCreateParams.Shipping)
468 : undefined
469
470 try {
471 const stripeCustomer = await this.stripe_.customers.create(
472 {
473 email: customer.email,
474 name:
475 customer.company_name ||
476 `${customer.first_name ?? ""} ${customer.last_name ?? ""}`.trim() ||
477 undefined,
478 phone: customer.phone as string | undefined,
479 ...shipping,
480 },
481 {
482 idempotencyKey: idempotency_key,
483 }
484 )
485
486 return {
487 id: stripeCustomer.id,
488 data: stripeCustomer as unknown as Record<string, unknown>,
489 }
490 } catch (e) {
491 throw this.buildError(
492 "An error occurred in createAccountHolder when creating a Stripe customer",
493 e
494 )
495 }
496 }
497
498 async updateAccountHolder({
499 context,
500 }: UpdateAccountHolderInput): Promise<UpdateAccountHolderOutput> {
501 const { account_holder, customer, idempotency_key } = context
502
503 if (!account_holder?.data?.id) {
504 throw this.buildError(
505 "No account holder in context",
506 new Error("No account holder provided while updating account holder")
507 )
508 }
509
510 // If no customer context was provided, we simply don't update anything within the provider
511 if (!customer) {
512 return {}
513 }
514
515 const accountHolderId = account_holder.data.id as string
516
517 const shipping = customer.billing_address
518 ? ({
519 address: {
520 city: customer.billing_address.city,
521 country: customer.billing_address.country_code,
522 line1: customer.billing_address.address_1,
523 line2: customer.billing_address.address_2,
524 postal_code: customer.billing_address.postal_code,
525 state: customer.billing_address.province,
526 },
527 } as Stripe.CustomerCreateParams.Shipping)
528 : undefined
529
530 try {
531 const stripeCustomer = await this.stripe_.customers.update(
532 accountHolderId,
533 {
534 email: customer.email,
535 name:
536 customer.company_name ||
537 `${customer.first_name ?? ""} ${customer.last_name ?? ""}`.trim() ||
538 undefined,
539 phone: customer.phone as string | undefined,
540 ...shipping,
541 },
542 {
543 idempotencyKey: idempotency_key,
544 }
545 )
546
547 return {
548 data: stripeCustomer as unknown as Record<string, unknown>,
549 }
550 } catch (e) {
551 throw this.buildError(
552 "An error occurred in updateAccountHolder when updating a Stripe customer",
553 e
554 )
555 }
556 }
557
558 async deleteAccountHolder({
559 context,
560 }: DeleteAccountHolderInput): Promise<DeleteAccountHolderOutput> {
561 const { account_holder } = context
562 const accountHolderId = account_holder?.data?.id as string | undefined
563 if (!accountHolderId) {
564 throw this.buildError(
565 "No account holder in context",
566 new Error("No account holder provided while deleting account holder")
567 )
568 }
569
570 try {
571 await this.stripe_.customers.del(accountHolderId)
572 return {}
573 } catch (e) {
574 throw this.buildError("An error occurred in deleteAccountHolder", e)
575 }
576 }
577
578 async listPaymentMethods({
579 context,
580 }: ListPaymentMethodsInput): Promise<ListPaymentMethodsOutput> {
581 const accountHolderId = context?.account_holder?.data?.id as
582 | string
583 | undefined
584 if (!accountHolderId) {
585 return []
586 }
587
588 const paymentMethods = await this.stripe_.customers.listPaymentMethods(
589 accountHolderId,
590 // In order to keep the interface simple, we just list the maximum payment methods, which should be enough in almost all cases.
591 // We can always extend the interface to allow additional filtering, if necessary.
592 { limit: 100 }
593 )
594
595 return paymentMethods.data.map((method) => ({
596 id: method.id,
597 data: method as unknown as Record<string, unknown>,
598 }))
599 }
600
601 async savePaymentMethod({
602 context,
603 data,
604 }: SavePaymentMethodInput): Promise<SavePaymentMethodOutput> {
605 const accountHolderId = context?.account_holder?.data?.id as
606 | string
607 | undefined
608
609 if (!accountHolderId) {
610 throw this.buildError(
611 "Account holder not set while saving a payment method",
612 new Error("Missing account holder")
613 )
614 }
615
616 const resp = await this.stripe_.setupIntents.create(
617 {
618 customer: accountHolderId,
619 ...data,
620 },
621 {
622 idempotencyKey: context?.idempotency_key,
623 }
624 )
625
626 return { id: resp.id, data: resp as unknown as Record<string, unknown> }
627 }
628
629 async deletePaymentMethod({
630 context,
631 data,
632 }: DeletePaymentMethodInput): Promise<DeletePaymentMethodOutput> {
633 const paymentMethodId = data?.id as string | undefined
634
635 if (!paymentMethodId) {
636 throw this.buildError(
637 "Payment method ID not set while deleting a payment method",
638 new Error("Missing payment method ID")
639 )
640 }
641
642 await this.stripe_.paymentMethods.detach(paymentMethodId, {
643 idempotencyKey: context?.idempotency_key,
644 })
645
646 return {}
647 }
648
649 private getStatus(paymentIntent: Stripe.PaymentIntent): {
650 data: Stripe.PaymentIntent
651 status: PaymentSessionStatus
652 } {
653 switch (paymentIntent.status) {
654 case "requires_payment_method":
655 if (paymentIntent.last_payment_error) {
656 return { status: PaymentSessionStatus.ERROR, data: paymentIntent }
657 }
658 return { status: PaymentSessionStatus.PENDING, data: paymentIntent }
659 case "requires_confirmation":
660 return { status: PaymentSessionStatus.PENDING, data: paymentIntent }
661 case "processing":
662 if (
663 this.isAsyncPaymentMethod(
664 paymentIntent.payment_method as Stripe.PaymentMethod
665 )
666 ) {
667 return {
668 status: PaymentSessionStatus.PENDING_AUTHORIZATION,
669 data: paymentIntent,
670 }
671 }
672 return { status: PaymentSessionStatus.PENDING, data: paymentIntent }
673 case "requires_action":
674 return {
675 status: PaymentSessionStatus.REQUIRES_MORE,
676 data: paymentIntent,
677 }
678 case "canceled":
679 return { status: PaymentSessionStatus.CANCELED, data: paymentIntent }
680 case "requires_capture":
681 return { status: PaymentSessionStatus.AUTHORIZED, data: paymentIntent }
682 case "succeeded":
683 return { status: PaymentSessionStatus.CAPTURED, data: paymentIntent }
684 default:
685 return { status: PaymentSessionStatus.PENDING, data: paymentIntent }
686 }
687 }
688
689 async getWebhookActionAndData(
690 webhookData: ProviderWebhookPayload["payload"]
691 ): Promise<WebhookActionResult> {
692 const event = this.constructWebhookEvent(webhookData)
693 const intent = event.data.object as Stripe.PaymentIntent
694
695 const { currency } = intent
696
697 // Payment intents created by Medusa always carry the originating payment
698 // session id in their metadata (see `initiatePayment`). An intent without
699 // one did not originate from this Medusa instance - e.g. an event from
700 // another integration sharing the same Stripe account - and must not be
701 // acted upon, so we treat it as an unsupported event.
702 if (!intent.metadata?.session_id) {
703 return { action: PaymentActions.NOT_SUPPORTED }
704 }
705
706 switch (event.type) {
707 case "payment_intent.created":
708 case "payment_intent.processing":
709 const webhookPaymentMethod = intent.payment_method
710 const paymentMethod =
711 typeof webhookPaymentMethod === "object"
712 ? (intent.payment_method as Stripe.PaymentMethod)
713 : typeof webhookPaymentMethod === "string"
714 ? await this.stripe_.paymentMethods.retrieve(webhookPaymentMethod)
715 : null
716
717 return {
718 action:
719 paymentMethod && this.isAsyncPaymentMethod(paymentMethod)
720 ? PaymentActions.PENDING_AUTHORIZATION
721 : PaymentActions.PENDING,
722 data: {
723 session_id: intent.metadata.session_id,
724 amount: getAmountFromSmallestUnit(intent.amount, currency),
725 },
726 }
727 case "payment_intent.canceled":
728 return {
729 action: PaymentActions.CANCELED,
730 data: {
731 session_id: intent.metadata.session_id,
732 amount: getAmountFromSmallestUnit(intent.amount, currency),
733 },
734 }
735 case "payment_intent.payment_failed":
736 return {
737 action: PaymentActions.FAILED,
738 data: {
739 session_id: intent.metadata.session_id,
740 amount: getAmountFromSmallestUnit(intent.amount, currency),
741 },
742 }
743 case "payment_intent.requires_action":
744 return {
745 action: PaymentActions.REQUIRES_MORE,
746 data: {
747 session_id: intent.metadata.session_id,
748 amount: getAmountFromSmallestUnit(intent.amount, currency),
749 },
750 }
751 case "payment_intent.amount_capturable_updated":
752 return {
753 action: PaymentActions.AUTHORIZED,
754 data: {
755 session_id: intent.metadata.session_id,
756 amount: getAmountFromSmallestUnit(
757 intent.amount_capturable,
758 currency
759 ),
760 },
761 }
762 case "payment_intent.partially_funded":
763 return {
764 action: PaymentActions.REQUIRES_MORE,
765 data: {
766 session_id: intent.metadata.session_id,
767 amount: getAmountFromSmallestUnit(
768 intent.next_action?.display_bank_transfer_instructions
769 ?.amount_remaining ?? intent.amount,
770 currency
771 ),
772 },
773 }
774 case "payment_intent.succeeded":
775 return {
776 action: PaymentActions.SUCCESSFUL,
777 data: {
778 session_id: intent.metadata.session_id,
779 amount: getAmountFromSmallestUnit(intent.amount_received, currency),
780 },
781 }
782
783 default:
784 return { action: PaymentActions.NOT_SUPPORTED }
785 }
786 }
787
788 private isAsyncPaymentMethod(paymentMethod: Stripe.PaymentMethod): boolean {
789 return (
790 this.options_.asyncPaymentMethodTypes?.includes(paymentMethod.type) ??
791 false
792 )
793 }
794
795 /**
796 * Constructs Stripe Webhook event
797 * @param {object} data - the data of the webhook request: req.body
798 * ensures integrity of the webhook event
799 * @return {object} Stripe Webhook event
800 */
801 constructWebhookEvent(data: ProviderWebhookPayload["payload"]): Stripe.Event {
802 const signature = data.headers["stripe-signature"] as string
803
804 try {
805 return this.stripe_.webhooks.constructEvent(
806 data.rawData as string | Buffer,
807 signature,
808 this.options_.webhookSecret
809 )
810 } catch (error) {
811 throw this.buildError("An error occurred in constructWebhookEvent", error)
812 }
813 }
814 protected buildError(message: string, error: Error): Error {
815 const errorDetails =
816 "raw" in error ? (error.raw as Stripe.StripeRawError) : error
817
818 return new Error(
819 `${message}: ${error.message}. ${
820 "detail" in errorDetails ? errorDetails.detail : ""
821 }`.trim()
822 )
823 }
824 }
825
826 export default StripeBase