Payment Form: Cookbook

Respond to a Change in Shipping Contact

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

Payment Form

Use the shippingContactChanged callback to validate a shipping contact or respond to a change in the shipping contact chosen in the Apple 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 line item amount change or different shipping options, update the payment request with the new amounts by calling the done function in the callback.

To avoid an Apple Pay timeout, call done within 30 seconds to respond to the shipping contact change. Pass in an optional PaymentDetailsUpdate to send errors or update the payment total, line items, and shipping options.

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 (!shippingContact.addressLines) {
        shippingErrors.addressLines = "address lines are 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();
    }
  ...

});

Contact Developer Support, join our Slack channel, or ask for help on Stack Overflow