問題描述
在選擇付款方式(信用卡)時,如何在總金額中增加一個百分比?
How can I add a percentage to the total amount when choosing a payment (credit card)?
例如:如果客戶貨到付款,那么基價,如果我選擇在線支付,那么我收取的百分比加到總金額中?
For example: If the customer pays for cash on delivery, then the base price, and if I chose online payment, then the percentage charged by me is added to the total amount?
貨到付款的網關ID規定:cod在線支付網關ID設置:tinkoff
Gateway ID for cash payment on delivery is set out: cod Gateway ID for online payment is set out: tinkoff
add_action( 'woocommerce_after_calculate_totals', 'custom_fee_for_tinkoff' );
function custom_fee_for_tinkoff( $cart ) {
if ( is_checkout() || defined('WOOCOMMERCE_CHECKOUT') ) {
$payment_method = WC()->session->get( 'chosen_payment_method' );
if ($payment_method == 'tinkoff') {
$percentage = 0.025;
$surcharge = ( $cart->cart_contents_total + $cart->tax_total ) * $percentage;
$cart->add_fee( 'Комиссия банка', $surcharge, true, '' );
}
else { return; }
}
}
有問題的圖片
推薦答案
嘗試使用以下重新訪問的代碼來代替它:
Try the following revisited code instead that should do the trick:
// Add a custom fee based o cart subtotal
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_for_tinkoff', 20, 1 );
function custom_fee_for_tinkoff ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return; // Only checkout page
$payment_method = WC()->session->get( 'chosen_payment_method' );
if ( 'tinkoff' == $payment_method ) {
$surcharge = $cart->subtotal * 0.025;
$cart->add_fee( 'Комиссия банка', $surcharge, true );
}
}
// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return; // Only checkout page
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'input[name="payment_method"]', function(){
$(document.body).trigger('update_checkout');
});
});
</script>
<?php
}
代碼位于活動子主題(或活動主題)的 function.php 文件中.經測試有效.
Code goes in function.php file of your active child theme (or active theme). Tested and works.
這篇關于在 Woocommerce 中為特定支付網關添加自定義費用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!