Payment Form: Cookbook

Respond to a Shipping Contact Change

Recalculate shipping fees and taxes when a buyer changes the shipping address in the Apple Pay or Google Pay payment sheet.

Before you start Permalink Get a link to this section

Shipping contact change Permalink Get a link to this section

Use the shippingContactChanged callback to validate a shipping contact or respond to a change in the shipping contact chosen in the Apple Pay or Google Pay payment sheet.

Add the shippingContactChanged callback function to the callbacks property of the SqPaymentForm initializing argument. Use the callback to calculate a new shipping cost and other fees. If the calculation results in a line item amount change or different shipping options, update the payment request with the new amounts by calling the done function in the callback.

For an Apple Pay payment request, avoid a timeout by calling done within 30 seconds to respond to the shipping contact change. Pass in an optional PaymentDetailsUpdate object to send errors or update the payment total, line items, and shipping options.

Google Pay does not timeout the shipping option changed callback.

Note

To provide granular shipping address error messages, set shippingContactErrors to an object of type SqShippingErrors.

var paymentForm = new SqPaymentForm({

  ...

  // SqPaymentForm callback functions
  callbacks: {

    ...

    shippingContactChanged: function (shippingContact, done) {
      var valid = true;
      var shippingErrors = {};

      if (!shippingContact.postalCode) {
        shippingErrors.postalCode = "postal code is required";
        valid = false;
      }

      if (!valid) {
        done({shippingContactErrors: shippingErrors});
        return;
      }

      // Shipping address unserviceable.
      if (shippingContact.country !== 'US' || shippingContact.country !== 'CA') {
        done({error: 'Shipping to outside of the U.S. and Canada is not available.'});
        return;
      }

      // Update total, lineItems, and shippingOptions for Canadian address.
      if (shippingContact.country === 'CA') {
        const tax = 1000 * 0.08;
        done({
          total: {
            label: "MERCHANT NAME",
            amount: (1000 + tax).toFixed(2),
            pending: true
          },
          lineItems: [
            {
              label: "Subtotal",
              amount: "1000.00",
              pending: false
            },
            {
              label: "Tax",
              amount: tax.toFixed(2),
              pending: false
            }
          ],
          shippingOptions: [
            {
              id: "1",
              label: "International Shipping",
              amount: "20.00"
            }
          ]
        });
        return;
      }

    // Everything looks good and nothing to update
      done();
    }
  ...

});