bookmark_borderCancel a Stripe subscription after n payments

The Stripe API doesn’t allow you to set the total number of recurrences of a payment or an end date when creating the subscription but it is possible to cancel the subscription via the gform_post_add_subscription_payment hook which runs after a payment is recorded.

add_action( 'gform_post_add_subscription_payment', function ( $entry ) {
    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 ) ) {
            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
                $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 ) );
} );

The code snippet would go in your theme functions.php file.

The gform_post_add_subscription_payment is an action hook which is called after the Stripe webhook notifies your site that a payment has been made for the subscription and the add-on has recorded the transaction and added a note to the entry.

Because it runs for all forms with a subscription feed we need to tell it only to run for the correct feed, we do this by specifying the feed names in the array on this line:

$feed_names = array( 'feed name one', 'feed name two' );

You would then update the following line with the number of payments you want to allow:

if ( $count == 3 ) {

If the count retrieved from the database query matches the value you specify the cancel method will be called which will notify Stripe that the subscription for that customer should be cancelled.

Stripe will then notify your site when that action has been completed and the status on the entry will update to cancelled and a note will be added indicating the date it was cancelled.