Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐫 Make form fields optional for apple and google pay #73

Merged
merged 2 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions apps/vanilla-example/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,32 +97,32 @@ function initializeForm(token: string) {
},
onPaymentRequestLoad(paymentRequests) {
if (paymentRequests.apple_pay.isAvailable) {
console.log('Apple Pay is available');
const applePayButton = document.querySelector('#apple-pay-button') as HTMLButtonElement;
if (applePayButton) {
applePayButton.style.display = 'flex';

applePayButton.addEventListener('click', () => {
console.log('Apple Pay button clicked');
paymentRequests.apple_pay.startFlow({
overridePaymentRequest: { amount: { amountAtom: 420, currency: 'usd' }, pending: false },
});
});
}
}
if (paymentRequests.google_pay.isAvailable) {
console.log('Google Pay is available');
const googlePayButton = document.querySelector('#google-pay-button') as HTMLButtonElement;
if (googlePayButton) {
googlePayButton.style.display = 'flex';

googlePayButton.addEventListener('click', () => {
console.log('Google Pay button clicked');
paymentRequests.google_pay.startFlow({
overridePaymentRequest: { amount: { amountAtom: 420, currency: 'usd' }, pending: false },
});
});
}
} else if (!paymentRequests.google_pay.isAvailable && !paymentRequests.google_pay.isLoading) {
const googlePayButton = document.querySelector('#google-pay-button') as HTMLButtonElement;
googlePayButton.style.display = 'flex';
googlePayButton.disabled = true;
}
},
});
Expand Down
2 changes: 1 addition & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@getopenpay/openpay-js-react",
"version": "0.1.6",
"version": "0.1.7",
"description": "Accept payments through OpenPay, right on your site",
"author": "OpenPay <info@getopenpay.com> (https://getopenpay.com)",
"private": false,
Expand Down
39 changes: 26 additions & 13 deletions packages/utils/src/flows/stripe/stripe-pr-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
RunOjsFlow,
SimpleOjsFlowResult,
} from '../ojs-flow';
import { PaymentRequest } from '@stripe/stripe-js';
import { PaymentRequest, PaymentRequestPaymentMethodEvent } from '@stripe/stripe-js';
import {
confirmStripePrPM,
createStripePaymentRequest,
Expand All @@ -22,9 +22,9 @@ import {
startPaymentFlowForPR,
} from '../../cde-client';
import { Amount, FieldName } from '../../shared-models';
import { validateNonCdeFormFieldsForCC } from '../common/cc-flow-utils';
import { CheckoutRequest, StartPaymentFlowResponse } from '../../cde_models';
import { findCpmMatchingType, parseConfirmPaymentFlowResponse } from '../common/common-flow-utils';
import { validateNonCdeFormFieldsForCC } from '../common/cc-flow-utils';

const { log__, err__ } = createOjsFlowLoggers('stripe-pr');

Expand Down Expand Up @@ -124,10 +124,6 @@ export const runStripePrFlow: RunOjsFlow<StripePrFlowCustomParams, InitStripePrF
const anyCdeConnection = Array.from(context.cdeConnections.values())[0];
const pr = initResult.pr;

log__(`Validating non-CDE form fields`);
const cleanedFormInputs = overrideEmptyZipCode(nonCdeFormInputs);
const nonCdeFormFields = validateNonCdeFormFieldsForCC(cleanedFormInputs, flowCallbacks.onValidationError);

// TODO: adjust PR amounts as coupons are applied
if (customParams?.overridePaymentRequest) {
const override = customParams.overridePaymentRequest;
Expand All @@ -140,6 +136,11 @@ export const runStripePrFlow: RunOjsFlow<StripePrFlowCustomParams, InitStripePrF
log__(`Showing PR dialog...`);
pr.show();
const stripePmAddedEvent = await waitForUserToAddPaymentMethod(pr);
log__(`Stripe PM added event:`, stripePmAddedEvent);

log__(`Merging PM fields with form fields...`);
const mergedInputs = fillEmptyFormInputsWithStripePm(nonCdeFormInputs, stripePmAddedEvent);
const nonCdeFormFields = validateNonCdeFormFieldsForCC(mergedInputs, flowCallbacks.onValidationError);

log__(`PR dialog finished. Starting payment flow...`);
const startPaymentFlowResponse = await startPaymentFlowForPR(anyCdeConnection, {
Expand Down Expand Up @@ -183,13 +184,25 @@ export const runStripePrFlow: RunOjsFlow<StripePrFlowCustomParams, InitStripePrF
}
);

const overrideEmptyZipCode = (formInputs: Record<string, unknown>): Record<string, unknown> => {
const newFormInputs = { ...formInputs };
if (!newFormInputs[FieldName.ZIP_CODE]) {
log__(`Overriding empty zip code (only for google pay and apple pay)`);
newFormInputs[FieldName.ZIP_CODE] = '00000';
}
return newFormInputs;
const fillEmptyFormInputsWithStripePm = (
formInputs: Record<string, unknown>,
stripePmEvt: PaymentRequestPaymentMethodEvent
): Record<string, unknown> => {
const inputs = { ...formInputs };

// Try splitting full name into first and last
const [payerFirstName, ...payerLastNameParts] = stripePmEvt.payerName?.trim()?.split(/\s+/) ?? []; // Note that payerFirstName can also be undefined
const payerLastName = payerLastNameParts.join(' ') || undefined; // Force blank strings to be undefined

// Note: we use ||, not ?? to ensure that blanks are falsish
inputs[FieldName.FIRST_NAME] = inputs[FieldName.FIRST_NAME] || payerFirstName || '_OP_UNKNOWN';
inputs[FieldName.LAST_NAME] = inputs[FieldName.LAST_NAME] || payerLastName || '_OP_UNKNOWN';
inputs[FieldName.EMAIL] = inputs[FieldName.EMAIL] || stripePmEvt.payerEmail || 'op_unfilled@getopenpay.com';
inputs[FieldName.ZIP_CODE] = inputs[FieldName.ZIP_CODE] || stripePmEvt.shippingAddress?.postalCode || '00000';
inputs[FieldName.COUNTRY] = inputs[FieldName.COUNTRY] || stripePmEvt.shippingAddress?.country || 'US';

log__(`Final form inputs:`, inputs);
return inputs;
};

const updatePrWithAmount = (pr: PaymentRequest, amount: Amount, isPending: boolean): void => {
Expand Down
4 changes: 3 additions & 1 deletion packages/utils/src/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
StripeElements,
StripeElementsOptionsClientSecret,
Stripe as StripeType,
SetupIntentResult,
} from '@stripe/stripe-js';
import { Amount, CheckoutPaymentMethod, PaymentFlowStartedEventPayload } from './shared-models';
import { z } from 'zod';
Expand Down Expand Up @@ -166,7 +167,7 @@ export const confirmPaymentFlowForStripePRLegacy = async (
export const confirmStripePrPM = async (
nextActionMetadata: PaymentRequestNextActionMetadata,
stripePm: PaymentRequestPaymentMethodEvent
): Promise<void> => {
): Promise<SetupIntentResult> => {
if (!nextActionMetadata.stripe_pk || !nextActionMetadata.client_secret) {
throw new Error(`Invalid next action metadata format: ${JSON.stringify(nextActionMetadata)}`);
}
Expand All @@ -180,6 +181,7 @@ export const confirmStripePrPM = async (
} else {
stripePm.complete('success');
}
return confirmResult;
};

export const confirmPaymentFlowForStripeLink = async (payload: PaymentFlowStartedEventPayload): Promise<void> => {
Expand Down
2 changes: 1 addition & 1 deletion packages/vanilla/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@getopenpay/openpay-js",
"version": "0.1.6",
"version": "0.1.7",
"description": "Accept payments through OpenPay, right on your site",
"author": "OpenPay <info@getopenpay.com> (https://getopenpay.com)",
"license": "ISC",
Expand Down
2 changes: 1 addition & 1 deletion packages/vanilla/utils/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { connectToChild } from 'penpal';
export async function createConnection(iframe: HTMLIFrameElement, childOrigin?: string): Promise<CdeConnection> {
const connection = connectToChild({
iframe,
debug: true,
debug: false,
childOrigin,
});
const connectionObj = await connection.promise;
Expand Down