Skip to content

Limit Stripe Subscriptions to a Specified Number of Payments

Chris Eggleston 1 min read

Symptoms

Need to create a payment plan of equal installments for a limited number of transactions using the Gravity Forms Stripe Add-On. Or you would like to cancel a Stripe subscription after a specified number of payments.

The Stripe API doesn’t allow you to set the total number of recurring payments when creating the subscription and as a result you will not see an option for that when setting up your Stripe feed.

How To Fix It

The geniuses over at Gravity Forms have already put together a simple solution to this problem. You can read more about it here: Cancel a Stripe Subscription After a Specific Number of Payments.

Basically all you need to do is add the code snippet below to your themes functions.php file or a functionality plugin like WPCodeBox (recommended) and modify it as explained in the snippet.

gf-limit-payments.phpGist by chriseggGitHub
<?php

//Code provided by Gravity Forms here: https://rocketgenius.pxf.io/limit-payments
//Start copying below this line...

add_action( 'gform_post_add_subscription_payment', function ( $entry ) {
    gf_stripe()->log_debug( "Running..." );
 
    if ( rgar( $entry, 'payment_status' ) == 'Active' ) {
        $feed       = gf_stripe()->get_payment_feed( $entry );
        $feed_name  = rgars( $feed, 'meta/feedName' );
        $feed_names = array( 'feed name one', 'feed name two' ); // update this line
 
        if ( in_array( $feed_name, $feed_names ) ) {
            gf_stripe()->log_debug( 'Feed: ' . $feed_name . 'Entry: ' . $entry['id'] );
 
            global $wpdb;
            $count = $wpdb->get_var( $wpdb->prepare( "SELECT count(id) FROM {$wpdb->prefix}gf_addon_payment_transaction WHERE lead_id=%d", $entry['id'] ) );
 
            if ( $count >= 3 ) { // Update this line to the Total number of payments including the first one.
                $result = gf_stripe()->cancel( $entry, $feed );
                gf_stripe()->log_debug( "gform_post_add_subscription_payment: Cancelling subscription (feed #{$feed['id']} - {$feed_name}) for entry #{$entry['id']}. Result: " . print_r( $result, 1 ) );
            }
        }
    }
} );

Need More Help?

If you still need help, use the chat or leave a comment below and we’ll get back to you.

Comments

Ask a question or leave a comment

Your email is never shown. For help with a specific form, share what you expected and what happened instead.