diff --git a/.changeset/commex-2267-google-pay.md b/.changeset/commex-2267-google-pay.md new file mode 100644 index 000000000..1641bdd2d --- /dev/null +++ b/.changeset/commex-2267-google-pay.md @@ -0,0 +1,7 @@ +--- +'@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. + +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 0f4a860b6..32488d6cb 100644 --- a/packages/commerce-server/README.md +++ b/packages/commerce-server/README.md @@ -24,6 +24,32 @@ 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. 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`. + 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. @@ -140,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/docs/checkout-configuration.md b/packages/commerce-server/docs/checkout-configuration.md index 8e09e2680..aaddf5200 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, 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. 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/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 a2c6a9206..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([ @@ -113,4 +149,77 @@ describe('Commerce runtime configuration', () => { enableShipping: false, }); }); + + 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'] }, + }; + const checkout = { enablePromotionCodes: true, enableTaxCollection: true, enableShipping: false }; + const configuration = createRuntimeCommerceConfiguration({ + environment: { + ...environment(), + GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ ...checkout, paymentMethods }), + }, + }); + expect(configuration.readCheckout(logger)).toEqual({ ...checkout, paymentMethods }); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + 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: { processor: 'godaddy', checkoutTypes: ['standard'] } }, + { googlePay: { processor: 'godaddy', checkoutTypes: ['standard'], secret: 'not-allowed' } }, + { googlePay: {} }, + { googlePay: { processor: 'godaddy' } }, + { googlePay: { checkoutTypes: ['standard'] } }, + { googlePay: 'true' }, + { googlePay: { processor: 123 } }, + { googlePay: { checkoutTypes: 'standard' } }, + { 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 => { + const logger = { error: vi.fn(), warn: vi.fn() }; + const checkout = { enablePromotionCodes: true, enableTaxCollection: true, enableShipping: false }; + const configuration = createRuntimeCommerceConfiguration({ + environment: { + ...environment(), + GODADDY_CHECKOUT_CONFIGURATION: JSON.stringify({ ...checkout, paymentMethods }), + }, + }); + 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 c5c06b05f..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 { @@ -230,6 +334,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 +364,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..5d533b1f8 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, @@ -91,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(); }, ); @@ -111,6 +117,119 @@ 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, logger); + expect(mockGqlRequest.mock.calls[0]?.[0].variables.input.paymentMethods).toEqual(paymentMethods); + expect(logger.warn).not.toHaveBeenCalled(); + }, + ); + + 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) => { + const logger = { error: vi.fn(), warn: vi.fn() }; + checkout = { + ...checkout, + enableTaxCollection: true, + paymentMethods: paymentMethods as CommerceCheckoutConfiguration['paymentMethods'], + }; + mockGqlRequest.mockResolvedValue(response({ enableTaxCollection: true })); + + 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(); + }, + ); + + 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( + { + ...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..dd22fefab 100644 --- a/packages/commerce-server/src/index.ts +++ b/packages/commerce-server/src/index.ts @@ -4,10 +4,15 @@ 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, 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 6568a42d3..ce1d9c7a7 100644 --- a/packages/commerce-server/src/lib/commerce/checkout-config.ts +++ b/packages/commerce-server/src/lib/commerce/checkout-config.ts @@ -1,3 +1,6 @@ +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 { readonly originAddress?: Readonly>; @@ -9,6 +12,83 @@ 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); +} + +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, + 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 invalidPaymentMethods(logger); + if (method === null) continue; + if ( + !isRecord(method) || + Object.keys(method).some((key) => key !== 'processor' && key !== 'checkoutTypes') + ) { + return invalidPaymentMethods(logger); + } + if ( + typeof method.processor !== 'string' || + !method.processor || + method.processor !== method.processor.trim() + ) { + return invalidPaymentMethods(logger); + } + if ( + !Array.isArray(method.checkoutTypes) || + method.checkoutTypes.length === 0 || + !method.checkoutTypes.every( + (type: unknown) => typeof type === 'string' && type !== '' && type === type.trim(), + ) + ) + return invalidPaymentMethods(logger); + hasEnabledMethod = true; + } + return hasEnabledMethod ? (value as CheckoutSessionPaymentMethodsInput) : invalidPaymentMethods(logger); } const DEFAULT_CHECKOUT_CONFIGURATION: CommerceCheckoutConfiguration = { @@ -17,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; @@ -53,10 +136,12 @@ export function parseCommerceCheckoutConfiguration(raw: string | undefined): Com } } + const configuredPaymentMethods = parseCheckoutPaymentMethods(candidate.paymentMethods, logger); 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/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 8bba55e01..86b3be980 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, @@ -25,6 +26,7 @@ import { DEFAULT_CHECKOUT_PAYMENT_METHODS, getOAuthAccessToken, } from './checkout-subgraph'; +import { type CommerceLogger, consoleCommerceLogger } from './commerce-route'; import { type CommerceConfiguration, createRuntimeCommerceConfiguration, @@ -169,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; @@ -193,7 +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, logger) ?? + DEFAULT_CHECKOUT_PAYMENT_METHODS; const enablePromotionCodes: boolean = promotionCodesEnabled(checkoutConfiguration); const catalogShippingEnabled: boolean = lineItemData === undefined && checkoutConfiguration.enableShipping; const checkoutOAuthScope: string = 'commerce.product:read'; @@ -211,7 +217,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 +256,7 @@ export async function createCheckoutSession( { ...attribution, enableTaxCollection: checkoutConfiguration.enableTaxCollection, - paymentMethods: DEFAULT_CHECKOUT_PAYMENT_METHODS, + paymentMethods, }, ) : buildBuyNowCheckoutInput( @@ -308,7 +314,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.'); } 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);