Skip to content

Instantly share code, notes, and snippets.

@nerrad
Created April 23, 2021 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nerrad/fa24d2bf01c1726f62bec7accac8be39 to your computer and use it in GitHub Desktop.
Save nerrad/fa24d2bf01c1726f62bec7accac8be39 to your computer and use it in GitHub Desktop.
Modifying existing payment method config in WooCommerce Blocks checkout flow

DISCLAIMER: PLEASE READ

Note, this is just a proof of concept as an example of how this type of functionality could be implemented and should be used only if you understand the code. This uses an experimental interface provided by the WooCommerce Blocks API and it may get removed or changed in the future.

This is use at your own risk. Is not an official solution and not supported.

Ideally this kind of behaviour should be something that is provided by the official payment method extension.

WHAT THIS DOES

This is a code snippet that gives an example of how you can tweak a payment registered for the new WooCommerce Blocks checkout flow so that you can conditionally control when it's available for shoppers based on various criteria. In this case we're using whatever the billing country is set at.

You can find more about the payment method registration API in this doc

INSTALLATION

This example is a WordPress plugin. However, I do recommend you make sure you namespace things appropriately if you use. It's just in this format for demonstration and testing purposes.

// note this JS file requires modern browser support.
(function () {
const {
__experimentalDeRegisterPaymentMethod,
registerPaymentMethod,
getPaymentMethods,
} = wc.wcBlocksRegistry;
const paymentMethods = getPaymentMethods();
const paypalPaymentMethod = paymentMethods["paypal"];
const newOptions = {
...paypalPaymentMethod,
canMakePayment: ({ billingData }) => {
return billingData?.country === "CA";
},
};
// unregister the existing payment method
__experimentalDeRegisterPaymentMethod("paypal");
//register our enhanced version
registerPaymentMethod(newOptions);
})();
<?php
/**
* Plugin Name: Woo Blocks Checkout Flow Payment Method Restriction
* Description: A prototype example of how to restrict when a payment method is available to a shopper (using Paypal Standard as an example).
* Version: 1.0.0
* Author: Darren Ethier
* Author URI: https://unfoldingneurons.com
* Requires at least: 5.7
* Requires PHP: 7.2
*/
add_action( 'woocommerce_blocks_enqueue_checkout_block_scripts_before', function() {
wp_enqueue_script(
'woo-blocks-checkout-payment-method-restriction',
plugin_dir_url( __FILE__ ) . 'woo-blocks-checkout-flow-payment-restriction.js',
[ 'wc-payment-method-paypal' ],
'1.1',
true
);
}, 20 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment