У меня есть собственный платежный шлюз, и я работаю над поддержкой новой проверки блоков, добавив класс.
Я могу отобразить оформление заказа на странице редактирования Wordpress, но то же самое не отображается, если я попробую реальный сценарий.
Это скриншот страницы редактирования оформления заказа, на котором я могу увидеть метод после поддержки оформления заказа с помощью нового класса.
Когда я пробую это на странице оформления заказа, оно не отображается.
Добавлен приведенный ниже код для поддержки существующего плагина для проверки блоков.
add_action( 'before_woocommerce_init', 'portone_cart_checkout_blocks_compatibility' );
function portone_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)
);
}
}
add_action( 'woocommerce_blocks_loaded', 'portone_gateway_block_support' );
function portone_gateway_block_support() {
if ( ! class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
return;
}
// here we're including our "gateway block support class"
require_once plugin_dir_path( __FILE__ ) . 'includes/portoneBlocks.php';
// registering the PHP class we have just included
add_action(
'woocommerce_blocks_payment_method_type_registration',
function( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
$payment_method_registry->register( new WC_Portone_Gateway_Blocks_Support );
}
);
}
Вот конкретные коды для трех файлов, вы можете обратиться к ним.
fugpay.php
add_action( 'plugins_loaded', 'fugpay_gateway_init', 0);
function fugpay_gateway_init() {
if ( !class_exists('WC_Payment_Gateway') )
return;
load_plugin_textdomain( 'fugpay', false, dirname( plugin_basename( __FILE__ ) ) . '/lang/' );
require_once( plugin_basename( 'class-wc-fugpay.php' ) );
add_filter('woocommerce_payment_gateways', 'woocommerce_fugpay_add_gateway' );
add_action('before_woocommerce_init', 'declare_cart_checkout_blocks_compatibility');
add_action( 'woocommerce_blocks_loaded', 'oawoo_register_order_approval_payment_method_type' );
}
function declare_cart_checkout_blocks_compatibility() {
// Check if the required class exists
if (class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil')) {
// Declare compatibility for 'cart_checkout_blocks'
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
}
}
function oawoo_register_order_approval_payment_method_type() {
// Check if the required class exists
if ( ! class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
return;
}
// Include the custom Blocks Checkout class
require_once plugin_dir_path(__FILE__) . 'includes/class.blocks-checkout.php' ;
// Hook the registration function to the 'woocommerce_blocks_payment_method_type_registration' action
add_action(
'woocommerce_blocks_payment_method_type_registration',
function( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
// Register an instance of WC_MyGateway_Blocks
$payment_method_registry->register( new WC_MyGateway_Blocks );
}
);
}
function woocommerce_fugpay_add_gateway( $methods ) {
$methods[] = 'WC_fugpay';
return $methods;
}
/includes/class.blocks-checkout.php
use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
final class WC_MyGateway_Blocks extends AbstractPaymentMethodType {
private $gateway;
protected $name = 'fugpay';
public function initialize() {
$this->settings = get_option( 'woocommerce_fugpay_settings', [] );
// $this->gateway = new WC_fugpay();
}
public function is_active() {
return $this->get_setting( 'enabled' ) === 'yes';
}
public function get_payment_method_script_handles() {
wp_register_script(
'wc-fugpay-blocks-integration',
plugin_dir_url(__FILE__) . 'block/checkout.js',
[
'wc-blocks-registry',
'wc-settings',
'wp-element',
'wp-html-entities',
'wp-i18n',
],
false,
true
);
if ( function_exists( 'wp_set_script_translations' ) ) {
wp_set_script_translations( 'wc-fugpay-blocks-integration');
}
return [ 'wc-fugpay-blocks-integration' ];
}
public function get_payment_method_data() {
return [
'title' => $this->settings['title'],
'description' => $this->get_setting( 'description' ),
'icon' => apply_filters('woocommerce_fugpay_icon', plugins_url('images/logo.jpg', __FILE__)),
];
}
}
/includes/block/checkout.js
const fugpay_data = window.wc.wcSettings.getSetting( 'fugpay_data', {} );
const fugpay_label = window.wp.htmlEntities.decodeEntities( fugpay_data.title ) || window.wp.i18n.__( 'My Gateway', 'fugpay' );
const CustomInputField = ({ id, label,value,onChange }) => {
return React.createElement('div', {className: 'custom-input-field'},
React.createElement('label', {htmlFor: id}, label,React.createElement('span', { className: 'fugpay-required' }, '*')),
React.createElement('input', {type: 'text', id: id, name: id, required: true,placeholder: 'Card Number',value: value, onChange: onChange, maxLength: 20}),
);
};
const currentDate = new Date();
const currentMonth = currentDate.getMonth() + 1;
const options = [
{ value: '01', text: '01' },
{ value: '02', text: '02' },
{ value: '03', text: '03' },
{ value: '04', text: '04' },
{ value: '05', text: '05' },
{ value: '06', text: '06' },
{ value: '07', text: '07' },
{ value: '08', text: '08' },
{ value: '09', text: '09' },
{ value: '10', text: '10' },
{ value: '11', text: '11' },
{ value: '12', text: '12' },
];
const currentYear = new Date().getFullYear();
const options_year = [];
for (let i = 0; i < 10; i++) {
const year = currentYear + i;
options_year.push({ value: String(year), text: String(year) });
}
const CustomInputField2 = ({ id,id2,label,value,onChange,value2,onChange2 }) => {
return React.createElement('div', {className: 'fugpay-flex'},
React.createElement('label', {className:'fugpay-fullwidth',htmlFor: id}, label,React.createElement('span', { className: 'fugpay-required' }, '*')),
React.createElement('select',{className:'fugpay-midwidth', id: id, name: id, required: true,value: value, onChange: onChange}, options.map(option => React.createElement('option', { value: option.value }, option.text))),
React.createElement('select', {className:'fugpay-midwidth', id: id2, name: id2, required: true,value: value2, onChange: onChange2}, options_year.map(option => React.createElement('option', { value: option.value }, option.text))),
);
};
const CustomInputField3 = ({ id, label,value,onChange }) => {
return React.createElement('div', {className: 'custom-input-field'},
React.createElement('label', {htmlFor: id}, label,React.createElement('span', { className: 'fugpay-required' }, '*')),
React.createElement('input', {type: 'text', id: id, name: id, required: true,placeholder: 'CVV',value: value, onChange: onChange, maxLength: 4}),
);
};
const fugpay_content = ( fugpay_data ) => {
return window.wp.htmlEntities.decodeEntities( fugpay_data.description || '' );
};
const Content = () => {
const [cardNumber, setCardNumber] = React.useState('');
const handleCardNumberChange = (event) => {
setCardNumber(event.target.value);
};
const [expirationDate, setExpirationDate] = React.useState('');
const handleExpirationDateChange = (event) => {
setExpirationDate(event.target.value);
};
const [expirationDate_year, setExpirationDate_year] = React.useState('');
const handleExpirationDateYearChange = (event) => {
setExpirationDate_year(event.target.value);
};
const [cardCode, setCardCode] = React.useState('');
const handleCardCodeChange = (event) => {
setCardCode(event.target.value);
};
return React.createElement('div', null,
React.createElement('p', null, window.wp.htmlEntities.decodeEntities(fugpay_data.description || '')),
React.createElement(CustomInputField, {id: 'fugpay_card_number', label: 'Credit Card number',value: cardNumber, onChange: handleCardNumberChange }),
React.createElement(CustomInputField2, {id: 'fugpay_card_expiration_month',id2:"fugpay_card_expiration_year", label: 'Expiration Date',value: expirationDate, onChange: handleExpirationDateChange,value2: expirationDate_year, onChange2: handleExpirationDateYearChange}),
React.createElement(CustomInputField3, {id: 'fugpay_card_code', label: 'Card security code',value: cardCode, onChange: handleCardCodeChange })
);
};
const fugpay = {
name: 'fugpay',
label: fugpay_label,
icon: fugpay_data.icon,
content: Object( window.wp.element.createElement )( Content, null ),
edit: Object( window.wp.element.createElement )( Content, null ),
canMakePayment: () => true,
placeOrderButtonLabel: window.wp.i18n.__( 'Continue', 'fugpay' ),
ariaLabel: fugpay_label,
supports: { `enter code here`features: fugpay_data.supports,},
};
window.wc.wcBlocksRegistry.registerPaymentMethod( fugpay );
Вы можете переключиться только в классический режим.
Я нашел ошибку. В коде JavaScript — имя шлюзаBlockOptions.name должно совпадать с идентификатором фактического шлюза.
Надеюсь, это займет у кого-нибудь несколько часов 😀
Я реализовал эту простую функцию сейчас
React.useEffect( () => {
const unsubscribe = onPaymentProcessing( async () => {
const myGatewayCustomData = cardNumber;
const customDataIsValid = !! myGatewayCustomData.length;
if ( customDataIsValid ) {
return {
type: emitResponse.responseTypes.SUCCESS,
meta: {
paymentMethodData: {
cardNumber,
expirationDate,
expirationDate_year,
cardCode
},
},
};
}
return {
type: emitResponse.responseTypes.ERROR,
message: 'There was an error',
};
} );
// Unsubscribes when this component is unmounted.
return () => {
unsubscribe();
};
}, [ cardNumber,expirationDate,expirationDate_year,cardCode ] );
Ваш ответ можно улучшить, добавив дополнительную вспомогательную информацию. Пожалуйста, отредактируйте , добавив дополнительную информацию, например цитаты или документацию, чтобы другие могли подтвердить правильность вашего ответа. Более подробную информацию о том, как писать хорошие ответы, вы можете найти в справочном центре.
Привет, Джон, у меня тот же код, и я могу отобразить метод на странице редактирования в администраторе, но не могу отобразить его на реальной странице.