How to conditionally remove a payment option from checkout?

30 views Asked by At

Just looking for some guidance on this. Let's say I have a product id of 7025617862758 and payments options that are Credit Card and AfterPay. When this product has been added to the cart, regardless of what other products are in the cart, I'd like to hide the AfterPay payment option, and only allow for Credit Card.

I was thinking of creating an app for this (I have no experience doing so), and then using graphql to do a cart query to check what products it has. If that ID is in the cart then remove the payment option.

Does this sound like the correct approach? or am I over complicating it?

1

There are 1 answers

0
GDelsaux On

Yes definitely the right approach, creating a custom app isn't that complicated. The documentation from Shopify is pretty decent.

You'd need to use the 'new' checkout extensibility functions.

An example would be:

// @ts-check

// Use JSDoc annotations for type safety
/**
* @typedef {import("../generated/api").RunInput} RunInput
* @typedef {import("../generated/api").FunctionRunResult} FunctionRunResult
*/

/**
* @type {FunctionRunResult}
*/
const NO_CHANGES = {
  operations: [],
};

// The configured entrypoint for the 'purchase.payment-customization.run' extension target
/**
* @param {RunInput} input
* @returns {FunctionRunResult}
*/
export function run(input) {
  // Get the cart total from the function input, and return early if it's below 100
  const cartTotal = parseFloat(input.cart.cost.totalAmount.amount ?? "0.0");
  if (cartTotal < 100) {
    // You can use STDERR for debug logs in your function
    console.error("Cart total is not high enough, no need to hide the payment method.");
    return NO_CHANGES;
  }

  // Find the payment method to hide
  const hidePaymentMethod = input.paymentMethods
    .find(method => method.name.includes("Cash on Delivery"));

  if (!hidePaymentMethod) {
    return NO_CHANGES;
  }

  // The @shopify/shopify_function package applies JSON.stringify() to your function result
  // and writes it to STDOUT
  return {
    operations: [{
      hide: {
        paymentMethodId: hidePaymentMethod.id
      }
    }]
  };
};

You can find more detail with this link https://shopify.dev/docs/apps/checkout/payments/getting-started