如何在woocommerce_checkout_process钩子中获取WooCommerce当前选中的支付网关
WooCommerce结账前获取用户最新选中支付网关的解决方案
问题根因
WC()->session中存储的chosen_payment_method默认不会随用户前端切换支付方式的操作实时同步,读取到的始终是用户进入结账页面时的初始选择值,因此会出现取值滞后的问题。
方案1:直接读取POST提交的实时支付方式(推荐)
结账表单提交时,会自动携带当前用户选中的支付方式参数payment_method,该参数完全同步用户最后一次选择的结果,优先级高于session存储值,修改后的代码如下:
/** * Process the checkout */ add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process'); function my_custom_checkout_field_process() { // 直接从POST参数中取实时选中的支付方式,比session更可靠 $selected_payment_method_id = isset($_POST['payment_method']) ? wc_clean($_POST['payment_method']) : ''; if($selected_payment_method_id == 'bacs'){ // 建议对自定义字段也做sanitize处理再校验 $extra_fields = [ 'extra_info_company', 'extra_info_ordernumber', 'extra_info_first_name', 'extra_info_last_name', 'extra_info_phonenumber', 'extra_info_email' ]; foreach ($extra_fields as $field) { if (empty($_POST[$field]) || !wc_clean($_POST[$field])) { wc_add_notice( __( 'Vul alle extra velden in.' ), 'error' ); break; } } } }
方案2:同步更新session中的支付方式值
如果你的其他业务逻辑也依赖WC()->session里的chosen_payment_method,可以新增钩子实现前端切换支付方式时自动更新session,不需要修改原有校验逻辑也能拿到最新值,新增代码如下:
/** * 切换支付方式时同步更新session中的选中值 */ add_action( 'woocommerce_checkout_update_order_review', 'sync_chosen_payment_method_to_session' ); function sync_chosen_payment_method_to_session( $posted_data ) { parse_str( $posted_data, $output ); if ( isset( $output['payment_method'] ) ) { WC()->session->set( 'chosen_payment_method', wc_clean( $output['payment_method'] ) ); } }
内容的提问来源于stack exchange,提问作者Marty
相关产品推荐
相关产品推荐

