当帐户状态为“暂停”时如何使用 Woocommerce 订阅仍然生成发票

问题描述 投票:0回答:1

我正在尝试找到一种方法,即使在下订单且 WooCommerce 订阅处于保留状态时也可以继续生成发票。我遇到的问题是,一旦付款失败后订单被搁置,WooCommerce 将停止生成发票。有时,我们的团队没有注意到这些帐户,并且可能几个月都没有生成发票,而客户却继续收到我们的产品。由于我们的订阅产品是实体产品,而不是数字产品,因此我们需要 WooCommerce 每月继续生成发票并发送电子邮件,即使帐户处于暂停状态也是如此。

我正在尝试使用此代码即使在帐户处于暂停状态时也能生成发票。

// Generate invoice even if the subscription is on-hold
add_action('woocommerce_scheduled_subscription_payment', 
'generate_invoice_for_on_hold_subscription', 10, 2);

function generate_invoice_for_on_hold_subscription($amount_to_charge, $subscription) {
// Check if the subscription is on-hold
if ($subscription->has_status('on-hold')) {
    // Get the order related to the subscription
    $order = wc_create_order(array(
        'customer_id' => $subscription->get_customer_id()
    ));

    // Add subscription items to the order
    foreach ($subscription->get_items() as $item_id => $item) {
        $product_id = $item->get_product_id();
        $quantity = $item->get_quantity();
        $order->add_product(wc_get_product($product_id), $quantity);
    }

    // Set billing information
    $order->set_address($subscription->get_address('billing'), 'billing');

    // Create invoice by changing the order status to pending
    $order->update_status('pending');
    
    // Send the invoice email to the customer
    WC()->mailer()->get_emails()['WC_Email_Customer_Invoice']->trigger($order->get_id());
}
}

代码说明:

  • 查看订阅状态:该功能检查订阅状态是否为暂停状态。如果为 true,它将继续生成订单和发票。
  • 生成发票:它创建一个新订单并向其中添加订阅项目。订单状态设置为待生成发票。
  • 发送发票电子邮件:它会触发 WooCommerce 客户发票电子邮件将发票发送给客户。

任何人都可以确认此代码是否可以在帐户处于暂停状态时继续生成发票吗?任何帮助将不胜感激。

woocommerce woocommerce-subscriptions
1个回答
0
投票

请注意,挂钩在

woocommerce_scheduled_subscription_payment
操作挂钩 中的函数仅具有
$subscription_id
作为唯一参数。
但不是
$amount_to_charge
$subscription

您的代码中有一些错误,请尝试以下操作:

// Generate invoice even if the subscription is on-hold
add_action('woocommerce_scheduled_subscription_payment', 
'generate_invoice_for_on_hold_subscription', 10, 1);
function generate_invoice_for_on_hold_subscription( $subscription_id ) {
     // Get the WC_Subscription object
    $subscription = new WC_Subscription( $subscription_id );

    // Check if the subscription status is "on-hold"
    if ( $subscription->has_status( 'on-hold' ) ) {
        $orders_ids   = $subscription->get_related_orders(); // get related order
        $order_id     = absint( current( $orders_ids ) ); // Get current order ID
        $order        = wc_get_order( $order_id ); // Get the WC_Order object

        if ( is_a( $order, 'WC_Order' ) ) {
            // Send the invoice email to the customer
            WC()->mailer()->get_emails()['WC_Email_Customer_Invoice']->trigger( $order->get_id() );
        }
    }
}

应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.