From 69b8e3676dd0637ebf0b578f8854ede271d0e4a9 Mon Sep 17 00:00:00 2001 From: Sridharan Gopalan Date: Fri, 20 Nov 2026 12:33:47 -0800 Subject: [PATCH 1/3] fix(commerce-server): forward checkout payment methods (COMMEX-2267) --- .changeset/commex-2267-google-pay.md | 5 ++ packages/commerce-server/README.md | 22 +++++++++ .../docs/checkout-configuration.md | 4 +- packages/commerce-server/src/config.test.ts | 43 +++++++++++++++++ .../src/configuration-integration.test.ts | 13 +++++ .../src/create-checkout-session.test.ts | 26 ++++++++++ packages/commerce-server/src/index.ts | 4 ++ .../src/lib/commerce/checkout-config.ts | 47 +++++++++++++++++++ .../src/lib/commerce/checkout-subgraph.ts | 4 +- .../lib/commerce/create-checkout-session.ts | 5 +- 10 files changed, 168 insertions(+), 5 deletions(-) create mode 100644 .changeset/commex-2267-google-pay.md diff --git a/.changeset/commex-2267-google-pay.md b/.changeset/commex-2267-google-pay.md new file mode 100644 index 000000000..1394727d7 --- /dev/null +++ b/.changeset/commex-2267-google-pay.md @@ -0,0 +1,5 @@ +--- +'@godaddy/gd-commerce-server': patch +--- + +Forward server-configured checkout payment methods, including standard Google Pay, for cart, Buy Now, and non-catalog checkout. Keep the standard GoDaddy card default when optional payment settings are absent or malformed, without resetting valid checkout flags. diff --git a/packages/commerce-server/README.md b/packages/commerce-server/README.md index 0f4a860b6..30c060e53 100644 --- a/packages/commerce-server/README.md +++ b/packages/commerce-server/README.md @@ -24,6 +24,28 @@ The default configuration reads these **server-only environment variables** on e - `GODADDY_CURRENCY_CODE` - Optional `GODADDY_CHECKOUT_CONFIGURATION`: JSON with boolean `enablePromotionCodes`, `enableTaxCollection`, and `enableShipping` fields. All three default to false when this variable is absent or malformed so configuration discovery cannot prevent checkout creation. Optional `shipping` accepts the checkout API's `originAddress` or `fulfillmentLocationId`; omit it to use store configuration. +### Standard Google Pay + +Set `paymentMethods` inside the server-only checkout JSON. Keep the existing values for the three capability flags; this example has all three disabled: + +```json +{ + "enablePromotionCodes": false, + "enableTaxCollection": false, + "enableShipping": false, + "paymentMethods": { + "card": { "processor": "godaddy", "checkoutTypes": ["standard"] }, + "googlePay": { "processor": "godaddy", "checkoutTypes": ["standard"] } + } +} +``` + +The server forwards payment methods for cart, Buy Now, and trusted non-catalog checkout. Checkout API requires `processor` and `checkoutTypes` for each configured payment method; an empty `googlePay` object is invalid. The merchant's processor and the shopper's browser still determine availability. This configuration does not enable Apple Pay. + +Without `paymentMethods`, checkout keeps standard GoDaddy card payments. Invalid optional payment methods use that same fallback without clearing valid shipping, tax, or promotion flags. Payment methods accept the Checkout API method names and nullable method values. Each non-null method requires a nonempty `processor` and a nonempty array of `checkoutTypes`. Unknown names or method fields are invalid. Hosts supplying `CommerceConfiguration.readCheckout()` directly must validate their own values. Browser request bodies cannot select payment methods. + +Existing apps must install a release containing this change, update their lockfile, rebuild, and redeploy. A configuration update alone does not upgrade an installed package. A rebuild with an unchanged lockfile can keep the old code. The Airo integration also needs an updated configuration bridge that retains `paymentMethods`. + See [Checkout configuration](docs/checkout-configuration.md) for the temporary build-time synchronization flow and its eventual-consistency limitation. The API origin defaults to `https://api.godaddy.com`. The package does not load files, provision merchants, or assign application attribution. Hosts own these concerns and any readiness checks or retries before invoking Commerce. diff --git a/packages/commerce-server/docs/checkout-configuration.md b/packages/commerce-server/docs/checkout-configuration.md index 8e09e2680..dcf7b81da 100644 --- a/packages/commerce-server/docs/checkout-configuration.md +++ b/packages/commerce-server/docs/checkout-configuration.md @@ -33,7 +33,7 @@ Commerce Admin already exposes this lookup to builders through the `commerce_che Until Checkout API performs App Registry discovery itself: 1. During every initial build and rebuild/redeploy, the builder calls `commerce_checkout_configuration_get`. -2. The deployment writes the three returned feature flags to the server-only `GODADDY_CHECKOUT_CONFIGURATION` value; it does not copy the full MCP response or generate conditional application code. +2. The deployment writes the three returned feature flags and its server-owned payment-method policy to `GODADDY_CHECKOUT_CONFIGURATION`; it does not copy the full MCP response or generate conditional application code. For standard GoDaddy Payments Google Pay, add `paymentMethods: { card: { processor: 'godaddy', checkoutTypes: ['standard'] }, googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } }` to the existing JSON. 3. When Checkout is selected, `commerce-server` reads that value and explicitly configures the new checkout session. 4. The enabled providers calculate live rates and adjustments during checkout. @@ -49,6 +49,8 @@ For example: Restoring the server reader alone does not discover merchant settings: the builder/deployment integration must populate this value. Shipping-origin address details do not need to be copied into application code; hosted checkout can use store configuration. +The package forwards configured payment methods for all three session paths. Missing or malformed optional payment settings fall back to standard GoDaddy card checkout and do not reset valid feature flags. Upgrade and rebuild existing consumers before relying on this field. Apple Pay and its domain-registration prerequisites are separate work. + The accepted stopgap is eventually consistent: a provider enabled or disabled after deployment is reflected on the next rebuild, not immediately. This is acceptable only while the Checkout API change is pending. If the MCP lookup fails, the deployment does not receive the expected flags, or the server value is malformed, checkout falls back to all optional capabilities disabled. In particular, it sends `enableShipping: false` rather than preventing checkout creation. Builders should surface the lookup problem during the build, but it must not make the deployed checkout unusable. diff --git a/packages/commerce-server/src/config.test.ts b/packages/commerce-server/src/config.test.ts index a2c6a9206..b1e9956f0 100644 --- a/packages/commerce-server/src/config.test.ts +++ b/packages/commerce-server/src/config.test.ts @@ -113,4 +113,47 @@ describe('Commerce runtime configuration', () => { enableShipping: false, }); }); + + it('retains standard Google Pay settings alongside existing checkout capabilities', (): void => { + const paymentMethods = { + card: { processor: 'godaddy', checkoutTypes: ['standard'] }, + googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] }, + }; + const checkout = { enablePromotionCodes: true, enableTaxCollection: true, enableShipping: false }; + const configuration = createRuntimeCommerceConfiguration({ + environment: { + ...environment(), + GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ ...checkout, paymentMethods }), + }, + }); + expect(configuration.readCheckout()).toEqual({ ...checkout, paymentMethods }); + }); + + it.each([ + null, + [], + {}, + { unsupported: {} }, + { googlePay: {} }, + { googlePay: { processor: 'godaddy' } }, + { googlePay: { checkoutTypes: ['standard'] } }, + { googlePay: 'true' }, + { googlePay: { processor: 123 } }, + { googlePay: { checkoutTypes: 'standard' } }, + { googlePay: { checkoutTypes: [] } }, + { googlePay: { checkoutTypes: [null] } }, + { googlePay: { secret: 'not-allowed' } }, + ])( + 'falls back from invalid optional payment methods without clearing valid flags: %j', + (paymentMethods): void => { + const checkout = { enablePromotionCodes: true, enableTaxCollection: true, enableShipping: false }; + const configuration = createRuntimeCommerceConfiguration({ + environment: { + ...environment(), + GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ ...checkout, paymentMethods }), + }, + }); + expect(configuration.readCheckout()).toEqual(checkout); + }, + ); }); diff --git a/packages/commerce-server/src/configuration-integration.test.ts b/packages/commerce-server/src/configuration-integration.test.ts index c5c06b05f..fc7c2318b 100644 --- a/packages/commerce-server/src/configuration-integration.test.ts +++ b/packages/commerce-server/src/configuration-integration.test.ts @@ -230,6 +230,10 @@ it.each([undefined, 'https://api.example.com', 'https://api.example.com:8443'])( if (body.query.includes('CreateCheckoutSession')) { expect(body.variables.input.sourceApp).toBe(sourceApp); expect(body.variables.input.owner).toBe(owner); + expect(body.variables.input.paymentMethods).toEqual({ + card: { processor: 'godaddy', checkoutTypes: ['standard'] }, + googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] }, + }); return Response.json({ data: { createCheckoutSession: { @@ -256,6 +260,15 @@ it.each([undefined, 'https://api.example.com', 'https://api.example.com:8443'])( GODADDY_STORE_ID: 'store-1', GODADDY_CHANNEL_ID: 'channel-1', GODADDY_CURRENCY_CODE: 'USD', + GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ + enablePromotionCodes: false, + enableTaxCollection: false, + enableShipping: false, + paymentMethods: { + card: { processor: 'godaddy', checkoutTypes: ['standard'] }, + googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] }, + }, + }), }, }); const app = express(); diff --git a/packages/commerce-server/src/create-checkout-session.test.ts b/packages/commerce-server/src/create-checkout-session.test.ts index a5508c94a..56cbb6460 100644 --- a/packages/commerce-server/src/create-checkout-session.test.ts +++ b/packages/commerce-server/src/create-checkout-session.test.ts @@ -111,6 +111,32 @@ describe('createCheckoutSession', () => { }); }); + it.each(flows)( + 'forwards server-configured Google Pay for %s checkout', + async (_name, params): Promise => { + const paymentMethods = { + card: { processor: 'godaddy', checkoutTypes: ['standard'] }, + googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] }, + }; + checkout = { ...checkout, paymentMethods }; + await createCheckoutSession(params, configuration); + expect(mockGqlRequest.mock.calls[0]?.[0].variables.input.paymentMethods).toEqual(paymentMethods); + }, + ); + + it('does not let checkout callers override server-owned payment methods', async (): Promise => { + await createCheckoutSession( + { + ...cart, + paymentMethods: { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + } as CreateCheckoutSessionParams, + configuration, + ); + expect(mockGqlRequest.mock.calls[0]?.[0].variables.input.paymentMethods).toEqual({ + card: { processor: 'godaddy', checkoutTypes: ['standard'] }, + }); + }); + it.each(flows)('uses only host-owned attribution for %s checkout', async (_name, params): Promise => { config = { ...config, sourceApp: 'merchant-site', owner: 'merchant-orders' }; mockGqlRequest.mockResolvedValue(response({ sourceApp: 'merchant-site' })); diff --git a/packages/commerce-server/src/index.ts b/packages/commerce-server/src/index.ts index b968931c9..4b76349b8 100644 --- a/packages/commerce-server/src/index.ts +++ b/packages/commerce-server/src/index.ts @@ -4,6 +4,10 @@ export { parseCommerceCheckoutConfiguration, } from './lib/commerce/checkout-config'; export type { CheckoutReturnUrls } from './lib/commerce/checkout-return-urls'; +export type { + CheckoutSessionPaymentMethodConfigInput, + CheckoutSessionPaymentMethodsInput, +} from './lib/commerce/checkout-subgraph'; export type { CommerceErrorLogContext, CommerceLogger, diff --git a/packages/commerce-server/src/lib/commerce/checkout-config.ts b/packages/commerce-server/src/lib/commerce/checkout-config.ts index 6568a42d3..e38d2ae67 100644 --- a/packages/commerce-server/src/lib/commerce/checkout-config.ts +++ b/packages/commerce-server/src/lib/commerce/checkout-config.ts @@ -1,3 +1,5 @@ +import type { CheckoutSessionPaymentMethodsInput } from './checkout-subgraph'; + /** Shipping options accepted by the hosted checkout API. Omit to use the store's configuration. */ export interface CommerceCheckoutShippingConfiguration { readonly originAddress?: Readonly>; @@ -9,6 +11,49 @@ export interface CommerceCheckoutConfiguration { readonly enableTaxCollection: boolean; readonly enableShipping: boolean; readonly shipping?: CommerceCheckoutShippingConfiguration; + readonly paymentMethods?: CheckoutSessionPaymentMethodsInput; +} + +const PAYMENT_METHOD_NAMES = new Set([ + 'ach', + 'applePay', + 'card', + 'ccavenue', + 'express', + 'googlePay', + 'mercadopago', + 'offline', + 'paypal', + 'paze', +]); + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** Invalid optional payment settings fall back independently of the existing checkout flags. */ +function paymentMethods(value: unknown): CheckoutSessionPaymentMethodsInput | undefined { + if (!isRecord(value) || Object.keys(value).length === 0) return undefined; + for (const [name, method] of Object.entries(value)) { + if (!PAYMENT_METHOD_NAMES.has(name as keyof CheckoutSessionPaymentMethodsInput)) return undefined; + if (method === null) continue; + if ( + !isRecord(method) || + Object.keys(method).some((key) => key !== 'processor' && key !== 'checkoutTypes') + ) { + return undefined; + } + if (typeof method.processor !== 'string' || !method.processor.trim()) { + return undefined; + } + if ( + !Array.isArray(method.checkoutTypes) || + method.checkoutTypes.length === 0 || + !method.checkoutTypes.every((type: unknown) => typeof type === 'string' && type.trim() !== '') + ) + return undefined; + } + return value as CheckoutSessionPaymentMethodsInput; } const DEFAULT_CHECKOUT_CONFIGURATION: CommerceCheckoutConfiguration = { @@ -53,10 +98,12 @@ export function parseCommerceCheckoutConfiguration(raw: string | undefined): Com } } + const configuredPaymentMethods = paymentMethods(candidate.paymentMethods); return { enablePromotionCodes: candidate.enablePromotionCodes as boolean, enableTaxCollection: candidate.enableTaxCollection as boolean, enableShipping: candidate.enableShipping as boolean, ...(shipping ? { shipping: shipping as CommerceCheckoutShippingConfiguration } : {}), + ...(configuredPaymentMethods ? { paymentMethods: configuredPaymentMethods } : {}), }; } diff --git a/packages/commerce-server/src/lib/commerce/checkout-subgraph.ts b/packages/commerce-server/src/lib/commerce/checkout-subgraph.ts index addcf2e3d..15d66fc0f 100644 --- a/packages/commerce-server/src/lib/commerce/checkout-subgraph.ts +++ b/packages/commerce-server/src/lib/commerce/checkout-subgraph.ts @@ -105,8 +105,8 @@ export interface CheckoutCustomerInput { } export interface CheckoutSessionPaymentMethodConfigInput { - processor?: string; - checkoutTypes?: string[]; + processor: string; + checkoutTypes: string[]; } export interface CheckoutSessionPaymentMethodsInput { diff --git a/packages/commerce-server/src/lib/commerce/create-checkout-session.ts b/packages/commerce-server/src/lib/commerce/create-checkout-session.ts index 8bba55e01..f2ca7c90b 100644 --- a/packages/commerce-server/src/lib/commerce/create-checkout-session.ts +++ b/packages/commerce-server/src/lib/commerce/create-checkout-session.ts @@ -194,6 +194,7 @@ export async function createCheckoutSession( currencyCode: configCurrencyCode, } = readReadyCommerceConfig(configuration); const checkoutConfiguration = readReadyCheckoutConfig(configuration); + const paymentMethods = checkoutConfiguration.paymentMethods ?? DEFAULT_CHECKOUT_PAYMENT_METHODS; const enablePromotionCodes: boolean = promotionCodesEnabled(checkoutConfiguration); const catalogShippingEnabled: boolean = lineItemData === undefined && checkoutConfiguration.enableShipping; const checkoutOAuthScope: string = 'commerce.product:read'; @@ -211,7 +212,7 @@ export async function createCheckoutSession( enableTaxCollection: checkoutConfiguration.enableTaxCollection, enableShipping: checkoutConfiguration.enableShipping, enableShippingAddressCollection: checkoutConfiguration.enableShipping, - paymentMethods: DEFAULT_CHECKOUT_PAYMENT_METHODS, + paymentMethods, shipping: catalogShippingEnabled ? checkoutConfiguration.shipping : undefined, }; @@ -250,7 +251,7 @@ export async function createCheckoutSession( { ...attribution, enableTaxCollection: checkoutConfiguration.enableTaxCollection, - paymentMethods: DEFAULT_CHECKOUT_PAYMENT_METHODS, + paymentMethods, }, ) : buildBuyNowCheckoutInput( From 802dde3fc305724e1cef665a4eb1bf9b1bca2b3f Mon Sep 17 00:00:00 2001 From: Sridharan Gopalan Date: Fri, 20 Nov 2026 12:54:25 -0800 Subject: [PATCH 2/3] fix(commerce-server): align checkout payment validation (COMMEX-2267) --- packages/commerce-server/README.md | 4 +- .../docs/checkout-configuration.md | 2 +- packages/commerce-server/src/config.test.ts | 20 +++++ .../src/create-checkout-session.test.ts | 85 ++++++++++++++++++- .../src/lib/commerce/checkout-config.ts | 20 +++-- .../lib/commerce/create-checkout-session.ts | 9 +- 6 files changed, 129 insertions(+), 11 deletions(-) diff --git a/packages/commerce-server/README.md b/packages/commerce-server/README.md index 30c060e53..9b054eaef 100644 --- a/packages/commerce-server/README.md +++ b/packages/commerce-server/README.md @@ -42,7 +42,9 @@ Set `paymentMethods` inside the server-only checkout JSON. Keep the existing val The server forwards payment methods for cart, Buy Now, and trusted non-catalog checkout. Checkout API requires `processor` and `checkoutTypes` for each configured payment method; an empty `googlePay` object is invalid. The merchant's processor and the shopper's browser still determine availability. This configuration does not enable Apple Pay. -Without `paymentMethods`, checkout keeps standard GoDaddy card payments. Invalid optional payment methods use that same fallback without clearing valid shipping, tax, or promotion flags. Payment methods accept the Checkout API method names and nullable method values. Each non-null method requires a nonempty `processor` and a nonempty array of `checkoutTypes`. Unknown names or method fields are invalid. Hosts supplying `CommerceConfiguration.readCheckout()` directly must validate their own values. Browser request bodies cannot select payment methods. +Without `paymentMethods`, checkout keeps standard GoDaddy card payments. Empty, all-null, or invalid payment maps use that same fallback without clearing valid shipping, tax, or promotion flags. The same payment validation applies to environment configuration and custom `CommerceConfiguration.readCheckout()` implementations. Payment methods accept the Checkout API method names and nullable method values, with at least one non-null method. Each non-null method requires a nonempty `processor` and a nonempty array of `checkoutTypes`; padded strings, unknown names, and unknown method fields are invalid. Cardless configurations are accepted; the returned session must retain at least one configured method with its requested processor. Browser request bodies cannot select payment methods. + +Forwarding a method does not initialize its frontend SDK. This Google Pay integration uses GoDaddy Payments. Other providers, including Stripe, Square, and Mercado Pago, also require their provider-specific SDK configuration in hosted checkout. Existing apps must install a release containing this change, update their lockfile, rebuild, and redeploy. A configuration update alone does not upgrade an installed package. A rebuild with an unchanged lockfile can keep the old code. The Airo integration also needs an updated configuration bridge that retains `paymentMethods`. diff --git a/packages/commerce-server/docs/checkout-configuration.md b/packages/commerce-server/docs/checkout-configuration.md index dcf7b81da..aaddf5200 100644 --- a/packages/commerce-server/docs/checkout-configuration.md +++ b/packages/commerce-server/docs/checkout-configuration.md @@ -49,7 +49,7 @@ For example: Restoring the server reader alone does not discover merchant settings: the builder/deployment integration must populate this value. Shipping-origin address details do not need to be copied into application code; hosted checkout can use store configuration. -The package forwards configured payment methods for all three session paths. Missing or malformed optional payment settings fall back to standard GoDaddy card checkout and do not reset valid feature flags. Upgrade and rebuild existing consumers before relying on this field. Apple Pay and its domain-registration prerequisites are separate work. +The package forwards configured payment methods for all three session paths. Missing, empty, all-null, or malformed optional payment settings fall back to standard GoDaddy card checkout and do not reset valid feature flags. Environment and custom host payment settings use the same validation. A valid configuration may omit card, provided the returned session retains at least one configured method with the requested processor. Forwarding a provider does not supply its frontend SDK configuration; this integration enables Google Pay through GoDaddy Payments. Upgrade and rebuild existing consumers before relying on this field. Apple Pay and its domain-registration prerequisites are separate work. The accepted stopgap is eventually consistent: a provider enabled or disabled after deployment is reflected on the next rebuild, not immediately. This is acceptable only while the Checkout API change is pending. diff --git a/packages/commerce-server/src/config.test.ts b/packages/commerce-server/src/config.test.ts index b1e9956f0..bd6c3945b 100644 --- a/packages/commerce-server/src/config.test.ts +++ b/packages/commerce-server/src/config.test.ts @@ -129,10 +129,26 @@ describe('Commerce runtime configuration', () => { expect(configuration.readCheckout()).toEqual({ ...checkout, paymentMethods }); }); + it.each([ + { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + { card: null, googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + ])('retains a valid cardless payment configuration: %j', (paymentMethods): void => { + const checkout = { enablePromotionCodes: false, enableTaxCollection: true, enableShipping: false }; + const configuration = createRuntimeCommerceConfiguration({ + environment: { + ...environment(), + GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ ...checkout, paymentMethods }), + }, + }); + expect(configuration.readCheckout()).toEqual({ ...checkout, paymentMethods }); + }); + it.each([ null, [], {}, + { card: null }, + { card: null, googlePay: null }, { unsupported: {} }, { googlePay: {} }, { googlePay: { processor: 'godaddy' } }, @@ -143,6 +159,10 @@ describe('Commerce runtime configuration', () => { { googlePay: { checkoutTypes: [] } }, { googlePay: { checkoutTypes: [null] } }, { googlePay: { secret: 'not-allowed' } }, + { googlePay: { processor: ' godaddy ', checkoutTypes: ['standard'] } }, + { googlePay: { processor: 'godaddy', checkoutTypes: [' standard '] } }, + { googlePay: { processor: ' ', checkoutTypes: ['standard'] } }, + { googlePay: { processor: 'godaddy', checkoutTypes: [' '] } }, ])( 'falls back from invalid optional payment methods without clearing valid flags: %j', (paymentMethods): void => { diff --git a/packages/commerce-server/src/create-checkout-session.test.ts b/packages/commerce-server/src/create-checkout-session.test.ts index 56cbb6460..03b0a256b 100644 --- a/packages/commerce-server/src/create-checkout-session.test.ts +++ b/packages/commerce-server/src/create-checkout-session.test.ts @@ -1,6 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { CommerceCheckoutConfiguration } from './lib/commerce/checkout-config'; -import type { CheckoutSessionResult, CreateCheckoutSessionResult } from './lib/commerce/checkout-subgraph'; +import type { + CheckoutSessionPaymentMethodConfigInput, + CheckoutSessionResult, + CreateCheckoutSessionResult, +} from './lib/commerce/checkout-subgraph'; import type { CommerceConfig, CommerceConfiguration } from './lib/commerce/config'; import { type CreateCheckoutSessionParams, @@ -124,6 +128,85 @@ describe('createCheckoutSession', () => { }, ); + describe.each(flows)('%s payment configuration', (_name, params) => { + it.each>([ + { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + { card: null, googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + ])('accepts an upstream session with only a configured wallet: %j', async (paymentMethods) => { + checkout = { ...checkout, paymentMethods }; + mockGqlRequest.mockResolvedValue(response({ paymentMethods })); + + await expect(createCheckoutSession(params, configuration)).resolves.toHaveProperty('id', 'session-1'); + expect(mockGqlRequest.mock.calls[0]?.[0].variables.input.paymentMethods).toEqual(paymentMethods); + }); + + it.each([ + null, + [], + 'invalid', + {}, + { card: null }, + { card: null, googlePay: null }, + { googlePay: {} }, + { googlePay: { processor: 'godaddy' } }, + { googlepay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + { googlePay: { processor: ' godaddy ', checkoutTypes: ['standard'] } }, + { googlePay: { processor: 'godaddy', checkoutTypes: [' standard '] } }, + { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'], secret: 'not-allowed' } }, + ])( + 'falls back from invalid host payment methods while retaining tax collection: %j', + async (paymentMethods) => { + checkout = { + ...checkout, + enableTaxCollection: true, + paymentMethods: paymentMethods as CommerceCheckoutConfiguration['paymentMethods'], + }; + mockGqlRequest.mockResolvedValue(response({ enableTaxCollection: true })); + + await createCheckoutSession(params, configuration); + expect(mockGqlRequest.mock.calls[0]?.[0].variables.input).toMatchObject({ + enableTaxCollection: true, + paymentMethods: { card: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + }); + }, + ); + + it.each([ + null, + {}, + { googlePay: null }, + { googlePay: { processor: '' } }, + { googlePay: { processor: ' ' } }, + { googlePay: { processor: 'other' } }, + { card: { processor: 'godaddy' } }, + ])('rejects a session without any configured processor: %j', async (paymentMethods) => { + checkout = { + ...checkout, + paymentMethods: { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + }; + mockGqlRequest.mockResolvedValue(response({ paymentMethods })); + + await expect(createCheckoutSession(params, configuration)).rejects.toThrow( + 'Checkout session did not configure payment methods.', + ); + }); + + it('accepts a session when one of several configured methods survives API filtering', async () => { + checkout = { + ...checkout, + paymentMethods: { + card: { processor: 'godaddy', checkoutTypes: ['standard'] }, + googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] }, + }, + }; + mockGqlRequest.mockResolvedValue( + response({ paymentMethods: { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] } } }), + ); + + await expect(createCheckoutSession(params, configuration)).resolves.toHaveProperty('id', 'session-1'); + }); + }); + it('does not let checkout callers override server-owned payment methods', async (): Promise => { await createCheckoutSession( { diff --git a/packages/commerce-server/src/lib/commerce/checkout-config.ts b/packages/commerce-server/src/lib/commerce/checkout-config.ts index e38d2ae67..2ffa324d5 100644 --- a/packages/commerce-server/src/lib/commerce/checkout-config.ts +++ b/packages/commerce-server/src/lib/commerce/checkout-config.ts @@ -31,9 +31,10 @@ function isRecord(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); } -/** Invalid optional payment settings fall back independently of the existing checkout flags. */ -function paymentMethods(value: unknown): CheckoutSessionPaymentMethodsInput | undefined { +/** Shared validation for environment and host settings; at least one method must be enabled. */ +export function parseCheckoutPaymentMethods(value: unknown): CheckoutSessionPaymentMethodsInput | undefined { if (!isRecord(value) || Object.keys(value).length === 0) return undefined; + let hasEnabledMethod = false; for (const [name, method] of Object.entries(value)) { if (!PAYMENT_METHOD_NAMES.has(name as keyof CheckoutSessionPaymentMethodsInput)) return undefined; if (method === null) continue; @@ -43,17 +44,24 @@ function paymentMethods(value: unknown): CheckoutSessionPaymentMethodsInput | un ) { return undefined; } - if (typeof method.processor !== 'string' || !method.processor.trim()) { + if ( + typeof method.processor !== 'string' || + !method.processor || + method.processor !== method.processor.trim() + ) { return undefined; } if ( !Array.isArray(method.checkoutTypes) || method.checkoutTypes.length === 0 || - !method.checkoutTypes.every((type: unknown) => typeof type === 'string' && type.trim() !== '') + !method.checkoutTypes.every( + (type: unknown) => typeof type === 'string' && type !== '' && type === type.trim(), + ) ) return undefined; + hasEnabledMethod = true; } - return value as CheckoutSessionPaymentMethodsInput; + return hasEnabledMethod ? (value as CheckoutSessionPaymentMethodsInput) : undefined; } const DEFAULT_CHECKOUT_CONFIGURATION: CommerceCheckoutConfiguration = { @@ -98,7 +106,7 @@ export function parseCommerceCheckoutConfiguration(raw: string | undefined): Com } } - const configuredPaymentMethods = paymentMethods(candidate.paymentMethods); + const configuredPaymentMethods = parseCheckoutPaymentMethods(candidate.paymentMethods); return { enablePromotionCodes: candidate.enablePromotionCodes as boolean, enableTaxCollection: candidate.enableTaxCollection as boolean, diff --git a/packages/commerce-server/src/lib/commerce/create-checkout-session.ts b/packages/commerce-server/src/lib/commerce/create-checkout-session.ts index f2ca7c90b..09b2408cd 100644 --- a/packages/commerce-server/src/lib/commerce/create-checkout-session.ts +++ b/packages/commerce-server/src/lib/commerce/create-checkout-session.ts @@ -13,6 +13,7 @@ * Server-only. Credentials and integration settings come from the host configuration. */ +import { parseCheckoutPaymentMethods } from './checkout-config'; import { authorizationHeaders, buildBuyNowCheckoutInput, @@ -194,7 +195,8 @@ export async function createCheckoutSession( currencyCode: configCurrencyCode, } = readReadyCommerceConfig(configuration); const checkoutConfiguration = readReadyCheckoutConfig(configuration); - const paymentMethods = checkoutConfiguration.paymentMethods ?? DEFAULT_CHECKOUT_PAYMENT_METHODS; + const paymentMethods = + parseCheckoutPaymentMethods(checkoutConfiguration.paymentMethods) ?? DEFAULT_CHECKOUT_PAYMENT_METHODS; const enablePromotionCodes: boolean = promotionCodesEnabled(checkoutConfiguration); const catalogShippingEnabled: boolean = lineItemData === undefined && checkoutConfiguration.enableShipping; const checkoutOAuthScope: string = 'commerce.product:read'; @@ -309,7 +311,10 @@ export async function createCheckoutSession( throw new UpstreamError('Checkout session did not enable configured shipping and address collection'); } - if (!session.paymentMethods?.card?.processor) { + const hasConfiguredPaymentMethod = Object.entries(paymentMethods).some( + ([name, method]) => method != null && session.paymentMethods?.[name]?.processor === method.processor, + ); + if (!hasConfiguredPaymentMethod) { throw new UpstreamError('Checkout session did not configure payment methods.'); } From c62760538c56f115b51548a1eeb45fc47b1559a3 Mon Sep 17 00:00:00 2001 From: Sridharan Gopalan Date: Fri, 20 Nov 2026 14:08:32 -0800 Subject: [PATCH 3/3] fix(commerce-server): warn on invalid payment configuration (COMMEX-2267) --- .changeset/commex-2267-google-pay.md | 2 + packages/commerce-server/README.md | 9 +- .../src/checkout-route.test.ts | 12 +- packages/commerce-server/src/config.test.ts | 54 ++++++++- .../src/configuration-integration.test.ts | 106 +++++++++++++++++- .../src/create-checkout-session.test.ts | 16 ++- packages/commerce-server/src/index.ts | 1 + .../src/lib/commerce/checkout-config.ts | 48 ++++++-- .../src/lib/commerce/commerce-route.ts | 19 +++- .../src/lib/commerce/config.ts | 18 ++- .../lib/commerce/create-checkout-session.ts | 7 +- packages/commerce-server/src/router.ts | 2 +- .../src/server/api/commerce/checkout/POST.ts | 3 +- 13 files changed, 263 insertions(+), 34 deletions(-) diff --git a/.changeset/commex-2267-google-pay.md b/.changeset/commex-2267-google-pay.md index 1394727d7..1641bdd2d 100644 --- a/.changeset/commex-2267-google-pay.md +++ b/.changeset/commex-2267-google-pay.md @@ -3,3 +3,5 @@ --- Forward server-configured checkout payment methods, including standard Google Pay, for cart, Buy Now, and non-catalog checkout. Keep the standard GoDaddy card default when optional payment settings are absent or malformed, without resetting valid checkout flags. + +Warn through the configured logger when invalid payment methods fall back to standard GoDaddy card payments, without logging configuration values. diff --git a/packages/commerce-server/README.md b/packages/commerce-server/README.md index 9b054eaef..32488d6cb 100644 --- a/packages/commerce-server/README.md +++ b/packages/commerce-server/README.md @@ -44,6 +44,8 @@ The server forwards payment methods for cart, Buy Now, and trusted non-catalog c Without `paymentMethods`, checkout keeps standard GoDaddy card payments. Empty, all-null, or invalid payment maps use that same fallback without clearing valid shipping, tax, or promotion flags. The same payment validation applies to environment configuration and custom `CommerceConfiguration.readCheckout()` implementations. Payment methods accept the Checkout API method names and nullable method values, with at least one non-null method. Each non-null method requires a nonempty `processor` and a nonempty array of `checkoutTypes`; padded strings, unknown names, and unknown method fields are invalid. Cardless configurations are accepted; the returned session must retain at least one configured method with its requested processor. Browser request bodies cannot select payment methods. +An invalid payment map emits a warning with code `invalid_checkout_payment_methods` and fallback `standard_godaddy_card`. The warning contains no configuration values. Missing or valid payment settings do not warn. Router requests use the configured logger's optional `warn` method; error-only or failing warning loggers fall back to `console.warn`. Each checkout attempt that reads an invalid map warns once. + Forwarding a method does not initialize its frontend SDK. This Google Pay integration uses GoDaddy Payments. Other providers, including Stripe, Square, and Mercado Pago, also require their provider-specific SDK configuration in hosted checkout. Existing apps must install a release containing this change, update their lockfile, rebuild, and redeploy. A configuration update alone does not upgrade an installed package. A rebuild with an unchanged lockfile can keep the old code. The Airo integration also needs an updated configuration bridge that retains `paymentMethods`. @@ -164,10 +166,15 @@ Upstream errors without a specific mapping stay 502; business errors such as inv ```ts createCommerceRouter({ configuration, - logger: { error: (message, context) => log.error(context, message) }, + logger: { + error: (message, context) => log.error(context, message), + warn: (message, context) => log.warn(context, message), + }, // Use the host's request id when its edge sets one; unsafe or missing ids fall back to a UUID. getRequestId: (req) => req.get('x-request-id'), }); ``` `createCommerceCatalogRouter` and `createGoDaddyPaymentsRouter` accept the same `{ logger, getRequestId }` as their last argument. The logger defaults to `console.error`. In-process helpers throw the exported `CommerceError` subclasses (`InvalidRequestError`, `NotFoundError`, `CommerceNotConfiguredError`, `UpstreamError`), including when a host configuration throws while being read. Check `error.code` (for example `'not_found'`) rather than `instanceof`, which fails when a host has more than one copy of this package. + +In-process checkout callers can pass their logger as `createCheckoutSession(params, configuration, logger)`. Direct configuration readers can use `configuration.readCheckout(logger)` or `parseCommerceCheckoutConfiguration(raw, logger)` to receive the same payment warnings. These arguments are optional and default to console warnings. diff --git a/packages/commerce-server/src/checkout-route.test.ts b/packages/commerce-server/src/checkout-route.test.ts index 5da3dcc3f..9a76ac96f 100644 --- a/packages/commerce-server/src/checkout-route.test.ts +++ b/packages/commerce-server/src/checkout-route.test.ts @@ -70,7 +70,11 @@ describe('public checkout boundary', () => { async (route): Promise => { const response = await post(valid, route); expect(response.status).toBe(200); - expect(createCheckoutSession).toHaveBeenCalledWith(expect.objectContaining(valid), expect.anything()); + expect(createCheckoutSession).toHaveBeenCalledWith( + expect.objectContaining(valid), + expect.anything(), + expect.objectContaining({ error: expect.any(Function) }), + ); }, ); @@ -82,7 +86,11 @@ describe('public checkout boundary', () => { successUrl: 'https://shop.example.com/receipt?orderId=cart-1&campaign=spring', }; expect((await post(body)).status).toBe(200); - expect(createCheckoutSession).toHaveBeenCalledWith(expect.objectContaining(body), expect.anything()); + expect(createCheckoutSession).toHaveBeenCalledWith( + expect.objectContaining(body), + expect.anything(), + expect.objectContaining({ error: expect.any(Function) }), + ); }); it.each([false, true])( diff --git a/packages/commerce-server/src/config.test.ts b/packages/commerce-server/src/config.test.ts index bd6c3945b..1ad3a0917 100644 --- a/packages/commerce-server/src/config.test.ts +++ b/packages/commerce-server/src/config.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; +import { parseCommerceCheckoutConfiguration } from './lib/commerce/checkout-config'; import { createRuntimeCommerceConfiguration, readCommerceConfig } from './lib/commerce/config'; function environment(): NodeJS.ProcessEnv { @@ -13,9 +14,42 @@ function environment(): NodeJS.ProcessEnv { afterEach((): void => { vi.unstubAllEnvs(); + vi.restoreAllMocks(); }); describe('Commerce runtime configuration', () => { + it.each(['missing', 'throwing'] as const)( + 'keeps the safe fallback and emits a console warning when the host warn method is %s', + (mode): void => { + const consoleWarning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const logger = { + error: vi.fn(), + ...(mode === 'throwing' + ? { + warn: vi.fn(() => { + throw new Error('private-logger-error'); + }), + } + : {}), + }; + const checkout = { enablePromotionCodes: true, enableTaxCollection: false, enableShipping: false }; + expect( + parseCommerceCheckoutConfiguration( + JSON.stringify({ + ...checkout, + paymentMethods: { googlePay: { secret: 'private-payment-config' } }, + }), + logger, + ), + ).toEqual(checkout); + expect(consoleWarning).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('falling back'), { + code: 'invalid_checkout_payment_methods', + fallback: 'standard_godaddy_card', + }); + expect(logger.error).not.toHaveBeenCalled(); + }, + ); + it('defaults to production and does not select an API origin from environment variables', (): void => { const config = readCommerceConfig({ environment: { ...environment(), GODADDY_API_BASE_URL: 'https://api.example.com' }, @@ -76,9 +110,10 @@ describe('Commerce runtime configuration', () => { }); it('reads checkout flags and API shipping options', (): void => { + const logger = { error: vi.fn(), warn: vi.fn() }; const values = environment(); const configuration = createRuntimeCommerceConfiguration({ environment: values }); - expect(configuration.readCheckout()).toEqual({ + expect(configuration.readCheckout(logger)).toEqual({ enablePromotionCodes: false, enableTaxCollection: false, enableShipping: false, @@ -89,12 +124,13 @@ describe('Commerce runtime configuration', () => { enableShipping: true, shipping: { fulfillmentLocationId: 'location-1' }, }); - expect(configuration.readCheckout()).toEqual({ + expect(configuration.readCheckout(logger)).toEqual({ enablePromotionCodes: true, enableTaxCollection: false, enableShipping: true, shipping: { fulfillmentLocationId: 'location-1' }, }); + expect(logger.warn).not.toHaveBeenCalled(); }); it.each([ @@ -115,6 +151,7 @@ describe('Commerce runtime configuration', () => { }); it('retains standard Google Pay settings alongside existing checkout capabilities', (): void => { + const logger = { error: vi.fn(), warn: vi.fn() }; const paymentMethods = { card: { processor: 'godaddy', checkoutTypes: ['standard'] }, googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] }, @@ -126,7 +163,8 @@ describe('Commerce runtime configuration', () => { GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ ...checkout, paymentMethods }), }, }); - expect(configuration.readCheckout()).toEqual({ ...checkout, paymentMethods }); + expect(configuration.readCheckout(logger)).toEqual({ ...checkout, paymentMethods }); + expect(logger.warn).not.toHaveBeenCalled(); }); it.each([ @@ -150,6 +188,8 @@ describe('Commerce runtime configuration', () => { { card: null }, { card: null, googlePay: null }, { unsupported: {} }, + { googlepay: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'], secret: 'not-allowed' } }, { googlePay: {} }, { googlePay: { processor: 'godaddy' } }, { googlePay: { checkoutTypes: ['standard'] } }, @@ -166,6 +206,7 @@ describe('Commerce runtime configuration', () => { ])( 'falls back from invalid optional payment methods without clearing valid flags: %j', (paymentMethods): void => { + const logger = { error: vi.fn(), warn: vi.fn() }; const checkout = { enablePromotionCodes: true, enableTaxCollection: true, enableShipping: false }; const configuration = createRuntimeCommerceConfiguration({ environment: { @@ -173,7 +214,12 @@ describe('Commerce runtime configuration', () => { GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ ...checkout, paymentMethods }), }, }); - expect(configuration.readCheckout()).toEqual(checkout); + expect(configuration.readCheckout(logger)).toEqual(checkout); + expect(logger.warn).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('falling back'), { + code: 'invalid_checkout_payment_methods', + fallback: 'standard_godaddy_card', + }); + expect(logger.error).not.toHaveBeenCalled(); }, ); }); diff --git a/packages/commerce-server/src/configuration-integration.test.ts b/packages/commerce-server/src/configuration-integration.test.ts index fc7c2318b..21b0accf5 100644 --- a/packages/commerce-server/src/configuration-integration.test.ts +++ b/packages/commerce-server/src/configuration-integration.test.ts @@ -1,7 +1,8 @@ import { once } from 'node:events'; import express from 'express'; import { afterEach, expect, it, vi } from 'vitest'; -import { createRuntimeCommerceConfiguration } from './lib/commerce/config'; +import type { CommerceCheckoutConfiguration } from './lib/commerce/checkout-config'; +import { type CommerceConfiguration, createRuntimeCommerceConfiguration } from './lib/commerce/config'; import { createCommerceRouter } from './router'; const clientFetch = globalThis.fetch; @@ -10,6 +11,109 @@ afterEach((): void => { vi.restoreAllMocks(); }); +it.each(['environment', 'host'] as const)( + 'warns once through the router logger when %s payment settings fall back, then recovers', + async (source): Promise => { + const logger = { error: vi.fn(), warn: vi.fn() }; + const consoleWarning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const card = { processor: 'godaddy', checkoutTypes: ['standard'] }; + let settings: CommerceCheckoutConfiguration = { + enablePromotionCodes: false, + enableTaxCollection: true, + enableShipping: false, + paymentMethods: { + card, + googlepay: { ...card, secret: 'private-payment-config' }, + } as CommerceCheckoutConfiguration['paymentMethods'], + }; + const environment = { + GODADDY_OAUTH_CLIENT_ID: 'client-1', + GODADDY_OAUTH_CLIENT_SECRET: 'private-oauth-secret', + GODADDY_STORE_ID: 'store-1', + GODADDY_CHANNEL_ID: 'channel-1', + GODADDY_CURRENCY_CODE: 'USD', + GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify(settings), + }; + const runtime = createRuntimeCommerceConfiguration({ environment }); + const configuration: CommerceConfiguration = + source === 'environment' ? runtime : { read: () => runtime.read(), readCheckout: () => settings }; + let expectedPaymentMethods: CommerceCheckoutConfiguration['paymentMethods'] = { card }; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit): Promise => { + if (String(input).endsWith('/v2/oauth2/token')) { + return Response.json({ access_token: 'token', expires_in: 3600 }); + } + const body = JSON.parse(String(init?.body)); + expect(body.variables.input.paymentMethods).toEqual(expectedPaymentMethods); + expect(body.variables.input.enableTaxCollection).toBe(true); + return Response.json({ + data: { + createCheckoutSession: { + id: 'session-1', + url: 'https://checkout.example.com/session-1', + storeId: 'store-1', + channelId: 'channel-1', + enableTaxCollection: true, + paymentMethods: body.variables.input.paymentMethods, + }, + }, + }); + }), + ); + const app = express(); + app.use(express.json()); + app.use( + '/api/commerce', + createCommerceRouter({ + configuration, + logger, + checkoutReturnUrls: { + returnUrls: ['https://example.com/cart'], + successUrls: ['https://example.com/success'], + }, + }), + ); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Expected a listening TCP server'); + const requestCheckout = (): Promise => + clientFetch(`http://127.0.0.1:${address.port}/api/commerce/checkout`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + draftOrderId: 'cart-1', + returnUrl: 'https://example.com/cart', + successUrl: 'https://example.com/success', + }), + }); + const fallback = await requestCheckout(); + expect(fallback.status).toBe(200); + const fallbackBody = await fallback.json(); + expect(fallbackBody).toHaveProperty('id', 'session-1'); + expectedPaymentMethods = { card, googlePay: card }; + settings = { ...settings, paymentMethods: expectedPaymentMethods }; + environment.GODADDY_CHECKOUT_CONFIGURATION = JSON.stringify(settings); + expect((await requestCheckout()).status).toBe(200); + expect(logger.warn).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('falling back'), { + code: 'invalid_checkout_payment_methods', + fallback: 'standard_godaddy_card', + }); + const diagnostics = JSON.stringify({ warnings: logger.warn.mock.calls, response: fallbackBody }); + expect(diagnostics).not.toContain('private-payment-config'); + expect(diagnostics).not.toContain('private-oauth-secret'); + expect(logger.error).not.toHaveBeenCalled(); + expect(consoleWarning).not.toHaveBeenCalled(); + } finally { + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + } + }, +); + it('serves variant product details only on the configured channel without querying SKUGroup.status', async (): Promise => { const upstream = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit): Promise => { const { query, variables } = JSON.parse(String(init?.body)) as { diff --git a/packages/commerce-server/src/create-checkout-session.test.ts b/packages/commerce-server/src/create-checkout-session.test.ts index 03b0a256b..5d533b1f8 100644 --- a/packages/commerce-server/src/create-checkout-session.test.ts +++ b/packages/commerce-server/src/create-checkout-session.test.ts @@ -95,13 +95,15 @@ describe('createCheckoutSession', () => { it.each(flows)( 'uses default payments without built-in attribution for %s checkout', async (_name, params): Promise => { - await createCheckoutSession(params, configuration); + const logger = { error: vi.fn(), warn: vi.fn() }; + await createCheckoutSession(params, configuration, logger); const input = mockGqlRequest.mock.calls[0]?.[0].variables.input; expect(input).toMatchObject({ paymentMethods: { card: { processor: 'godaddy', checkoutTypes: ['standard'] } }, }); expect(input).not.toHaveProperty('sourceApp'); expect(input).not.toHaveProperty('owner'); + expect(logger.warn).not.toHaveBeenCalled(); }, ); @@ -118,13 +120,15 @@ describe('createCheckoutSession', () => { it.each(flows)( 'forwards server-configured Google Pay for %s checkout', async (_name, params): Promise => { + const logger = { error: vi.fn(), warn: vi.fn() }; const paymentMethods = { card: { processor: 'godaddy', checkoutTypes: ['standard'] }, googlePay: { processor: 'godaddy', checkoutTypes: ['standard'] }, }; checkout = { ...checkout, paymentMethods }; - await createCheckoutSession(params, configuration); + await createCheckoutSession(params, configuration, logger); expect(mockGqlRequest.mock.calls[0]?.[0].variables.input.paymentMethods).toEqual(paymentMethods); + expect(logger.warn).not.toHaveBeenCalled(); }, ); @@ -156,6 +160,7 @@ describe('createCheckoutSession', () => { ])( 'falls back from invalid host payment methods while retaining tax collection: %j', async (paymentMethods) => { + const logger = { error: vi.fn(), warn: vi.fn() }; checkout = { ...checkout, enableTaxCollection: true, @@ -163,11 +168,16 @@ describe('createCheckoutSession', () => { }; mockGqlRequest.mockResolvedValue(response({ enableTaxCollection: true })); - await createCheckoutSession(params, configuration); + await createCheckoutSession(params, configuration, logger); expect(mockGqlRequest.mock.calls[0]?.[0].variables.input).toMatchObject({ enableTaxCollection: true, paymentMethods: { card: { processor: 'godaddy', checkoutTypes: ['standard'] } }, }); + expect(logger.warn).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('falling back'), { + code: 'invalid_checkout_payment_methods', + fallback: 'standard_godaddy_card', + }); + expect(logger.error).not.toHaveBeenCalled(); }, ); diff --git a/packages/commerce-server/src/index.ts b/packages/commerce-server/src/index.ts index 4b76349b8..dd22fefab 100644 --- a/packages/commerce-server/src/index.ts +++ b/packages/commerce-server/src/index.ts @@ -12,6 +12,7 @@ export type { CommerceErrorLogContext, CommerceLogger, CommerceRequestIdResolver, + CommerceWarningLogContext, } from './lib/commerce/commerce-route'; export { type CommerceConfig, diff --git a/packages/commerce-server/src/lib/commerce/checkout-config.ts b/packages/commerce-server/src/lib/commerce/checkout-config.ts index 2ffa324d5..ce1d9c7a7 100644 --- a/packages/commerce-server/src/lib/commerce/checkout-config.ts +++ b/packages/commerce-server/src/lib/commerce/checkout-config.ts @@ -1,4 +1,5 @@ import type { CheckoutSessionPaymentMethodsInput } from './checkout-subgraph'; +import { type CommerceLogger, type CommerceWarningLogContext, consoleCommerceLogger } from './commerce-route'; /** Shipping options accepted by the hosted checkout API. Omit to use the store's configuration. */ export interface CommerceCheckoutShippingConfiguration { @@ -31,25 +32,51 @@ function isRecord(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); } +function invalidPaymentMethods(logger: CommerceLogger): undefined { + const message = + 'commerce-server: Invalid paymentMethods configuration; falling back to standard GoDaddy card payments. Check method names, processor, checkoutTypes, and unsupported fields.'; + const context: CommerceWarningLogContext = { + code: 'invalid_checkout_payment_methods', + fallback: 'standard_godaddy_card', + }; + try { + if (logger.warn) { + logger.warn(message, context); + return undefined; + } + } catch { + // A host logger failure must not prevent checkout or expose its error/configuration values. + consoleCommerceLogger.warn?.(message, context); + return undefined; + } + consoleCommerceLogger.warn?.(message, context); + return undefined; +} + /** Shared validation for environment and host settings; at least one method must be enabled. */ -export function parseCheckoutPaymentMethods(value: unknown): CheckoutSessionPaymentMethodsInput | undefined { - if (!isRecord(value) || Object.keys(value).length === 0) return undefined; +export function parseCheckoutPaymentMethods( + value: unknown, + logger: CommerceLogger = consoleCommerceLogger, +): CheckoutSessionPaymentMethodsInput | undefined { + if (value === undefined) return undefined; + if (!isRecord(value) || Object.keys(value).length === 0) return invalidPaymentMethods(logger); let hasEnabledMethod = false; for (const [name, method] of Object.entries(value)) { - if (!PAYMENT_METHOD_NAMES.has(name as keyof CheckoutSessionPaymentMethodsInput)) return undefined; + if (!PAYMENT_METHOD_NAMES.has(name as keyof CheckoutSessionPaymentMethodsInput)) + return invalidPaymentMethods(logger); if (method === null) continue; if ( !isRecord(method) || Object.keys(method).some((key) => key !== 'processor' && key !== 'checkoutTypes') ) { - return undefined; + return invalidPaymentMethods(logger); } if ( typeof method.processor !== 'string' || !method.processor || method.processor !== method.processor.trim() ) { - return undefined; + return invalidPaymentMethods(logger); } if ( !Array.isArray(method.checkoutTypes) || @@ -58,10 +85,10 @@ export function parseCheckoutPaymentMethods(value: unknown): CheckoutSessionPaym (type: unknown) => typeof type === 'string' && type !== '' && type === type.trim(), ) ) - return undefined; + return invalidPaymentMethods(logger); hasEnabledMethod = true; } - return hasEnabledMethod ? (value as CheckoutSessionPaymentMethodsInput) : undefined; + return hasEnabledMethod ? (value as CheckoutSessionPaymentMethodsInput) : invalidPaymentMethods(logger); } const DEFAULT_CHECKOUT_CONFIGURATION: CommerceCheckoutConfiguration = { @@ -70,7 +97,10 @@ const DEFAULT_CHECKOUT_CONFIGURATION: CommerceCheckoutConfiguration = { enableShipping: false, }; -export function parseCommerceCheckoutConfiguration(raw: string | undefined): CommerceCheckoutConfiguration { +export function parseCommerceCheckoutConfiguration( + raw: string | undefined, + logger?: CommerceLogger, +): CommerceCheckoutConfiguration { if (!raw?.trim()) return DEFAULT_CHECKOUT_CONFIGURATION; let value: unknown; @@ -106,7 +136,7 @@ export function parseCommerceCheckoutConfiguration(raw: string | undefined): Com } } - const configuredPaymentMethods = parseCheckoutPaymentMethods(candidate.paymentMethods); + const configuredPaymentMethods = parseCheckoutPaymentMethods(candidate.paymentMethods, logger); return { enablePromotionCodes: candidate.enablePromotionCodes as boolean, enableTaxCollection: candidate.enableTaxCollection as boolean, diff --git a/packages/commerce-server/src/lib/commerce/commerce-route.ts b/packages/commerce-server/src/lib/commerce/commerce-route.ts index d7983d54f..8248b89d7 100644 --- a/packages/commerce-server/src/lib/commerce/commerce-route.ts +++ b/packages/commerce-server/src/lib/commerce/commerce-route.ts @@ -13,13 +13,21 @@ export interface CommerceErrorLogContext { error: unknown; } -/** Receives server-side failure detail that is never sent to the browser. */ +export interface CommerceWarningLogContext { + code: 'invalid_checkout_payment_methods'; + fallback: 'standard_godaddy_card'; +} + +/** Receives server-side diagnostics that are never sent to the browser. */ export interface CommerceLogger { error(message: string, context: CommerceErrorLogContext): void; + /** Optional for compatibility with existing error-only loggers; defaults to `console.warn`. */ + warn?(message: string, context: CommerceWarningLogContext): void; } export const consoleCommerceLogger: CommerceLogger = { error: (message, context): void => console.error(message, context), + warn: (message, context): void => console.warn(message, context), }; /** Returns the host's id for this request (for example one set by its load balancer), if any. */ @@ -39,6 +47,10 @@ function observabilityLocals(res: Response): CommerceObservabilityLocals { return res.locals as CommerceObservabilityLocals; } +export function commerceLoggerForResponse(res: Response): CommerceLogger { + return observabilityLocals(res).commerceLogger ?? consoleCommerceLogger; +} + export function resolveRequestId(req: Request, resolver?: CommerceRequestIdResolver): string { let supplied: string | undefined; // A failing host resolver must not prevent the failure response. @@ -91,10 +103,7 @@ export function sendCommerceError( }; // A failing or invalid host logger must not prevent the failure response. try { - (observabilityLocals(res).commerceLogger ?? consoleCommerceLogger).error( - `commerce-server: ${label}`, - context, - ); + commerceLoggerForResponse(res).error(`commerce-server: ${label}`, context); } catch (loggerError) { console.error(`commerce-server: ${label} (host logger failed)`, { ...context, loggerError }); } diff --git a/packages/commerce-server/src/lib/commerce/config.ts b/packages/commerce-server/src/lib/commerce/config.ts index 42e49c4b2..ce5a83e81 100644 --- a/packages/commerce-server/src/lib/commerce/config.ts +++ b/packages/commerce-server/src/lib/commerce/config.ts @@ -1,6 +1,7 @@ /** Server-only Commerce configuration. Hosts own secrets and deployment-specific loading. */ import type { Response } from 'express'; import { type CommerceCheckoutConfiguration, parseCommerceCheckoutConfiguration } from './checkout-config'; +import type { CommerceLogger } from './commerce-route'; import { CommerceError, CommerceNotConfiguredError } from './errors'; const DEFAULT_API_BASE_URL = 'https://api.godaddy.com'; @@ -29,7 +30,8 @@ export interface CommerceConfiguration { /** Authoritative host state. Missing support preserves legacy live/error behavior. */ readConnectionState?(): CommerceConnectionState | undefined; read(): CommerceConfig; - readCheckout(): CommerceCheckoutConfiguration; + /** The runtime reader uses this logger for invalid optional payment settings. */ + readCheckout(logger?: CommerceLogger): CommerceCheckoutConfiguration; } export interface RuntimeCommerceConfigurationOptions { @@ -93,8 +95,11 @@ export function createRuntimeCommerceConfiguration( ): CommerceConfiguration { return { read: (): CommerceConfig => readCommerceConfig(options), - readCheckout: (): CommerceCheckoutConfiguration => - parseCommerceCheckoutConfiguration((options.environment ?? process.env).GODADDY_CHECKOUT_CONFIGURATION), + readCheckout: (logger): CommerceCheckoutConfiguration => + parseCommerceCheckoutConfiguration( + (options.environment ?? process.env).GODADDY_CHECKOUT_CONFIGURATION, + logger, + ), }; } @@ -144,9 +149,12 @@ export function readReadyCommerceConfig(configuration: CommerceConfiguration): C return fromHost(() => configuration.read()); } -export function readReadyCheckoutConfig(configuration: CommerceConfiguration): CommerceCheckoutConfiguration { +export function readReadyCheckoutConfig( + configuration: CommerceConfiguration, + logger?: CommerceLogger, +): CommerceCheckoutConfiguration { assertCommerceConnectionReady(configuration); - return fromHost(() => configuration.readCheckout()); + return fromHost(() => configuration.readCheckout(logger)); } export function commerceConfigurationForResponse(res: Response): CommerceConfiguration { diff --git a/packages/commerce-server/src/lib/commerce/create-checkout-session.ts b/packages/commerce-server/src/lib/commerce/create-checkout-session.ts index 09b2408cd..86b3be980 100644 --- a/packages/commerce-server/src/lib/commerce/create-checkout-session.ts +++ b/packages/commerce-server/src/lib/commerce/create-checkout-session.ts @@ -26,6 +26,7 @@ import { DEFAULT_CHECKOUT_PAYMENT_METHODS, getOAuthAccessToken, } from './checkout-subgraph'; +import { type CommerceLogger, consoleCommerceLogger } from './commerce-route'; import { type CommerceConfiguration, createRuntimeCommerceConfiguration, @@ -170,6 +171,7 @@ function promotionCodesEnabled(configuration: object): boolean { export async function createCheckoutSession( params: CreateCheckoutSessionParams, configuration: CommerceConfiguration = createRuntimeCommerceConfiguration(), + logger: CommerceLogger = consoleCommerceLogger, ): Promise { const { draftOrderId, skuId, quantity, lineItemData, returnUrl, successUrl } = params; @@ -194,9 +196,10 @@ export async function createCheckoutSession( owner, currencyCode: configCurrencyCode, } = readReadyCommerceConfig(configuration); - const checkoutConfiguration = readReadyCheckoutConfig(configuration); + const checkoutConfiguration = readReadyCheckoutConfig(configuration, logger); const paymentMethods = - parseCheckoutPaymentMethods(checkoutConfiguration.paymentMethods) ?? DEFAULT_CHECKOUT_PAYMENT_METHODS; + parseCheckoutPaymentMethods(checkoutConfiguration.paymentMethods, logger) ?? + DEFAULT_CHECKOUT_PAYMENT_METHODS; const enablePromotionCodes: boolean = promotionCodesEnabled(checkoutConfiguration); const catalogShippingEnabled: boolean = lineItemData === undefined && checkoutConfiguration.enableShipping; const checkoutOAuthScope: string = 'commerce.product:read'; diff --git a/packages/commerce-server/src/router.ts b/packages/commerce-server/src/router.ts index 935087686..3d6d122d4 100644 --- a/packages/commerce-server/src/router.ts +++ b/packages/commerce-server/src/router.ts @@ -30,7 +30,7 @@ export interface CommerceRouterFeatures { /** Where failure detail is logged and how each request's id is chosen. */ export interface CommerceRouterObservabilityOptions { - /** Receives 5xx failure detail. Defaults to `console.error`. */ + /** Receives 5xx failures and optional configuration warnings. Defaults to the console. */ logger?: CommerceLogger; /** * Returns the host's id for the request, for example `(req) => req.get('x-request-id')` when diff --git a/packages/commerce-server/src/server/api/commerce/checkout/POST.ts b/packages/commerce-server/src/server/api/commerce/checkout/POST.ts index ec9483eea..bd0991150 100644 --- a/packages/commerce-server/src/server/api/commerce/checkout/POST.ts +++ b/packages/commerce-server/src/server/api/commerce/checkout/POST.ts @@ -40,7 +40,7 @@ import type { Request, Response } from 'express'; import { assertCommerceCartScope } from '@/lib/commerce/cart-scope'; import type { CheckoutReturnUrlValidator } from '@/lib/commerce/checkout-return-urls'; -import { commerceRoute } from '@/lib/commerce/commerce-route'; +import { commerceLoggerForResponse, commerceRoute } from '@/lib/commerce/commerce-route'; import { type CommerceConfig, commerceConfigurationForResponse, @@ -100,6 +100,7 @@ async function createCheckout(req: Request, res: Response): Promise { ...destinations, }, configuration, + commerceLoggerForResponse(res), ); res.status(200).json(session);