Stripe and S2Member – Update Subscription Metadata

S2Member User Profile Fields

Oddly, S2Member does not by default directly expose Subscription beginning and end dates, although it does expose a user profile field for setting the latter if desired. Site operators will like to be able to view that data, whether in profile pages or as output in custom lists and tables.

/* 
 * GET STRIPE EVENTS VIA WEBHOOK
 * AND MODIFY USER DATA (SUBSCRIPTION DETAILS, both S2Member and related custom fields) 
 */
add_action('init', 'ckm_event_listener' );

function ckm_event_listener() {
  
  if( isset( $_GET['listener'] ) && $_GET['listener'] == 'ckm_stripe' ) { 
    
    require_once( __DIR__ .  '/stripe/init.php' );
                //keeping actually used keys private
    /**** IN LIVE MODE ****/
    \Stripe\Stripe::setApiKey('sk_live_{key}');
    /**** TEST MODE *******		*/
    //\Stripe\Stripe::setApiKey('sk_test_{key}');

    // retrieve the request's body and parse it as JSON
    $body = @file_get_contents('php://input');

    // grab the event information
    $event_json = json_decode($body);

    // this will be used to retrieve the event from Stripe
    $event_id = $event_json->id;
     
    if( isset( $event_json->id ) ) { 
    
      try { 
      
        // to verify this is a real event, we re-retrieve the event from Stripe 
        $event = \Stripe\Event::retrieve($event_id);
        $event_data = $event->data->object;		 
        
        // SUBSCRIPTION UPDATED (INCLUDING CANCELED? )
        if ( $event->type == 'customer.subscription.updated' || $event->type == 'customer.subscription.created' ) {

          $stripe_customer = \Stripe\Customer::retrieve( $event_data->customer ); 
          $customer_email = $stripe_customer->email ;  
          $user_id = get_user_by( 'email', $customer_email )->ID ; 
          $stripe_sub_id = $event_data->id ; //subscription id  
          
          if ( ! $user_id ) {
            
            $user_id = get_users( array('meta_key' => 'wp_s2member_subscr_id', 'meta_value' => $stripe_sub_id, 'fields' => 'ids' ) )[0] ;
            
          }
          
          $period_end_added = update_user_meta( $user_id, 'wp_s2member_auto_eot_time', $event_data->current_period_end ) ;
          $period_start = date( 'Y/m/d', $event_data->current_period_start ) ;
          $period_end = date( 'Y/m/d', $event_data->current_period_end ) ;
          $period_start_date_added = update_user_meta( $user_id, 'current_subscription_start_date', $period_start ) ;
          $period_end_date_added = update_user_meta( $user_id, 'current_subscription_end_date', $period_end ) ;
            
          } 
          
        } 
      
      catch ( Exception $e ) {
        custom_logs('Unknown error finding event by ID');
      }
      
    }
    
  } 
  
}

 

 

Leave a Reply