我正在为WooCommerce撰写扩展程序,这样我就可以在下订单之前验证客户的年龄。通过向外部API发送特定请求来验证年龄,并且根据API的结果是否成功,订单应该成功或失败。
<?php
/**
* LicenseScanner Integration
*
* Enables LicenseScanner integration.
*
* @class WC_LicenseScanner
* @extends WC_Integration
*/
class WC_LicenseScanner extends WC_Integration {
/**
* Init and hook in the integration.
*
* @access public
* @return void
*/
public function __construct() {
$this->id = 'licensescanner';
$this->method_title = __( 'LicenseScanner', 'woocommerce' );
$this->method_description = __( 'LicenseScanner enables you to verify the age of the customer.', 'woocommerce' );
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Actions
add_action( 'woocommerce_update_options_integration_licensescanner', array( $this, 'process_admin_options' ) );
// Require phone number during the check-out
add_filter( 'woocommerce_billing_fields', array($this, 'wc_mandatory_filter_phone'), 10, 1 );
// Send age verification upon order
add_action( 'woocommerce_pay_order_before_submit', array($this, 'request_age_verification'));
}
/**
* Initialise Settings Form Fields
*
* @access public
* @return void
*/
function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'License Bar Code Scanner URL:', 'woocommerce' ),
'type' => 'text',
'description' => __( 'Enter the License Bar Code Scanner URL that the notification should be sent to once the user attempts to check out', 'woocommerce' ),
'desc_tip' => true,
'default' => get_option('woocommerce_licensescanner') ? get_option('woocommerce_licensescanner') : ''
)
);
}
function wc_mandatory_filter_phone( $address_fields ) {
$address_fields['billing_phone']['required'] = true;
return $address_fields;
}
function request_age_verification() {
throw new Exception('The age verification failed');
}
}
所以显然抛出一个例外并不足以让订单失败......或者我可能迷上了错误的行为? 我可能会以某种方式尝试使用JS禁用订单按钮,但如果潜在的攻击者只是在浏览器中启用它或向后端伪造请求,那就不够好了
答案 0 :(得分:1)
您应该尝试使用专用的 woocommerce_pay_order_before_submit
操作挂钩,而不是使用woocommerce_checkout_process
,所以在您的代码中:
// Send age verification upon order
add_action( 'woocommerce_checkout_process', array( $this, 'request_age_verification' ) );
它应该与它一起工作......