我们希望通过webhook创建退款,但退款金额似乎是退款金额的三倍。
以下是我们对代码的处理方式,仅触发一次。
$order_id = (isset($_REQUEST["order_id"]) && strlen($_REQUEST["order_id"]) > 0) ? intval($_REQUEST["order_id"]) : false;
$amount = (isset($_REQUEST["amount"]) && strlen($_REQUEST["amount"]) > 0) ? floatval($_REQUEST["amount"]) : false;
$reason = (isset($_REQUEST["reason"]) && strlen($_REQUEST["reason"]) > 0) ? $_REQUEST["reason"] : false;
if ($order_id) {
$order = wc_get_order($order_id);
if ($order->get_remaining_refund_amount() >= $amount) {
$refund = wc_create_refund(array(
'amount' => $amount,
'reason' => $reason,
'order_id' => $order_id,
'refund_payment' => true
));
if (is_wp_error($refund)) {
if ($refund->get_error_message() == 'Invalid refund amount.') {
echo 'Refund requested exceeds remaining order balance of ' . $order->get_formatted_order_total();
} else {
echo $refund->get_error_message();
}
} else {
echo $refund->get_id();
}
} else {
echo 'Refund requested exceeds remaining order balance of ' . $order->get_formatted_order_total();
}
}
但正如您从下面的屏幕截图中看到的那样,似乎将退款值增加了三倍但不确定原因
任何人都可以解释为什么会发生这种情况。
请求作为带有唯一密钥标识符的post http请求进入。例如
https://example.com/process-refunds/?key=ff5f61b5a9d6ff2a5d7fb9fc815113d4&order_id=1234&amount=100&reason=Testing
答案 0 :(得分:1)
检查条件以获取最大退款金额。并且通过使用静态变量确保您的代码仅运行一次。
static $result;
$order = wc_get_order($order_id);
$max_refund = wc_format_decimal($order->get_total() - $order->get_total_refunded());
if (!$max_refund) {
return;
}
if($result == null){
// Create the refund object
$refund = wc_create_refund(array('amount' => $max_refund, 'reason' => __('Order Fully Refunded', 'woocommerce'), 'order_id' => $order_id, 'line_items' => array()));
wc_delete_shop_order_transients($order_id);
}
$result = 'code-already-run';
希望它能对您有所帮助。
答案 1 :(得分:1)
尝试在init
钩子(添加到主题的'functions.php')中调用该函数,该函数对我来说很好。
add_action( 'init', 'wc_manual_refund' );
function wc_manual_refund()
{
$order_id = (isset($_REQUEST["order_id"]) && strlen($_REQUEST["order_id"]) > 0) ? intval($_REQUEST["order_id"]) : false;
$amount = (isset($_REQUEST["amount"]) && strlen($_REQUEST["amount"]) > 0) ? floatval($_REQUEST["amount"]) : false;
$reason = (isset($_REQUEST["reason"]) && strlen($_REQUEST["reason"]) > 0) ? $_REQUEST["reason"] : false;
if ($order_id) {
$order = wc_get_order($order_id);
if ($order->get_remaining_refund_amount() >= $amount) {
$refund = wc_create_refund(array(
'amount' => $amount,
'reason' => $reason,
'order_id' => $order_id,
'refund_payment' => true
));
if (is_wp_error($refund)) {
if ($refund->get_error_message() == 'Invalid refund amount.') {
echo 'Refund requested exceeds remaining order balance of ' . $order->get_formatted_order_total();
} else {
echo $refund->get_error_message();
}
} else {
echo $refund->get_id();
}
} else {
echo 'Refund requested exceeds remaining order balance of ' . $order->get_formatted_order_total();
}
}
}