Integrating advanced subscription features in WooCommerce
Challenge: enhancing user engagement and loyalty in subscription-based eCommerce.
Solution: implementing a token reward system with WooToken plugin
Welcome to our series of posts “WooCode”, where we delve into the world of WooCommerce implementation tricks and tips. In this series, we’re committed to showcasing a variety of innovative techniques and practical solutions to enhance your WooCommerce experience.
In the e-commerce universe, subscriptions are the stars that keep shining. They offer customers a hassle-free, continuous service or product delivery, and for businesses, they provide a predictable and steady revenue stream. Whether it’s about delivering gourmet coffee beans to doorsteps every month or providing ongoing access to exclusive digital content, subscriptions are reshaping consumer habits and expectations.
Exploring Woocommerce Subscriptions Plugin
WooCommerce, the popular e-commerce platform for WordPress, has adapted to this trend with the Woo Subscriptions plugin. An important aspect to highlight about Woo Subscriptions is that it is developed and maintained directly by the WooCommerce Team. This ensures a level of reliability and compatibility that is essential for developers.
Key Features of Woo Subscriptions
Flexible Billing Schedules: Customize billing cycles to fit the needs of your product or service, whether that’s daily, weekly, monthly, or annually.
Subscription Management: Subscribers can manage their own plans, upgrading, downgrading, or pausing their subscriptions as needed, giving them control and flexibility.
Automated Reminders: The plugin sends automatic emails for renewals, payments, and subscription expirations, keeping both you and your customers informed.
Variable Subscriptions: Offer different subscription levels or types, allowing customers to choose the option that best suits their needs.
Integration with Payment Gateways: Seamlessly works with a variety of payment gateways, ensuring secure and reliable transaction processing.
Handling Failed Payments: Woo Subscriptions is designed to automatically rebill on failed subscription payments, which is crucial for maintaining consistent revenue.
In-Depth Reporting: Plugin comes with detailed reporting capabilities, allowing store owners to track recurring revenue, the number of active subscribers, and other critical metrics.
Step-by-Step guide to setting up subscription payments in Woocommerce
Implementing subscription payments in your WooCommerce store is a straightforward process with the Woo Subscriptions plugin. This section provides a simple guide to get you started and highlights the ease and advantages of incorporating subscription payments into your e-commerce strategy.
Install and Activate the Plugin: Begin by installing the Woo Subscriptions plugin. Navigate to your WordPress dashboard, go to Plugins > Add New, search for Woo Subscriptions, and install it. Once installed, activate the plugin.
Create Subscription Products: In your WooCommerce dashboard, go to Products > Add New. Here, you can create new subscription products or convert existing products into subscriptions. Set the product type to ‘Subscription’ and configure the subscription options, like billing interval, period, and sign-up fee, if any.
Configure Payment Methods: Ensure that your chosen payment gateways support recurring payments. Woo Subscriptions integrates with multiple gateways, allowing secure transactions. Set these up in WooCommerce settings by configuring API keys for your payment gateway.
Manage Subscription Settings: Customize the subscription settings according to your business model. This includes setting up renewal reminders, managing subscriber emails, and configuring cancellation settings.
Test Your Subscription Process: Before going live, conduct thorough testing. Create a subscription product, go through the checkout process, and ensure that the billing cycle works as expected. Once testing is successful, transition to production mode.
Implementing User Token Balance
In the WooToken Points for Subscriptions plugin, we’ve integrated a feature that allows for the rewarding and management of user token balances. This functionality provides a practical application of customizing WooCommerce Subscriptions, enhancing the user experience by adding a layer of engagement through token accumulation.
Awarding Tokens for Subscription Payments
When a user completes a payment for a specific subscription product, the add_tokens_for_specific_subscription_product function is triggered. This function checks the product title in the latest order against a predefined product (in our case, “Monthly Subscription 19.99”). If the product matches, it proceeds to calculate the number of tokens to be awarded.
function add_tokens_for_specific_subscription_product( $subscription ) {
$product_title_to_check = "Monthly Subscription 19.99";
$last_order = $subscription->get_last_order();
$order = wc_get_order( $last_order );
$product_line_total = 0;
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
if ( $product && $product->get_name() == $product_title_to_check ) {
$product_line_total = $item->get_total();
break;
}
}
if ( $product_line_total > 0 ) {
// calculate tokens and apply to user balance
}
}
add_action( 'woocommerce_subscription_payment_complete', 'add_tokens_for_specific_subscription_product' );
Token calculation
The token calculation is flexible and can be tailored to different pricing strategies. For instance, the current setup awards 30 tokens for a product line total of $19.99, but also includes a rate-based calculation for different amounts (1.5 tokens per dollar).
Once the token amount is determined, the function retrieves the user’s current token balance from their user metadata, updates this balance by adding the newly awarded tokens, and then saves this new balance back to the user’s metadata.
// calculate tokens and apply to user balance
if ( $product_line_total > 0 ) {
$user_id = $subscription->get_user_id();
$tokens_to_award = ($product_line_total == 19.99) ? 30 : $product_line_total * 1.5;
$current_balance = get_user_meta( $user_id, 'user_token_balance', true );
$new_balance = (empty($current_balance) ? 0 : $current_balance) + $tokens_to_award;
update_user_meta( $user_id, 'user_token_balance', $new_balance );
}
Transaction log
For transparency and record-keeping, each token transaction is logged using the ct_log_token_transaction function. This log includes details like the user ID, the number of tokens added or deducted, and the reason for the transaction.
// Function to log token transactions
function ct_log_token_transaction( $user_id, $amount, $reason = '' ) {
$logger = wc_get_logger();
$context = array( 'source' => 'ct-token-transactions' );
$user_info = get_userdata( $user_id );
$log_message = sprintf(
'Token Transaction for user %s (ID: %d): Amount: %d, Reason: %s',
$user_info->user_login,
$user_id,
$amount,
$reason
);
$logger->info( $log_message, $context );
}
Admin Form for Deducting Tokens
The admin form provides a straightforward way to deduct tokens from a user’s account. It includes fields to select a user, specify the amount of tokens to deduct, and a field for the reason for deduction.
// Handle form submission
if ( isset( $_POST['ct_deduct_tokens_nonce'] ) && wp_verify_nonce( $_POST['ct_deduct_tokens_nonce'], 'ct_deduct_tokens' ) ) {
$user_id = intval( $_POST['user_id'] );
$amount = intval( $_POST['amount'] );
$reason = sanitize_text_field( $_POST['reason'] ) ? sanitize_text_field( $_POST['reason'] ) : 'Admin deduction';
if ($amount <= 0) {
wp_die("Please enter a positive amount for deduction.");
}
if ( $user_id && $amount ) {
$deducted = ct_deduct_tokens( $user_id, $amount, $reason );
if ( $deducted ) {
$user_info = get_userdata($user_id);
$user_display_name = $user_info->first_name . ' ' . $user_info->last_name;
echo '<div class="notice notice-success is-dismissible"><p>Tokens deducted successfully from ' . $user_display_name . '! Amount deducted: ' . $amount . ' tokens.</p></div>';
$form_submitted = true;
} else {
echo '<div class="notice notice-error is-dismissible"><p>Failed to deduct tokens. Maybe the user doesn’t have enough tokens.</p></div>';
$form_submitted = true;
}
} else {
echo '<div class="notice notice-error is-dismissible"><p>Error.</p></div>';
$form_submitted = true;
}
}
Displaying Member Card on User Account Page
On the user account page, the plugin adds a member card section, enhancing the visibility of the token system for the user. This feature is implemented via the ct_display_user_token_balance function.
function ct_display_user_token_balance( $subscription ) {
$user_id = $subscription->get_user_id();
$token_balance = get_user_meta( $user_id, 'user_token_balance', true );
$rebill_date = $subscription->get_date( 'next_payment' );
echo '<div class="card">';
echo '<div class="card-header">Member Card</div>';
echo '<div class="card-content">';
echo '<p>Client\'s Name: ' . esc_html( get_userdata( $user_id )->display_name ) . '</p>';
echo '<p>Amount of Tokens: ' . esc_html( $token_balance ) . '</p>';
echo '<p>Member Number: ' . esc_html( $user_id ) . '</p>';
echo '<p>Rebill Date: ' . esc_html( date_i18n( wc_date_format(), strtotime( $rebill_date ) ) ) . '</p>';
echo '</div></div>';
}
add_action( 'woocommerce_subscription_details_after_subscription_table', 'ct_display_user_token_balance' );
Summary
The WooToken Points for Subscriptions plugin can be applied to a variety of real-world scenarios in eCommerce, offering practical and engaging solutions to enhance customer loyalty and experience. Here are a few examples:
Subscription Box Services: Reward customers with tokens for each subscription renewal, redeemable for special items or discounts.
Online Learning Platforms: Use tokens to grant access to additional courses, content, or discounts on future subscriptions.
Health and Wellness Programs: Offer tokens for subscription renewals, redeemable for exclusive workshops or health products.
For developers interested in exploring the code, contributing, or implementing this plugin, the full source code is available on GitHub : https://github.com/createit-dev/326-WooToken-Points-for-Subscriptions
If you are looking for Woocommerce developers or ecommerce optimization services feel free to contact us!