Woocommerce Subscription Pricing/Billing Schedule

Question

We are currently building a site using the Woocomerce Subscriptions plugin. When adding a product to the cart a customer inputs their information on the product page and it returns a calculated price for that order.

add_filter( 'woocommerce_add_cart_item_data', 'custom_add_to_cart_item_data', 20, 2 );
function custom_add_to_cart_item_data( $cart_item_data, $product_id ) {
 ...
 // Calculate total price based on input
 $totalPrice = calculateTotalPrice($product, $plan, $input);

 // Set calculated price to be the result of total price
 $cart_item_data['price_based_on_input'] = $totalPrice;
}

We then check if price_based_on_input is set and we update the price:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price_to_cart_item', 9999, 1);
function add_custom_price_to_cart_item( $cart ) {
    // WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    // Avoiding hook repetition
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item ) {
        // Check if price_based_on_input is set
        if( isset( $item['price_based_on_input'] ) ) {
            // Store price_based_on_input in a new variable
            $price = $item['price_based_on_input'];

            // Set the price of the item to the price_based_on_input
            $item['data']->set_price( $price );
        }
    }
}

What we need to be able to do is update the subscription price based on the user’s input as well as update the billing schedule which will be based on what the user has entered on the product page, through custom form fields. We currently calculate the price and the billing schedule in days.

The billing schedule would be different for each customer as they might have a schedule of being billed every 14 days and another customer might have a billing schedule of every 21 days. You can set this manually in the backend but it needs to be run automatically when the price is calculated.

Having referenced the documentation it looks like the two hooks that look usable for this are:

1. woocommerce_checkout_subscription_created - Triggered when a subscription is created after a customer purchases a subscription product or products.
2. subscriptions_created_for_order - Triggered when the subscriptions in an order are first created with the pending status. This occurs before payment has been made on an order and subscriptions are activated.

Where is the best place to implement the results of these calculations for the subscription? The price would need to apply to all future recurring payments on the subscription, the same goes for the calculated billing schedule.

0
zen_1991 8 months 2020-12-02T03:10:25-05:00 0 Answers 14 views 0

Leave an answer

Browse
Browse