How to integrate a custom payment gateway with the WooCommerce Checkout block

Before you start, you can find a complete tutorial on creating a WooCommerce payment gateway (be sure to read it before reading this article), but in the latest version of WooCommerce (starting with 8.3, I guess), you may notice that your custom payment method is not available in the checkout block.

For example, if you try to deactivate all payment methods in the store except the custom payment method, you may receive the following error message:

自定义付款方式未显示在结账栏中
Here I use the Storefront theme as an example, but any WordPress theme will get the same error message.

But what is certain is that when you use the old one[woocommerce_checkout]When it comes to shortcode, everything works well.

Yes, the previously released Payment Gateway tutorial no longer seems complete, but we will change it with this additional tutorial today, and I will step by step guide you on what you should do to add custom compatibility to WooCommerce payment methods for WooCommerce shopping carts and checkout blocks.

This is what we want to achieve at the end of this tutorial:

自定义支付网关与 WooCommerce 结帐块集成

Of course, I will also show you some clever extras, such as adding custom icons to your payment method.

article directories

Server-side integration 

First, let’s start with server-side integration, and I’m sure many of you find developing in PHP more comfortable than JavaScript + React, so let’s start with something simple.

Register a block to support PHP classes 

The “Block Support PHP Class” is a PHP class in addition to the main payment gateway class. We’ll use the following simple code fragment to register it, which is similar to what we saw in woocommerce_payment_gateways Similar to what you do when registering the main gateway class in hook.

add_action( 'woocommerce_blocks_loaded', 'rudr_gateway_block_support' );
function rudr_gateway_block_support() {

	// if( ! class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
	// 	return;
	// }

	//Introduce the "gateway block support class" file here
	require_once __DIR__ . '/includes/class-wc-misha-gateway-blocks-support.php';

	//Register the PHP class we just introduced
	add_action(
		'woocommerce_blocks_payment_method_type_registration',
		function( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
			$payment_method_registry->register( new WC_Misha_Gateway_Blocks_Support );
		}
	);

}

Keep the following points in mind:

  • I canceledclass_exists()Conditions, because we no longer need it, because the checkout block is now part of WooCommerce, not a separate plug-in.
  • Our block-supporting PHP class itself will be located in a separate file, and we will review it in the next stepclass-wc-misha-gateway-blocks-support.phpCheck it.

Block supports PHP classes 

In this section, I will create aWC_Misha_Gateway_Blocks_Support PHP classes to extend WooCommerce’s AbstractPaymentMethodType Class. And don’t forget that we already have extensions WC_Payment_Gateway WC_Misha_Gateway class of.

For my part, I put it inincludes/class-wc-misha-gateway-blocks-support.php.

& lt;?php
Use Automattic\ WooCommerce\ Blocks\ Payments\ Integrations\ AbstractPaymentMethodType

Final class WC_Misha_Gateway_Blocks_Support extends AbstractPaymentMethodType {

Private $gateway

Protected $name = 'misha'; / / payment gateway id

Public function initialize () {
/ / get payment gateway settings
$this->settings = get_option ("woocommerce_ {$this->name} _ settings", array ())

/ / you can also initialize your payment gateway here
/ / $gateways = WC ()-& gt;payment_gateways->payment_gateways ()
/ / $this->gateway = $gateways[ $this->name]
}

Public function is_active () {
Return! Empty ($this->settings[ 'enabled']) & &' yes' = = $this->settings[ 'enabled']
}

Public function get_payment_method_script_handles () {

Wp_register_script (
'wc-misha-blocks-integration'
Plugin_dir_url (_ _ DIR__). 'build/index.js'
Array (
'wc-blocks-registry'
'wc-settings'
'wp-element'
'wp-html-entities'
),
Null, / / or time () or filemtime (...) To skip caching
True
);

Return array ('wc-misha-blocks-integration')

}

Public function get_payment_method_data () {
Return array (
'title' = & gt; $this->get_setting (' title')
/ / almost the same way:
/ / 'title' = & gt; isset ($this->settings[' title'])? $this->settings[ 'title']:' Default value'
'description' = & gt; $this->get_setting (' description')
/ / if $this->gateway was initialized on line 15
/ / 'supports' = & gt; array_filter ($this->gateway->supports, & # 91; $this->gateway,' supports'])

/ / example of getting a public key
/ / 'publicKey' = & gt; $this->get_publishable_key ()
);
}

/ / private function get_publishable_key () {
/ / $test_mode = (! Empty ($this->settings[ 'testmode']) & &' yes' = = $this->settings[ 'testmode'])
/ / $setting_key = $test_mode? 'test_publishable_key': 'publishable_key'
/ / return! Empty ($this->settings[ $setting_key)? $this->settings[ $setting_key]:''
/ /}

}

Let’s first look at the properties and methods of the class.

Attribute:

  • $name– This is the payment gateway ID in this step.
  • $gateway– We can store an instance of the payment gateway object here, but it’s not necessary, so I commented on this part in the code.

Method:

  • is_active(),
  • get_payment_method_script_handles()– This is where we include the JavaScript file, which includes the integrated client part.
  • get_payment_method_data()– Provides all necessary data that you will use on the front end as an associative array.

you can also useindex.asset.phpTo get the script version and dependencies.

public function get_payment_method_script_handles() {

	$asset_path   = plugin_dir_path( __DIR__ ) . 'build/index.asset.php';
	$version      = null;
	$dependencies = array();
	if( file_exists( $asset_path ) ) {
		$asset        = require $asset_path;
		$version      = isset( $asset[ 'version' ] ) ? $asset[ 'version' ] : $version;
		$dependencies = isset( $asset[ 'dependencies' ] ) ? $asset[ 'dependencies' ] : $dependencies;
	}
	
	wp_register_script( 
		'wc-misha-blocks-integration', 
		plugin_dir_url( __DIR__ ) . 'build/index.js', 
		$dependencies, 
		$version, 
		true 
	);

	return array( 'wc-misha-blocks-integration' );

}

Declare compatibility 

When you want users to know your payment method with WooCommerce Checkout BlockThis section is usually useful when incompatible.

When users try to edit the checkout page in Gutenberg, they will receive a notification:

自定义付款方式不支持 WooCommerce 结账阻止的通知。

The method is as follows:

add_action( 'before_woocommerce_init', 'rudr_cart_checkout_blocks_compatibility' );

function rudr_cart_checkout_blocks_compatibility() {

    if( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
				'cart_checkout_blocks',
				__FILE__,
				false // true (compatible, default) or false (not compatible)
			);
    }
		
}

client integration 

setting items 

Again, I want the content in this tutorial to remain super simple, so I’ll just use @wordpress/scripts.

In our build, you can definitely further configure the WooCommerce hybrid build so you can use theimport { registerPaymentMethod } from ....

This is what my folder structure looks like:

具有 WooCommerce 结账块支持的自定义支付网关的文件夹结构。

Register a custom payment method for the WooCommerce Checkout block 

answers here’s/src/index.jsDocuments in case you have questions.

import { decodeEntities } from '@wordpress/html-entities';

const { registerPaymentMethod } = window.wc.wcBlocksRegistry
const { getSetting } = window.wc.wcSettings

const settings = getSetting( 'misha_data', {} )

const label = decodeEntities( settings.title )

const Content = () => {
	return decodeEntities( settings.description || '' )
}

const Label = ( props ) => {
	const { PaymentMethodLabel } = props.components
	return <PaymentMethodLabel text={ label } />
}

registerPaymentMethod( {
	name: "misha",
	label: <Label />,
	content: <Content />,
	edit: <Content />,
	canMakePayment: () => true,
	ariaLabel: label,
	supports: {
		features: settings.supports,
	}
})

Maybe discuss in detail registerPaymentMethod() and discussions registerExpressPaymentMethod()That’s a good idea, but I think we’ll delve into specific examples more in depth in the next tutorial on my blog.

Finally! Congratulations!

自定义支付网关与 WooCommerce 结帐块集成

If you want to know the source of the payment method title and description:

How to integrate a custom payment gateway with the WooCommerce Checkout block

Add payment method icon 

Since I promised you more examples, and you may not want to wait until the next tutorial, let’s start with this.

My goal now is to display an icon near the custom payment gateway title in the WooCommerce Checkout block:

将徽标添加到 WooCommerce 结帐块中的自定义支付网关。

First, let’s modify our block’s support for PHP classes, especially itsget_payment_method_data(), we will provide another parameter there:

public function get_payment_method_data() {
	return array(
		'title'        => $this->get_setting( 'title' ),
		'description'  => $this->get_setting( 'description' ),
		'icon'         => plugin_dir_url( __DIR__ ) . 'assets/icon.png',
		
		...

Then I suggested creating another React component for it:

const Icon = () => {
	return settings.icon 
		? <img src={settings.icon} style={{ float: 'right', marginRight: '20px' }} /> 
		: ''
}

const Label = () => {
	return (
        <span style={{ width: '100%' }}>
            {label}
            <Icon />
        </span>
    );
};

If the icon image URL is not provided, it will not be displayed<img>Labels, great!

Statement: The original text is from https://rudrastyh.com/woocommisce/checkout-block-payment-method-integration.html and translated by WordPress University. Please keep this statement if you reprint it.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注