我正在使用 woocommerce 插件和 woocommerce 的 braintree 扩展进行支付。我已经启用了 woocommerce braintree 的卡和 paypal 支付来结帐。我想弄清楚如何在用户实际结帐和付款之前知道用户选择了哪个支付网关。 woocommerce 或 braintree 下用于查找信用卡单选按钮或 paypal 支付单选按钮的任何 Hook 均已检查付款。
但是我知道我们可以在付款成功后检测到用于特定订单的网关,但我想要在结帐页面完成付款之前选择的网关信息。有什么帮助吗?
最佳答案
您可以在结帐页面上使用一些基本的 JavaScript 检测所选的付款方式,并通过挂接到 woocommerce_checkout_update_order_review 操作使用 PHP 运行您的自定义代码。
首先, 您还应该将 JS 代码放在结帐页面、结帐模板或主题的页眉/页脚中,这样您就可以检测到用户何时更改了付款方式选项并在之后运行您自己的代码。
JS代码:
jQuery(document).ready( function() {
jQuery( "#payment_method_bacs" ).on( "click", function() {
jQuery( 'body' ).trigger( 'update_checkout' );
});
jQuery( "#payment_method_paypal" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_stripe" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
});
请注意,对于您激活的每种付款方式,您都应该添加“点击”事件。它为您提供了在触发自定义代码时进行微调的选项。 为防止点击事件只运行一次,您应该在第一个 JS 代码下方添加下一个 JS 代码块。
jQuery( document ).ajaxStop(function() {
jQuery( "#payment_method_bacs" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_paypal" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_stripe" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
});
它只是在ajax 之后触发的相同代码。 在两个 JS 代码块中添加您实际使用的支付选项。
之后,您将 Hook 的自定义 PHP 代码放入结帐中,如下所示:
if ( ! function_exists( 'name_of_your_function' ) ) :
function name_of_your_function( $posted_data) {
// Your code goes here
}
endif;
add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
这段代码可以放在functions.php中。
这是完整的 PHP 代码,用于检测并在结帐页面上选择特定支付选项时运行:
function name_of_your_function( $posted_data) {
global $woocommerce;
// Parsing posted data on checkout
$post = array();
$vars = explode('&', $posted_data);
foreach ($vars as $k => $value){
$v = explode('=', urldecode($value));
$post[$v[0]] = $v[1];
}
// Here we collect payment method
$payment_method = $post['payment_method'];
// Run code custom code for each specific payment option selected
if ($payment_method == "paypal") {
// Your code goes here
}
elseif ($payment_method == "bacs") {
// Your code goes here
}
elseif ($payment_method == "stripe") {
// Your code goes here
}
}
add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
希望对您有所帮助! 这是在结帐页面上运行所有自定义逻辑的非常强大的选项!
关于php - 结帐页面中的 Woocommerce 付款方式检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42930063/