Auto Payments with Manual WooCommerce Subscriptions

WooCommerce Subscriptions is great way to handle recurring subscriptions on WordPress. You can create a WooCommerce Subscription product out of the box, which allows your customers to purchase a subscription with automatic payments.

If you want more control you can use WooCommerce like an invoicing system by manually creating subscriptions on the backend and sending out invoices. Putting each customer on a unique subscription gives you full control to update and modify their subscription plan according to their unique plan.

One problem, manually creating subscriptions, can be setup with manual payments. In order to setup automatic payments, some extra coding is required. The following is what I use to enabled auto payments from manually added subscriptions. This code will run after the customer pays their first invoice and changes their subscription to automatic payments with Stripe.

// After payment received, connect up the Stripe info into the subscription.
function anchor_woocommerce_payment_complete( $order_id ) {

    $customer_id = get_field('_customer_user', $order_id);
    $payment_tokens = WC_Payment_Tokens::get_customer_tokens( $customer_id );

    foreach ( $payment_tokens as $payment_token ) {
        $token_id = $payment_token->get_token();
    }

    $payment_cus_id = get_field('_stripe_customer_id', "user_" . $customer_id);
    $payment_card_id = $token_id;

    // Find parent subscription id
    if (wcs_order_contains_subscription($order_id)) {
        $subscription = wcs_get_subscriptions_for_order( $order_id );
        $subscription_id = key($subscription);
    } else {
        $subscription_id = get_field('_subscription_renewal', $order_id);
    }

    update_post_meta( $subscription_id, '_stripe_customer_id', $payment_cus_id );
    update_post_meta( $subscription_id, '_stripe_card_id', $payment_card_id  );
    update_post_meta( $subscription_id, '_requires_manual_renewal', "false" );
    update_post_meta( $subscription_id, '_payment_method', "stripe" );
    update_post_meta( $subscription_id, '_payment_method_title', "Credit card" );

}
add_action( 'woocommerce_payment_complete', 'anchor_woocommerce_payment_complete' );