Cancel a Stripe Subscription After a Specified Number of Payments

Cancel a Stripe Subscription After a Specified Number of Payments

The Stripe API doesn』t allow you to set the total number of recurrences of a payment 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.
The Stripe API now supports specifying an end date for when subscriptions should automatically cancel, this can be set using the gform_stripe_subscription_params_pre_update_customer filter.
Note: If you delete the entry associated to the subscription this snippet will not work.
123456789101112131415161718192021add_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 ) );            }        }    }} );
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:
1$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:
1if ( $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 canceled.
Stripe will then notify your site when that action has been completed and the status on the entry will update to canceled and a note will be added indicating the date it was canceled.

發表回覆

您的電子郵箱地址不會被公開。 必填項已用 * 標註