|
| 1 | +import { |
| 2 | + hostedCheckoutEndpoint, |
| 3 | + normalizePaymentMethodTypes, |
| 4 | + shouldShowAutomaticTax, |
| 5 | + supportsAdvancedCollection, |
| 6 | + type CheckoutPlaygroundConfig, |
| 7 | +} from '../checkoutPlayground/types'; |
| 8 | + |
| 9 | +export type CheckoutSessionResponse = { |
| 10 | + publishableKey: string; |
| 11 | + checkoutSessionClientSecret: string; |
| 12 | +}; |
| 13 | + |
| 14 | +const isRecord = (value: unknown): value is Record<string, unknown> => |
| 15 | + typeof value === 'object' && value !== null; |
| 16 | + |
| 17 | +const isCheckoutSessionResponse = ( |
| 18 | + value: unknown |
| 19 | +): value is CheckoutSessionResponse => |
| 20 | + isRecord(value) && |
| 21 | + typeof value.publishableKey === 'string' && |
| 22 | + value.publishableKey.length > 0 && |
| 23 | + typeof value.checkoutSessionClientSecret === 'string' && |
| 24 | + value.checkoutSessionClientSecret.length > 0; |
| 25 | + |
| 26 | +const getCheckoutSessionErrorMessage = (value: unknown): string | undefined => { |
| 27 | + if (typeof value === 'string') { |
| 28 | + const trimmedValue = value.trim(); |
| 29 | + return trimmedValue || undefined; |
| 30 | + } |
| 31 | + |
| 32 | + if (isRecord(value) && typeof value.error === 'string') { |
| 33 | + const trimmedError = value.error.trim(); |
| 34 | + return trimmedError || undefined; |
| 35 | + } |
| 36 | + |
| 37 | + return undefined; |
| 38 | +}; |
| 39 | + |
| 40 | +async function parseCheckoutSessionResponseBody(response: { |
| 41 | + text(): Promise<string>; |
| 42 | +}): Promise<unknown> { |
| 43 | + const responseText = await response.text(); |
| 44 | + |
| 45 | + if (!responseText.trim()) { |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + try { |
| 50 | + return JSON.parse(responseText) as unknown; |
| 51 | + } catch { |
| 52 | + return responseText; |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +export type CheckoutSessionRequestBody = { |
| 57 | + merchant_country_code: string; |
| 58 | + mode: CheckoutPlaygroundConfig['mode']; |
| 59 | + currency: CheckoutPlaygroundConfig['currency']; |
| 60 | + customer: CheckoutPlaygroundConfig['customerType']; |
| 61 | + allow_promotion_codes: boolean; |
| 62 | + phone_number_collection: boolean; |
| 63 | + shipping_address_collection: boolean; |
| 64 | + billing_address_collection: boolean; |
| 65 | + include_shipping_options: boolean; |
| 66 | + automatic_tax: boolean; |
| 67 | + payment_method_types: string[]; |
| 68 | + adaptive_pricing: boolean; |
| 69 | + checkout_session_payment_method_save: 'enabled' | 'disabled'; |
| 70 | + checkout_session_payment_method_remove: 'enabled' | 'disabled'; |
| 71 | + customer_email?: string; |
| 72 | +}; |
| 73 | + |
| 74 | +export function buildCheckoutSessionRequestBody( |
| 75 | + config: CheckoutPlaygroundConfig |
| 76 | +): CheckoutSessionRequestBody { |
| 77 | + const advancedCollectionEnabled = supportsAdvancedCollection(config); |
| 78 | + const allowPromotionCodes = advancedCollectionEnabled |
| 79 | + ? config.allowPromotionCodes |
| 80 | + : false; |
| 81 | + const phoneNumberCollection = advancedCollectionEnabled |
| 82 | + ? config.phoneNumberCollection |
| 83 | + : false; |
| 84 | + const automaticTax = shouldShowAutomaticTax(config) |
| 85 | + ? config.automaticTax |
| 86 | + : false; |
| 87 | + |
| 88 | + // The hosted demo backend uses this synthetic country code to exercise tax flows. |
| 89 | + const body: CheckoutSessionRequestBody = { |
| 90 | + merchant_country_code: 'us_tax', |
| 91 | + mode: config.mode, |
| 92 | + currency: config.currency, |
| 93 | + customer: config.customerType, |
| 94 | + allow_promotion_codes: allowPromotionCodes, |
| 95 | + phone_number_collection: phoneNumberCollection, |
| 96 | + shipping_address_collection: config.shippingAddressCollection, |
| 97 | + billing_address_collection: config.billingAddressCollection, |
| 98 | + include_shipping_options: config.enableShipping, |
| 99 | + automatic_tax: automaticTax, |
| 100 | + payment_method_types: normalizePaymentMethodTypes( |
| 101 | + config.paymentMethodTypes |
| 102 | + ), |
| 103 | + adaptive_pricing: config.adaptivePricing, |
| 104 | + checkout_session_payment_method_save: |
| 105 | + config.checkoutSessionPaymentMethodSave ? 'enabled' : 'disabled', |
| 106 | + checkout_session_payment_method_remove: |
| 107 | + config.checkoutSessionPaymentMethodRemove ? 'enabled' : 'disabled', |
| 108 | + }; |
| 109 | + |
| 110 | + if (config.adaptivePricing && config.adaptivePricingCountry !== 'none') { |
| 111 | + body.customer_email = `test+location_${config.adaptivePricingCountry.toUpperCase()}@example.com`; |
| 112 | + } |
| 113 | + |
| 114 | + return body; |
| 115 | +} |
| 116 | + |
| 117 | +export async function fetchCheckoutSessionParams( |
| 118 | + config: CheckoutPlaygroundConfig |
| 119 | +): Promise<CheckoutSessionResponse> { |
| 120 | + if (normalizePaymentMethodTypes(config.paymentMethodTypes).length === 0) { |
| 121 | + throw new Error('Select at least one payment method.'); |
| 122 | + } |
| 123 | + |
| 124 | + const response = await fetch(hostedCheckoutEndpoint, { |
| 125 | + method: 'POST', |
| 126 | + headers: { |
| 127 | + 'Content-Type': 'application/json', |
| 128 | + }, |
| 129 | + body: JSON.stringify(buildCheckoutSessionRequestBody(config)), |
| 130 | + }); |
| 131 | + |
| 132 | + const responseBody = await parseCheckoutSessionResponseBody(response); |
| 133 | + |
| 134 | + if (!response.ok) { |
| 135 | + throw new Error( |
| 136 | + getCheckoutSessionErrorMessage(responseBody) || |
| 137 | + 'Failed to create checkout session.' |
| 138 | + ); |
| 139 | + } |
| 140 | + |
| 141 | + if (!isCheckoutSessionResponse(responseBody)) { |
| 142 | + throw new Error('Checkout session response was missing required fields.'); |
| 143 | + } |
| 144 | + |
| 145 | + return { |
| 146 | + publishableKey: responseBody.publishableKey, |
| 147 | + checkoutSessionClientSecret: responseBody.checkoutSessionClientSecret, |
| 148 | + }; |
| 149 | +} |
0 commit comments