Set user role after paying monthly subscription on Memberpres

484 Views Asked by At

I'm building a website where users pay a monthly subscription to access different courses. I've got Memberpress setup to handle user registration and the monthly subscription.

When the user selects a course, I call a function the set the user role. This way I disable the other courses for the rest of the month.

After a month passes, the user pays the monthly fee again, and can select a new course. What would be the best way to capture that event, so I can add the set role function to it?

After looking around a bit I found two solutions, but I'm not sure which one would work, and also how to test it without waiting for a month to get charged.

Hook 1:

function mepr_capture_new_recurring_sub($event) {
  $subscription = $event->get_data();
  $user = $subscription->user();
  
    $user_ID = get_current_user_id(); 
    $theUser = new WP_User($user_ID);
    $theUser->set_role( 'subscriber' );
}
add_action('mepr-event-subscription-created', 'mepr_capture_new_recurring_sub');

Hook 2:

function catch_first_payment_after_trial($event) {
  $transaction = $event->get_data();
  $subscription = $transaction->subscription();
  $is_first_real_payment = false;

  if($subscription !== false) {
    if($subscription->trial && $subscription->trial_amount <= 0.00 && $subscription->txn_count == 1) {
      $is_first_real_payment = true;
    }
    elseif($subscription->trial && $subscription->trial_amount > 0.00 && $subscription->txn_count == 2) {
      $is_first_real_payment = true;
    }
  }

  if($is_first_real_payment) {
    $user_ID = get_current_user_id(); 
    $theUser = new WP_User($user_ID);
    $theUser->set_role( 'subscriber' );
  }
}
add_action('mepr-event-transaction-completed', 'catch_first_payment_after_trial');

Thanks

1

There are 1 best solutions below

0
On

Not sure if you still need this. But to test, you can add memberpress transactions manually. On the transactions page at the very top there is a button called add, use that.