* Gets and selects the appropriate payment method for an organization. * Handles both card and link payment methods, with preference for existing default.
(params: {
organizationId: string
stripeCustomerId: string
logger: Logger
})
| 347 | * Handles both card and link payment methods, with preference for existing default. |
| 348 | */ |
| 349 | async function getOrganizationPaymentMethod(params: { |
| 350 | organizationId: string |
| 351 | stripeCustomerId: string |
| 352 | logger: Logger |
| 353 | }): Promise<string> { |
| 354 | const { organizationId, stripeCustomerId, logger } = params |
| 355 | const logContext = { organizationId, stripeCustomerId } |
| 356 | |
| 357 | // Get payment methods for the organization - include both card and link types |
| 358 | const [cardPaymentMethods, linkPaymentMethods] = await Promise.all([ |
| 359 | stripeServer.paymentMethods.list({ |
| 360 | customer: stripeCustomerId, |
| 361 | type: 'card', |
| 362 | }), |
| 363 | stripeServer.paymentMethods.list({ |
| 364 | customer: stripeCustomerId, |
| 365 | type: 'link', |
| 366 | }), |
| 367 | ]) |
| 368 | |
| 369 | const allPaymentMethods = [ |
| 370 | ...cardPaymentMethods.data, |
| 371 | ...linkPaymentMethods.data, |
| 372 | ] |
| 373 | |
| 374 | logger.debug( |
| 375 | { |
| 376 | ...logContext, |
| 377 | cardPaymentMethodCount: cardPaymentMethods.data.length, |
| 378 | linkPaymentMethodCount: linkPaymentMethods.data.length, |
| 379 | totalPaymentMethodCount: allPaymentMethods.length, |
| 380 | paymentMethodIds: allPaymentMethods.map((pm) => pm.id), |
| 381 | paymentMethodTypes: allPaymentMethods.map((pm) => pm.type), |
| 382 | }, |
| 383 | 'Retrieved payment methods for organization (cards and link)', |
| 384 | ) |
| 385 | |
| 386 | if (allPaymentMethods.length === 0) { |
| 387 | throw new AutoTopupPaymentError( |
| 388 | 'No payment methods available for organization', |
| 389 | ) |
| 390 | } |
| 391 | |
| 392 | // Get the customer to check for default payment method |
| 393 | const customer = await stripeServer.customers.retrieve(stripeCustomerId) |
| 394 | |
| 395 | let paymentMethodToUse: string | null = null |
| 396 | |
| 397 | // Check if there's already a default payment method |
| 398 | if ( |
| 399 | customer && |
| 400 | !customer.deleted && |
| 401 | customer.invoice_settings?.default_payment_method |
| 402 | ) { |
| 403 | const defaultPaymentMethodId = |
| 404 | typeof customer.invoice_settings.default_payment_method === 'string' |
| 405 | ? customer.invoice_settings.default_payment_method |
| 406 | : customer.invoice_settings.default_payment_method.id |
no outgoing calls
no test coverage detected