Skip to content
51 changes: 43 additions & 8 deletions src/js/frontend/wc-square.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ jQuery( document ).ready( ( $ ) => {
args.is_change_payment_method_request;
this.metrics = {};

this.is_building_payment_form = false;
this.has_pending_payment_form_refresh = false;

if ( $( 'form.checkout' ).length ) {
this.form = $( 'form.checkout' );
this.handle_checkout_page();
Expand Down Expand Up @@ -200,6 +203,13 @@ jQuery( document ).ready( ( $ ) => {
* @since 2.0.0
*/
set_payment_fields() {
// `this.payment_form` isn't set until a build finishes, so starting another build now
// would mount a second card. Apply this update once the current build settles.
if ( this.is_building_payment_form ) {
this.has_pending_payment_form_refresh = true;
return;
Comment thread
faisal-alvi marked this conversation as resolved.
Resolved
}

if ( this.payment_form ) {
// Don't re-initialize the payment form if it's already been initialized and exist in DOM.
if (
Expand All @@ -213,9 +223,14 @@ jQuery( document ).ready( ( $ ) => {
return;
}

// Destroy the payment form and re-initialize it.
// Destroy the payment form and re-initialize it. The reference is dropped first so an
// update arriving during the teardown is queued instead of destroying it again.
const payment_form = this.payment_form;
this.payment_form = null;
this.is_building_payment_form = true;

this.log( 'Destroying payment form' );
this.payment_form.destroy().then( () => {
payment_form.destroy().catch( () => {} ).then( () => {
this.log( 'Re-building payment form' );
this.initializeCard( this.payments );
} );
Expand All @@ -235,23 +250,43 @@ jQuery( document ).ready( ( $ ) => {
*
* @param {object} payments The Square payment object.
*/
initializeCard( payments ) {
async initializeCard( payments ) {
this.is_building_payment_form = true;

let defaultPostalCode = $( '#billing_postcode' ).val();
defaultPostalCode = defaultPostalCode || '';

payments.card( {
postalCode: defaultPostalCode, // Default postal code value.
} ).then( ( card ) => {
let card = null;

try {
card = await payments.card( {
postalCode: defaultPostalCode, // Default postal code value.
} );

if ( ! document.getElementById( 'wc-square-credit-card-container' ) ) {
this.end( 'initialize_payment_form', true );
return;
}

card.attach( '#wc-square-credit-card-container' );
// Only expose the card once it is mounted and ready to tokenize.
await card.attach( '#wc-square-credit-card-container' );
this.payment_form = card;
this.log( 'Payment form loaded' );
this.end( 'initialize_payment_form' );
} );
} catch ( error ) {
this.log( `Could not build payment form: ${ error }`, 'error' );
this.end( 'initialize_payment_form', true );

// Don't leave a half-built card behind for the next build to mount alongside.
await card?.destroy().catch( () => {} );
} finally {
this.is_building_payment_form = false;

if ( this.has_pending_payment_form_refresh ) {
this.has_pending_payment_form_refresh = false;
this.set_payment_fields();
}
}
}

/**
Expand Down
98 changes: 98 additions & 0 deletions tests/e2e/specs/a94.credit-card-form-lifecycle.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { test, expect } from '@playwright/test';
import { chromium } from 'playwright';
import { addOneOrMoreProductToCart } from '@woocommerce/e2e-utils-playwright';

import {
fillAddressFields,
fillCreditCardFields,
visitCheckout,
doesProductExist,
createProduct,
placeOrder,
waitForUnBlock,
} from '../utils/helper';

const cardFrame = '#wc-square-credit-card-container .sq-card-component';

/**
* Recreates the conditions that rendered the card field twice: Square is slow to build the card,
* and another plugin (e.g. a delivery date picker) triggers a checkout update as the page loads.
*
* @param {Object} page Playwright page object.
*/
async function slowCardWithCheckoutUpdate( page ) {
await page.route( /squarecdn\.com|squareupsandbox\.com/, async ( route ) => {
await new Promise( ( resolve ) => setTimeout( resolve, 1500 ) );
await route.continue().catch( () => {} );
} );

await page.addInitScript( () => {
document.addEventListener( 'DOMContentLoaded', () => {
jQuery( document.body ).one( 'updated_checkout', () => {
jQuery( document.body ).trigger( 'update_checkout' );
} );
} );
} );
}

test.beforeAll( 'Setup', async ( { baseURL } ) => {
const browser = await chromium.launch();
const page = await browser.newPage();

if ( ! ( await doesProductExist( baseURL, 'simple-product' ) ) ) {
await createProduct( page, {
name: 'Simple Product',
regularPrice: '14.99',
sku: 'simple-product',
} );

await expect( page.getByText( 'Product published' ) ).toBeVisible();
}

await browser.close();
} );

test( '[non-Block]: Checkout update while the card is loading renders a single card field @general', async ( {
page,
} ) => {
await slowCardWithCheckoutUpdate( page );
await addOneOrMoreProductToCart( page, 'simple-product' );
await visitCheckout( page, false );
await fillAddressFields( page, false );

await expect( page.locator( cardFrame ) ).toHaveCount( 1 );
await fillCreditCardFields( page, true, false );

// Give a late duplicate time to mount before checking again.
await page.waitForTimeout( 3000 );
await expect( page.locator( cardFrame ) ).toHaveCount( 1 );

await placeOrder( page, false );
await expect( page.locator( '.entry-title' ) ).toHaveText( 'Order received' );
} );

test( '[non-Block]: Placing an order before the card field is ready shows an error and can be retried @general', async ( {
page,
} ) => {
await slowCardWithCheckoutUpdate( page );
await addOneOrMoreProductToCart( page, 'simple-product' );
await visitCheckout( page, false );

await page.locator( 'label[for="payment_method_square_credit_card"]' ).click();
await expect( page.locator( cardFrame ) ).toHaveCount( 0 );
await page.locator( '#place_order' ).click();

await expect(
page
.getByText( 'An error occurred, please try again or try an alternate form of payment.' )
.first()
).toBeVisible();

await waitForUnBlock( page );
await fillAddressFields( page, false );
await fillCreditCardFields( page, true, false );
await expect( page.locator( cardFrame ) ).toHaveCount( 1 );

await placeOrder( page, false );
await expect( page.locator( '.entry-title' ) ).toHaveText( 'Order received' );
} );
Loading