fsBuilds: Offloading WooCommerce Checkout & Subscriptions to FastSpring (Video)

Braden Steel
Braden Steel • Senior Product Marketing Manager
February 7th, 2024
Estimated read time: 3 minutes, 35 seconds

fsBuilds features developer-built projects showing step-by-step examples, code snippets, and advice on how to approach building with FastSpring. The goal of this series is to not only help you build with FastSpring, but also to inspire you with new and unique ways to leverage FastSpring’s systems to best serve your company. As always, our support and sales engineering specialists are available to help if you need assistance along the way.

Offload the Complexities of Payments, Subscriptions, and Subscription Management to FastSpring

Job to be done: You want to use WooCommerce and WordPress as a CMS, but want to leverage a Merchant of Record to manage payments, subscriptions, and subscription management.

For this entry, we’re featuring a build by Topher DeRosia showing how you can easily use FastSpring’s javascript library in combination with FastSpring’s webhooks to both activate subscriptions when a purchase is made, or disable subscription access when a payment fails while still using WooCommerce as your CMS.

Resources

Interested in trying the build yourself? Here’s an example of how you can get started.

Add a Subscription to Cart

PHP & Javascript
<?php
/**
 * Subscription Product Add to Cart
 *
 * @author  Prospress
 * @package WooCommerce-Subscriptions/Templates
 * @version 1.0.0 - Migrated from WooCommerce Subscriptions v2.6.0
 */

defined( 'ABSPATH' ) || exit;

global $product;

// Bail if the product isn't purchasable and that's not because it's limited.
if ( ! $product->is_purchasable() && ( ! is_user_logged_in() || 'no' === wcs_get_product_limitation( $product ) ) ) {
	return;
}

$user_id = get_current_user_id();

echo wp_kses_post( wc_get_stock_html( $product ) );

if ( $product->is_in_stock() ) : ?>

	<?php do_action( 'woocommerce_before_add_to_cart_form' ); ?>

    <script>
        var QueryString = (function () {
        // This function is anonymous, is executed immediately and
        // the return value is assigned to QueryString!
        var query_string = {};
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            // If first entry with this name
            if (typeof query_string[pair[0]] === "undefined") {
                query_string[pair[0]] = decodeURIComponent(pair[1]);
                // If second entry with this name
            } else if (typeof query_string[pair[0]] === "string") {
                var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
                query_string[pair[0]] = arr;
                // If third or later entry with this name
            } else {
                query_string[pair[0]].push(decodeURIComponent(pair[1]));
            }
        }
        return query_string;
        })();
    </script>
    <script>
        jQuery(document).ready(function () {
        var s = {};

        if (QueryString.product) {
            s = {
              products: [
                  {
                    path: QueryString.product,
                    quantity: 1,
                  },
              ],
            };
        }

        if (QueryString.email && QueryString.fname && QueryString.lname) {
            s.paymentContact = {};
            s.paymentContact.email = QueryString.email;
            s.paymentContact.firstName = QueryString.fname;
            s.paymentContact.lastName = QueryString.lname;
        }

        if (QueryString.coupon) {
            s.coupon = QueryString.coupon;
        }

        if (s) fastspring.builder.push(s);
        });
    </script>

    <!--
        Initialize the Store Builder Library
    -->
    <script
        id="fsc-api"
        src="https://sbl.onfastspring.com/sbl/0.9.2/fastspring-builder.min.js"
        type="text/javascript"
        data-storefront="mediaforge.test.onfastspring.com/popup-mediaforge">
    </script>

    <!--
        To add a product to the purchase session we need to define the data-fsc-item-path-value
        with the product path and also define the data-fsc-action where we first Add this item to the
        session and then initiate Checkout
    -->
    <button data-fsc-item-path-value='<?php echo esc_attr( $product->get_slug() ); ?>' data-fsc-action="Add, Checkout" >
        Subscribe Now With FastSpring
    </button>

	<?php do_action( 'woocommerce_after_add_to_cart_form' ); ?>

<?php endif; ?>
Expand

Subscription Creation via FastSpring Webhook

PHP
<?php
/**
 * Plugin Name: WooCommerce Subscription Creation
 * Description: Creation of a subscription from a webhook hit from FastSpring
 * Author: Topher
 * Version: 1.0
 * License: GPL2+
 * License URI: https://www.gnu.org/licenses/gpl-2.0.txt
 */

if (!function_exists( 'write_log' ) ) {

    function write_log( $log ) {
        if ( true === WP_DEBUG ) {
            if ( is_array( $log ) || is_object( $log ) ) {
                error_log( print_r( $log, true ) );
            } else {
                error_log( $log );
            }
        }
    }
}


function fs_create_subscription() {

	$json = file_get_contents('php://input');
	$object = json_decode($json);

	write_log( 'START TOPHER LOG' );
	write_log( 'PAYLOAD: ' . print_r( $object, true ) );
	write_log( 'END TOPHER LOG' );

}
add_action( 'wp', 'fs_create_subscription' );
Expand

Developer Documentation

If you have another use case you want to explore, speak directly with a solution engineer by signing up for a demo here.

Braden Steel

Braden Steel

Braden is the Senior Product Marketing Manager for FastSpring. When he's not bringing new products to market, he spends his time writing fantasy novels.

Try FastSpring

Get a free account and see why FastSpring is the ecommerce partner of choice for software providers around the world. Try our full-service ecommerce solution today to unlock revenue growth for your online company.