我正在尝试通过在表单提交时执行的脚本以编程方式向 woocommerce 购物车添加费用。据我所知,我认为我无法使用挂钩,因为我需要在提交页面上的表单时应用自定义费用(自定义 API 集成)。
我尝试在脚本中执行以下操作:
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){
$valid = false;
if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
return;
}
if (isset($_POST['coupon_code'])) {
$code = $_POST['coupon_code'];
$coupon = new WC_Coupon($code);
if($coupon->get_amount() != null){
$valid == true;
}
//if not then lets check to see if its a giftcard.
if($valid == false){
$api_login="xxxxxx";
$api_password="xxxxxx";
$url = "https://xxxxxx.com/xxxxx/xxxxx.svc";
$client = new SoapClient( $url . "?singleWsdl",
array(
"location" => $url,
"login" => $api_login,
"password" => $api_password,
"trace" => 1
)
);
$request = new StdClass();
$request->bonId = $code;
$request->bonType = 'GiftCard';
// call the correct database
$request->context = new StdClass();
$request->context->DatabaseId = 'xxxxx';
try {
$resu = $client->GetBonAvailableAmount($request);
if (isset($resu->GetBonAvailableAmountResult->Amount)) {
$amount = $resu->GetBonAvailableAmountResult->Amount;
$cart->add_fee('xxxxxx Gift Card ', floatval('-'.$amount * 0.83333), false, '' );
} else {
$response['status'] = 'error';
$response['message'] = 'Gift card not recognized.';
}
} catch (Exception $e) {
}
}
}
}
我可以看到,当我echo
使用购物车对象时,有一个fee
对象包含所有正确的数据。
似乎购物车或总计没有更新,如果我刷新页面,它们仍然没有反映我预期的值。
我搜索了几乎所有 Stack Overflow 帖子,但似乎找不到任何解决问题的方法。
有什么我在这里想念的吗?