Ejemplo n.º 1
0
/**
 *Process the login form
 *
 * @access      public
 * @since       1.0
 */
function rcp_process_login_form()
{
    if (!isset($_POST['rcp_action']) || 'login' != $_POST['rcp_action']) {
        return;
    }
    if (!isset($_POST['rcp_login_nonce']) || !wp_verify_nonce($_POST['rcp_login_nonce'], 'rcp-login-nonce')) {
        return;
    }
    // this returns the user ID and other info from the user name
    $user = get_user_by('login', $_POST['rcp_user_login']);
    do_action('rcp_before_form_errors', $_POST);
    if (!$user) {
        // if the user name doesn't exist
        rcp_errors()->add('empty_username', __('Invalid username', 'rcp'), 'login');
    }
    if (!isset($_POST['rcp_user_pass']) || $_POST['rcp_user_pass'] == '') {
        // if no password was entered
        rcp_errors()->add('empty_password', __('Please enter a password', 'rcp'), 'login');
    }
    if ($user) {
        // check the user's login with their password
        if (!wp_check_password($_POST['rcp_user_pass'], $user->user_pass, $user->ID)) {
            // if the password is incorrect for the specified user
            rcp_errors()->add('empty_password', __('Incorrect password', 'rcp'), 'login');
        }
    }
    if (function_exists('is_limit_login_ok') && !is_limit_login_ok()) {
        rcp_errors()->add('limit_login_failed', limit_login_error_msg(), 'login');
    }
    do_action('rcp_login_form_errors', $_POST);
    // retrieve all error messages
    $errors = rcp_errors()->get_error_messages();
    // only log the user in if there are no errors
    if (empty($errors)) {
        $remember = isset($_POST['rcp_user_remember']);
        $redirect = !empty($_POST['rcp_redirect']) ? $_POST['rcp_redirect'] : home_url();
        rcp_login_user_in($user->ID, $_POST['rcp_user_login'], $remember);
        // redirect the user back to the page they were previously on
        wp_redirect($redirect);
        exit;
    } else {
        if (function_exists('limit_login_failed')) {
            limit_login_failed($_POST['rcp_user_login']);
        }
    }
}
/**
 * Register a new user
 *
 * @access      public
 * @since       1.0
 */
function rcp_process_registration() {

  	if ( isset( $_POST["rcp_register_nonce"] ) && wp_verify_nonce( $_POST['rcp_register_nonce'], 'rcp-register-nonce' ) ) {

		global $rcp_options, $user_ID;

		$subscription_id = isset( $_POST['rcp_level'] ) ? absint( $_POST['rcp_level'] ) : false;
		$discount        = isset( $_POST['rcp_discount'] ) ? sanitize_text_field( $_POST['rcp_discount'] ) : '';
		$discount_valid  = false;
		$price           = number_format( (float) rcp_get_subscription_price( $subscription_id ), 2 );
		$price           = str_replace( ',', '', $price );
		$base_price      = $price; // Used for discount calculations later
		$expiration      = rcp_get_subscription_length( $subscription_id );
		$subscription    = rcp_get_subscription_details( $subscription_id );

		// get the selected payment method/gateway
		if( ! isset( $_POST['rcp_gateway'] ) ) {
			$gateway = 'paypal';
		} else {
			$gateway = sanitize_text_field( $_POST['rcp_gateway'] );
		}

		/***********************
		* validate the form
		***********************/

		do_action( 'rcp_before_form_errors', $_POST );

		$is_ajax   = isset( $_POST['rcp_ajax'] );

		$user_data = rcp_validate_user_data();

		if( ! $subscription_id ) {
			// no subscription level was chosen
			rcp_errors()->add( 'no_level', __( 'Please choose a subscription level', 'rcp' ), 'register' );
		}

		if( $subscription_id ) {

			if( $price == 0 && $expiration->duration > 0 && rcp_has_used_trial( $user_data['id'] ) ) {
				// this ensures that users only sign up for a free trial once
				rcp_errors()->add( 'free_trial_used', __( 'You may only sign up for a free trial once', 'rcp' ), 'register' );
			}
		}

		if( ! empty( $discount ) ) {

			if( rcp_validate_discount( $discount, $subscription_id ) ) {

				$discount_valid = true;

			} else {

				// the entered discount code is incorrect
				rcp_errors()->add( 'invalid_discount', __( 'The discount you entered is invalid', 'rcp' ), 'register' );

			}

			if( $discount_valid && $price > 0 ) {

				if( ! $user_data['need_new'] && rcp_user_has_used_discount( $user_data['id'] , $discount ) && apply_filters( 'rcp_discounts_once_per_user', true ) ) {

					$discount_valid = false;
					rcp_errors()->add( 'discount_already_used', __( 'You can only use the discount code once', 'rcp' ), 'register' );
				}

				if( $discount_valid ) {

					$discounts    = new RCP_Discounts();
					$discount_obj = $discounts->get_by( 'code', $discount );

					if( is_object( $discount_obj ) ) {
						// calculate the after-discount price
						$price = $discounts->calc_discounted_price( $base_price, $discount_obj->amount, $discount_obj->unit );
					}

				}
			
			}

		}

		if( $price == 0 && isset( $_POST['rcp_auto_renew'] ) ) {
			// since free subscriptions do not go through PayPal, they cannot be auto renewed
			rcp_errors()->add( 'invalid_auto_renew', __( 'Free subscriptions cannot be automatically renewed', 'rcp' ), 'register' );
		}

		// Validate extra fields in gateways with the 2.1+ gateway API
		if( ! has_action( 'rcp_gateway_' . $gateway ) && $price > 0 ) {
		
			$gateways    = new RCP_Payment_Gateways;
			$gateway_var = $gateways->get_gateway( $gateway );
			$gateway_obj = new $gateway_var['class'];
			$gateway_obj->validate_fields();
		}

		do_action( 'rcp_form_errors', $_POST );

		// retrieve all error messages, if any
		$errors = rcp_errors()->get_error_messages();

		if ( ! empty( $errors ) && $is_ajax ) {
			wp_send_json_error( array( 'success' => false, 'errors' => rcp_get_error_messages_html( 'register' ), 'nonce' => wp_create_nonce( 'rcp-register-nonce' ) ) );
		} elseif( $is_ajax ) {
			wp_send_json_success( array( 'success' => true ) );
		}

		// only create the user if there are no errors
		if( ! empty( $errors ) ) {
			return;
		}

		// deterime the expiration date of the user's subscription
		if( $expiration->duration > 0 ) {

			$member_expires = rcp_calc_member_expiration( $expiration );

		} else {

			$member_expires = 'none';

		}

		if( $user_data['need_new'] ) {

			$user_data['id'] = wp_insert_user( array(
					'user_login'		=> $user_data['login'],
					'user_pass'	 		=> $user_data['password'],
					'user_email'		=> $user_data['email'],
					'first_name'		=> $user_data['first_name'],
					'last_name'			=> $user_data['last_name'],
					'user_registered'	=> date( 'Y-m-d H:i:s' )
				)
			);
		}

		if( $user_data['id'] ) {

			if( ! rcp_is_active( $user_data['id'] ) ) {

				rcp_set_status( $user_data['id'], 'pending' );
	
			}

			// setup a unique key for this subscription
			$subscription_key = rcp_generate_subscription_key();
			update_user_meta( $user_data['id'], 'rcp_subscription_key', $subscription_key );
			update_user_meta( $user_data['id'], 'rcp_subscription_level', $subscription_id );

			rcp_set_expiration_date( $user_data['id'], $member_expires );

			// Set the user's role
			$role = ! empty( $subscription->role ) ? $subscription->role : 'subscriber';
			$user = new WP_User( $user_data['id'] );
			$user->add_role( apply_filters( 'rcp_default_user_level', $role, $subscription_id ) );

			do_action( 'rcp_form_processing', $_POST, $user_data['id'], $price );

			// process a paid subscription
			if( $price > '0' ) {

				if( ! empty( $discount ) ) {

					// record the usage of this discount code
					$discounts->add_to_user( $user_data['id'], $discount );

					// incrase the usage count for the code
					$discounts->increase_uses( $discount_obj->id );

					// if the discount is 100%, log the user in and redirect to success page
					if( $price == '0' ) {
						rcp_set_status( $user_data['id'], 'active' );
						rcp_email_subscription_status( $user_data['id'], 'active' );
						rcp_login_user_in( $user_data['id'], $user_data['login'] );
						wp_redirect( rcp_get_return_url( $user_data['id'] ) ); exit;
					}

				}

				// Determine auto renew behavior
				if( '3' == rcp_get_auto_renew_behavior() && isset( $_POST['rcp_auto_renew'] ) ) {

					$auto_renew = true;

				} elseif( '1' == rcp_get_auto_renew_behavior() ) {

					$auto_renew = true;

				} else {

					$auto_renew = false;

				}

				// Remove trialing status, if it exists
				delete_user_meta( $user_data['id'], 'rcp_is_trialing' );

				// log the new user in
				rcp_login_user_in( $user_data['id'], $user_data['login'] );

				$redirect = rcp_get_return_url( $user_data['id'] );

				$subscription_data = array(
					'price'             => $price,
					'discount'          => $base_price - $price,
					'discount_code'     => $discount,
					'fee' 			    => ! empty( $subscription->fee ) ? number_format( $subscription->fee, 2 ) : 0,
					'length' 			=> $expiration->duration,
					'length_unit' 		=> strtolower( $expiration->duration_unit ),
					'subscription_id'   => $subscription->id,
					'subscription_name' => $subscription->name,
					'key' 				=> $subscription_key,
					'user_id' 			=> $user_data['id'],
					'user_name' 		=> $user_data['login'],
					'user_email' 		=> $user_data['email'],
					'currency' 			=> $rcp_options['currency'],
					'auto_renew' 		=> $auto_renew,
					'return_url' 		=> $redirect,
					'new_user' 			=> $user_data['need_new'],
					'post_data' 		=> $_POST
				);

				// send all of the subscription data off for processing by the gateway
				rcp_send_to_gateway( $gateway, apply_filters( 'rcp_subscription_data', $subscription_data ) );

			// process a free or trial subscription
			} else {

				// This is a free user registration or trial

				// if the subscription is a free trial, we need to record it in the user meta
				if( $member_expires != 'none' ) {

					// this is so that users can only sign up for one trial
					update_user_meta( $user_data['id'], 'rcp_has_trialed', 'yes' );
					update_user_meta( $user_data['id'], 'rcp_is_trialing', 'yes' );

					// activate the user's trial subscription
					rcp_set_status( $user_data['id'], 'active' );
					rcp_email_subscription_status( $user_data['id'], 'trial' );

				} else {

					// set the user's status to free
					rcp_set_status( $user_data['id'], 'free' );
					rcp_email_subscription_status( $user_data['id'], 'free' );

				}

				// date for trial / paid users, "none" for free users
				rcp_set_expiration_date( $user_data['id'], $member_expires );

				if( $user_data['need_new'] ) {

					if( ! isset( $rcp_options['disable_new_user_notices'] ) ) {

						// send an email to the admin alerting them of the registration
						wp_new_user_notification( $user_data['id']) ;

					}

					// log the new user in
					rcp_login_user_in( $user_data['id'], $user_data['login'] );

				}
				// send the newly created user to the redirect page after logging them in
				wp_redirect( rcp_get_return_url( $user_data['id'] ) ); exit;

			} // end price check

		} // end if new user id

	} // end nonce check
}
 /**
  * Process registration
  *
  * @since 2.3
  */
 public function process_signup()
 {
     Twocheckout::privateKey($this->secret_key);
     Twocheckout::sellerId($this->seller_id);
     Twocheckout::sandbox($this->test_mode);
     $member = new RCP_Member($this->user_id);
     if (empty($_POST['twoCheckoutToken'])) {
         rcp_errors()->add('missing_card_token', __('Missing 2Checkout token, please try again or contact support if the issue persists.', 'rcp'), 'register');
         return;
     }
     $paid = false;
     if ($this->auto_renew) {
         $payment_type = 'Credit Card';
         $line_items = array(array("recurrence" => $this->length . ' ' . ucfirst($this->length_unit), "type" => 'product', "price" => $this->amount, "productId" => $this->subscription_id, "name" => $this->subscription_name, "quantity" => '1', "tangible" => 'N', "startupFee" => $this->signup_fee));
     } else {
         $payment_type = 'Credit Card One Time';
         $line_items = array(array("recurrence" => 0, "type" => 'product', "price" => $this->amount, "productId" => $this->subscription_id, "name" => $this->subscription_name, "quantity" => '1', "tangible" => 'N', "startupFee" => $this->signup_fee));
     }
     try {
         $charge = Twocheckout_Charge::auth(array('merchantOrderId' => $this->subscription_key, 'token' => $_POST['twoCheckoutToken'], 'currency' => strtolower($this->currency), 'billingAddr' => array('name' => sanitize_text_field($_POST['rcp_card_name']), 'addrLine1' => sanitize_text_field($_POST['rcp_card_address']), 'city' => sanitize_text_field($_POST['rcp_card_city']), 'state' => sanitize_text_field($_POST['rcp_card_state']), 'zipCode' => sanitize_text_field($_POST['rcp_card_zip']), 'country' => sanitize_text_field($_POST['rcp_card_country']), 'email' => $this->email), "lineItems" => $line_items));
         if ($charge['response']['responseCode'] == 'APPROVED') {
             // Look to see if we have an existing subscription to cancel
             if ($member->just_upgraded() && rcp_can_member_cancel($member->ID)) {
                 $cancelled = rcp_cancel_member_payment_profile($member->ID, false);
             }
             $payment_data = array('date' => date('Y-m-d H:i:s', current_time('timestamp')), 'subscription' => $this->subscription_name, 'payment_type' => $payment_type, 'subscription_key' => $this->subscription_key, 'amount' => $this->amount + $this->signup_fee, 'user_id' => $this->user_id, 'transaction_id' => $charge['response']['transactionId']);
             $rcp_payments = new RCP_Payments();
             $rcp_payments->insert($payment_data);
             $paid = true;
         }
     } catch (Twocheckout_Error $e) {
         wp_die($e->getMessage(), __('Error', 'rcp'), array('response' => '401'));
     }
     if ($paid) {
         // set this user to active
         $member->renew($this->auto_renew);
         $member->add_note(__('Subscription started in 2Checkout', 'rcp'));
         $member->set_payment_profile_id('2co_' . $charge['response']['orderNumber']);
         if (!is_user_logged_in()) {
             // log the new user in
             rcp_login_user_in($this->user_id, $this->user_name, $_POST['rcp_user_pass']);
         }
         do_action('rcp_2co_signup', $this->user_id, $this);
     }
     // redirect to the success page, or error page if something went wrong
     wp_redirect($this->return_url);
     exit;
 }
 /**
  * Process registration
  *
  * @since 2.1
  */
 public function process_signup()
 {
     \Stripe\Stripe::setApiKey($this->secret_key);
     $paid = false;
     $member = new RCP_Member($this->user_id);
     $customer_exists = false;
     if (empty($_POST['stripeToken'])) {
         wp_die(__('Missing Stripe token, please try again or contact support if the issue persists.', 'rcp'), __('Error', 'rcp'), array('response' => 400));
     }
     $customer_id = $member->get_payment_profile_id();
     if ($customer_id) {
         $customer_exists = true;
         try {
             // Update the customer to ensure their card data is up to date
             $customer = \Stripe\Customer::retrieve($customer_id);
             if (isset($customer->deleted) && $customer->deleted) {
                 // This customer was deleted
                 $customer_exists = false;
             }
             // No customer found
         } catch (Exception $e) {
             $customer_exists = false;
         }
     }
     if (empty($customer_exists)) {
         try {
             $customer_args = array('card' => $_POST['stripeToken'], 'email' => $this->email);
             $customer = \Stripe\Customer::create(apply_filters('rcp_stripe_customer_create_args', $customer_args, $this));
             // A temporary invoice is created to force the customer's currency to be set to the store currency. See https://github.com/restrictcontentpro/restrict-content-pro/issues/549
             if (!empty($this->signup_fee)) {
                 \Stripe\InvoiceItem::create(array('customer' => $customer->id, 'amount' => 0, 'currency' => rcp_get_currency(), 'description' => 'Setting Customer Currency'));
                 $temp_invoice = \Stripe\Invoice::create(array('customer' => $customer->id));
             }
             $member->set_payment_profile_id($customer->id);
         } catch (Exception $e) {
             $this->handle_processing_error($e);
         }
     } else {
         $customer->source = $_POST['stripeToken'];
     }
     $customer->description = 'User ID: ' . $this->user_id . ' - User Email: ' . $this->email . ' Subscription: ' . $this->subscription_name;
     $customer->metadata = array('user_id' => $this->user_id, 'email' => $this->email, 'subscription' => $this->subscription_name);
     $customer->save();
     if ($this->auto_renew) {
         // process a subscription sign up
         if (!($plan_id = $this->plan_exists($this->subscription_name))) {
             // create the plan if it doesn't exist
             $plan_id = $this->create_plan($this->subscription_name);
         }
         try {
             // Add fees before the plan is updated and charged
             if (!empty($this->signup_fee)) {
                 $customer->account_balance = $customer->account_balance + $this->signup_fee * rcp_stripe_get_currency_multiplier();
                 // Add additional amount to initial payment (in cents)
                 $customer->save();
                 if (isset($temp_invoice)) {
                     $invoice = \Stripe\Invoice::retrieve($temp_invoice->id);
                     $invoice->closed = true;
                     $invoice->save();
                     unset($temp_invoice, $invoice);
                 }
             }
             // clean up any past due or unpaid subscriptions before upgrading/downgrading
             foreach ($customer->subscriptions->all()->data as $subscription) {
                 // check if we are renewing an existing subscription. This should not ever be 'active', if it is Stripe
                 // will do nothing. If it is 'past_due' the most recent invoice will be paid and the subscription will become active
                 if ($subscription->plan->id == $plan_id && in_array($subscription->status, array('active', 'past_due'))) {
                     continue;
                 }
                 // remove any subscriptions that are past_due or inactive
                 if (in_array($subscription->status, array('past_due', 'unpaid'))) {
                     $subscription->cancel();
                 }
             }
             // If the customer has an existing subscription, we need to cancel it
             if ($member->just_upgraded() && rcp_can_member_cancel($member->ID)) {
                 $cancelled = rcp_cancel_member_payment_profile($member->ID, false);
             }
             $sub_args = array('plan' => $plan_id, 'prorate' => false);
             if (!empty($this->discount_code)) {
                 $sub_args['coupon'] = $this->discount_code;
             }
             // Set the customer's subscription in Stripe
             $subscription = $customer->subscriptions->create(array($sub_args));
             $member->set_merchant_subscription_id($subscription->id);
             // subscription payments are recorded via webhook
             $paid = true;
         } catch (\Stripe\Error\Card $e) {
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\InvalidRequest $e) {
             // Invalid parameters were supplied to Stripe's API
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\Authentication $e) {
             // Authentication with Stripe's API failed
             // (maybe you changed API keys recently)
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\ApiConnection $e) {
             // Network communication with Stripe failed
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\Base $e) {
             // Display a very generic error to the user
             $this->handle_processing_error($e);
         } catch (Exception $e) {
             // Something else happened, completely unrelated to Stripe
             $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
             $error .= print_r($e, true);
             wp_die($error, __('Error', 'rcp'), array('response' => 401));
         }
     } else {
         // process a one time payment signup
         try {
             $charge = \Stripe\Charge::create(apply_filters('rcp_stripe_charge_create_args', array('amount' => round(($this->amount + $this->signup_fee) * rcp_stripe_get_currency_multiplier(), 0), 'currency' => strtolower($this->currency), 'customer' => $customer->id, 'description' => 'User ID: ' . $this->user_id . ' - User Email: ' . $this->email . ' Subscription: ' . $this->subscription_name, 'receipt_email' => $this->email, 'metadata' => array('email' => $this->email, 'user_id' => $this->user_id, 'level_id' => $this->subscription_id, 'level' => $this->subscription_name, 'key' => $this->subscription_key)), $this));
             $payment_data = array('date' => date('Y-m-d H:i:s', current_time('timestamp')), 'subscription' => $this->subscription_name, 'payment_type' => 'Credit Card One Time', 'subscription_key' => $this->subscription_key, 'amount' => $this->amount + $this->signup_fee, 'user_id' => $this->user_id, 'transaction_id' => $charge->id);
             $rcp_payments = new RCP_Payments();
             $rcp_payments->insert($payment_data);
             $paid = true;
         } catch (\Stripe\Error\Card $e) {
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\InvalidRequest $e) {
             // Invalid parameters were supplied to Stripe's API
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\Authentication $e) {
             // Authentication with Stripe's API failed
             // (maybe you changed API keys recently)
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\ApiConnection $e) {
             // Network communication with Stripe failed
             $this->handle_processing_error($e);
         } catch (\Stripe\Error\Base $e) {
             // Display a very generic error to the user
             $this->handle_processing_error($e);
         } catch (Exception $e) {
             // Something else happened, completely unrelated to Stripe
             $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
             $error .= print_r($e, true);
             wp_die($error, __('Error', 'rcp'), array('response' => 401));
         }
     }
     if ($paid) {
         // If this is a one-time signup and the customer has an existing subscription, we need to cancel it
         if (!$this->auto_renew && $member->just_upgraded() && rcp_can_member_cancel($member->ID)) {
             $cancelled = rcp_cancel_member_payment_profile($member->ID, false);
         }
         // set this user to active
         $member->set_status('active');
         $member->set_recurring($this->auto_renew);
         if (!is_user_logged_in()) {
             // log the new user in
             rcp_login_user_in($this->user_id, $this->user_name, $_POST['rcp_user_pass']);
         }
         if (!$this->auto_renew) {
             $member->set_expiration_date($member->calculate_expiration());
         }
         do_action('rcp_stripe_signup', $this->user_id, $this);
     } else {
         wp_die(__('An error occurred, please contact the site administrator: ', 'rcp') . get_bloginfo('admin_email'), __('Error', 'rcp'), array('response' => 401));
     }
     // redirect to the success page, or error page if something went wrong
     wp_redirect($this->return_url);
     exit;
 }
 /**
  * Process registration
  *
  * @since 2.1
  */
 public function process_signup()
 {
     \Stripe\Stripe::setApiKey($this->secret_key);
     $paid = false;
     $member = new RCP_Member($this->user_id);
     $customer_exists = false;
     if (empty($_POST['stripeToken'])) {
         wp_die(__('Missing Stripe token, please try again or contact support if the issue persists.', 'rcp'), __('Error', 'rcp'), array('response' => 400));
     }
     if ($this->auto_renew) {
         // process a subscription sign up
         $plan_id = strtolower(str_replace(' ', '', $this->subscription_name));
         if (!$this->plan_exists($plan_id)) {
             // create the plan if it doesn't exist
             $this->create_plan($this->subscription_name);
         }
         try {
             $customer_id = $member->get_payment_profile_id();
             if ($customer_id) {
                 $customer_exists = true;
                 try {
                     // Update the customer to ensure their card data is up to date
                     $customer = \Stripe\Customer::retrieve($customer_id);
                     if (isset($customer->deleted) && $customer->deleted) {
                         // This customer was deleted
                         $customer_exists = false;
                     }
                     // No customer found
                 } catch (Exception $e) {
                     $customer_exists = false;
                 }
             }
             if (!$customer_exists) {
                 $customer_args = array('card' => $_POST['stripeToken'], 'email' => $this->email, 'description' => 'User ID: ' . $this->user_id . ' - User Email: ' . $this->email . ' Subscription: ' . $this->subscription_name);
                 if (!empty($this->discount_code)) {
                     $customer_args['coupon'] = $this->discount_code;
                 }
                 $customer = \Stripe\Customer::create(apply_filters('rcp_stripe_customer_create_args', $customer_args, $this));
             } else {
                 $customer->card = $_POST['stripeToken'];
             }
             // Add fees before the plan is updated and charged
             if (!empty($this->signup_fee)) {
                 if ($this->signup_fee > 0) {
                     $description = sprintf(__('Signup Fee for %s', 'rcp'), $this->subscription_name);
                 } else {
                     $description = sprintf(__('Signup Discount for %s', 'rcp'), $this->subscription_name);
                 }
                 \Stripe\InvoiceItem::create(apply_filters('rcp_stripe_invoice_item_create_args', array('customer' => $customer->id, 'amount' => $this->signup_fee * 100, 'currency' => strtolower($this->currency), 'description' => $description), $this, $customer));
                 // Create the invoice containing taxes / discounts / fees
                 $invoice = \Stripe\Invoice::create(apply_filters('rcp_stripe_invoice_create_args', array('customer' => $customer->id), $this, $customer));
             }
             if (!empty($this->discount_code)) {
                 $customer->coupon = $this->discount_code;
             }
             // Save the card and any coupon
             $customer->save();
             // Process the invoice if there is one
             if (!empty($invoice)) {
                 $invoice->pay();
             }
             // Update the customer's subscription in Stripe
             $customer->updateSubscription(array('plan' => $plan_id));
             $member->set_payment_profile_id($customer->id);
             // subscription payments are recorded via webhook
             $paid = true;
         } catch (\Stripe\Error\Card $e) {
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
             exit;
         } catch (\Stripe\Error\InvalidRequest $e) {
             // Invalid parameters were supplied to Stripe's API
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Authentication $e) {
             // Authentication with Stripe's API failed
             // (maybe you changed API keys recently)
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\ApiConnection $e) {
             // Network communication with Stripe failed
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Base $e) {
             // Display a very generic error to the user
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (Exception $e) {
             // Something else happened, completely unrelated to Stripe
             $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
             $error .= print_r($e, true);
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         }
     } else {
         // process a one time payment signup
         try {
             $charge = \Stripe\Charge::create(apply_filters('rcp_stripe_charge_create_args', array('amount' => $this->amount * 100, 'currency' => strtolower($this->currency), 'card' => $_POST['stripeToken'], 'description' => 'User ID: ' . $this->user_id . ' - User Email: ' . $this->email . ' Subscription: ' . $this->subscription_name, 'receipt_email' => $this->email, 'metadata' => array('email' => $this->email, 'user_id' => $this->user_id, 'level_id' => $this->subscription_id, 'level' => $this->subscription_name, 'key' => $this->subscription_key)), $this));
             $payment_data = array('date' => date('Y-m-d g:i:s', current_time('timestamp')), 'subscription' => $this->subscription_name, 'payment_type' => 'Credit Card One Time', 'subscription_key' => $this->subscription_key, 'amount' => $this->amount, 'user_id' => $this->user_id, 'transaction_id' => $charge->id);
             $rcp_payments = new RCP_Payments();
             $rcp_payments->insert($payment_data);
             $paid = true;
         } catch (\Stripe\Error\Card $e) {
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
             exit;
         } catch (\Stripe\Error\InvalidRequest $e) {
             // Invalid parameters were supplied to Stripe's API
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Authentication $e) {
             // Authentication with Stripe's API failed
             // (maybe you changed API keys recently)
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\ApiConnection $e) {
             // Network communication with Stripe failed
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Base $e) {
             // Display a very generic error to the user
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (Exception $e) {
             // Something else happened, completely unrelated to Stripe
             $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
             $error .= print_r($e, true);
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         }
     }
     if ($paid) {
         // set this user to active
         $member->set_status('active');
         $member->set_recurring($this->auto_renew);
         if (!is_user_logged_in()) {
             // log the new user in
             rcp_login_user_in($this->user_id, $this->user_name, $_POST['rcp_user_pass']);
         }
         do_action('rcp_stripe_signup', $this->user_id, $this);
     } else {
         wp_die(__('An error occurred, please contact the site administrator: ', 'rcp') . get_bloginfo('admin_email'), __('Error', 'rcp'), array('response' => '401'));
     }
     // redirect to the success page, or error page if something went wrong
     wp_redirect($this->return_url);
     exit;
 }
/**
 * Register a new user
 *
 * @access      public
 * @since       1.0
 */
function rcp_process_registration()
{
    // check nonce
    if (!(isset($_POST["rcp_register_nonce"]) && wp_verify_nonce($_POST['rcp_register_nonce'], 'rcp-register-nonce'))) {
        return;
    }
    global $rcp_options, $rcp_levels_db;
    $subscription_id = rcp_get_registration()->get_subscription();
    $discount = isset($_POST['rcp_discount']) ? sanitize_text_field($_POST['rcp_discount']) : '';
    $price = number_format((double) $rcp_levels_db->get_level_field($subscription_id, 'price'), 2);
    $price = str_replace(',', '', $price);
    $subscription = $rcp_levels_db->get_level($subscription_id);
    $auto_renew = rcp_registration_is_recurring();
    // if both today's total and the recurring total are 0, the there is a full discount
    // if this is not a recurring subscription only check today's total
    $full_discount = $auto_renew ? rcp_get_registration()->get_total() == 0 && rcp_get_registration()->get_recurring_total() == 0 : rcp_get_registration()->get_total() == 0;
    // get the selected payment method/gateway
    if (!isset($_POST['rcp_gateway'])) {
        $gateway = 'paypal';
    } else {
        $gateway = sanitize_text_field($_POST['rcp_gateway']);
    }
    /***********************
     * validate the form
     ***********************/
    do_action('rcp_before_form_errors', $_POST);
    $is_ajax = isset($_POST['rcp_ajax']);
    $user_data = rcp_validate_user_data();
    if (!rcp_is_registration()) {
        // no subscription level was chosen
        rcp_errors()->add('no_level', __('Please choose a subscription level', 'rcp'), 'register');
    }
    if ($subscription_id && $price == 0 && $subscription->duration > 0 && rcp_has_used_trial($user_data['id'])) {
        // this ensures that users only sign up for a free trial once
        rcp_errors()->add('free_trial_used', __('You may only sign up for a free trial once', 'rcp'), 'register');
    }
    if (!empty($discount)) {
        // make sure we have a valid discount
        if (rcp_validate_discount($discount, $subscription_id)) {
            // check if the user has already used this discount
            if ($price > 0 && !$user_data['need_new'] && rcp_user_has_used_discount($user_data['id'], $discount) && apply_filters('rcp_discounts_once_per_user', false)) {
                rcp_errors()->add('discount_already_used', __('You can only use the discount code once', 'rcp'), 'register');
            }
        } else {
            // the entered discount code is incorrect
            rcp_errors()->add('invalid_discount', __('The discount you entered is invalid', 'rcp'), 'register');
        }
    }
    // Validate extra fields in gateways with the 2.1+ gateway API
    if (!has_action('rcp_gateway_' . $gateway) && $price > 0 && !$full_discount) {
        $gateways = new RCP_Payment_Gateways();
        $gateway_var = $gateways->get_gateway($gateway);
        $gateway_obj = new $gateway_var['class']();
        $gateway_obj->validate_fields();
    }
    do_action('rcp_form_errors', $_POST);
    // retrieve all error messages, if any
    $errors = rcp_errors()->get_error_messages();
    if (!empty($errors) && $is_ajax) {
        wp_send_json_error(array('success' => false, 'errors' => rcp_get_error_messages_html('register'), 'nonce' => wp_create_nonce('rcp-register-nonce')));
    } elseif ($is_ajax) {
        wp_send_json_success(array('success' => true));
    }
    // only create the user if there are no errors
    if (!empty($errors)) {
        return;
    }
    if ($user_data['need_new']) {
        $user_data['id'] = wp_insert_user(array('user_login' => $user_data['login'], 'user_pass' => $user_data['password'], 'user_email' => $user_data['email'], 'first_name' => $user_data['first_name'], 'last_name' => $user_data['last_name'], 'display_name' => $user_data['first_name'] . ' ' . $user_data['last_name'], 'user_registered' => date('Y-m-d H:i:s')));
    }
    if (empty($user_data['id'])) {
        return;
    }
    // Setup the member object
    $member = new RCP_Member($user_data['id']);
    update_user_meta($user_data['id'], '_rcp_new_subscription', '1');
    $subscription_key = rcp_generate_subscription_key();
    $old_subscription_id = $member->get_subscription_id();
    if ($old_subscription_id) {
        update_user_meta($user_data['id'], '_rcp_old_subscription_id', $old_subscription_id);
    }
    if (!$member->is_active()) {
        update_user_meta($user_data['id'], 'rcp_subscription_level', $subscription_id);
        update_user_meta($user_data['id'], 'rcp_subscription_key', $subscription_key);
        // Ensure no pending level details are set
        delete_user_meta($user_data['id'], 'rcp_pending_subscription_level');
        delete_user_meta($user_data['id'], 'rcp_pending_subscription_key');
        $member->set_status('pending');
    } else {
        // If the member is already active, we need to set these as pending changes
        update_user_meta($user_data['id'], 'rcp_pending_subscription_level', $subscription_id);
        update_user_meta($user_data['id'], 'rcp_pending_subscription_key', $subscription_key);
        // Flag the member as having just upgraded
        update_user_meta($user_data['id'], '_rcp_just_upgraded', current_time('timestamp'));
    }
    $member->set_joined_date('', $subscription_id);
    // Calculate the expiration date for the member
    $member_expires = $member->calculate_expiration($auto_renew);
    update_user_meta($user_data['id'], 'rcp_pending_expiration_date', $member_expires);
    // remove the user's old role, if this is a new user, we need to replace the default role
    $old_role = get_option('default_role', 'subscriber');
    if ($old_subscription_id) {
        $old_level = $rcp_levels_db->get_level($old_subscription_id);
        $old_role = !empty($old_level->role) ? $old_level->role : $old_role;
    }
    $member->remove_role($old_role);
    // Set the user's role
    $role = !empty($subscription->role) ? $subscription->role : 'subscriber';
    $user = new WP_User($user_data['id']);
    $user->add_role(apply_filters('rcp_default_user_level', $role, $subscription_id));
    do_action('rcp_form_processing', $_POST, $user_data['id'], $price);
    // process a paid subscription
    if ($price > '0') {
        if (!empty($discount)) {
            $discounts = new RCP_Discounts();
            $discount_obj = $discounts->get_by('code', $discount);
            // record the usage of this discount code
            $discounts->add_to_user($user_data['id'], $discount);
            // increase the usage count for the code
            $discounts->increase_uses($discount_obj->id);
            // if the discount is 100%, log the user in and redirect to success page
            if ($full_discount) {
                $member->set_expiration_date($member_expires);
                $member->set_status('active');
                rcp_login_user_in($user_data['id'], $user_data['login']);
                wp_redirect(rcp_get_return_url($user_data['id']));
                exit;
            }
        }
        // Remove trialing status, if it exists
        delete_user_meta($user_data['id'], 'rcp_is_trialing');
        // log the new user in
        rcp_login_user_in($user_data['id'], $user_data['login']);
        $redirect = rcp_get_return_url($user_data['id']);
        $subscription_data = array('price' => rcp_get_registration()->get_total(true, false), 'discount' => rcp_get_registration()->get_total_discounts(), 'discount_code' => $discount, 'fee' => rcp_get_registration()->get_total_fees(), 'length' => $subscription->duration, 'length_unit' => strtolower($subscription->duration_unit), 'subscription_id' => $subscription->id, 'subscription_name' => $subscription->name, 'key' => $subscription_key, 'user_id' => $user_data['id'], 'user_name' => $user_data['login'], 'user_email' => $user_data['email'], 'currency' => $rcp_options['currency'], 'auto_renew' => $auto_renew, 'return_url' => $redirect, 'new_user' => $user_data['need_new'], 'post_data' => $_POST);
        // if giving the user a credit, make sure the credit does not exceed the first payment
        if ($subscription_data['fee'] < 0 && abs($subscription_data['fee']) > $subscription_data['price']) {
            $subscription_data['fee'] = -1 * $subscription_data['price'];
        }
        update_user_meta($user_data['id'], 'rcp_pending_subscription_amount', $subscription_data['price'] + $subscription_data['fee']);
        // send all of the subscription data off for processing by the gateway
        rcp_send_to_gateway($gateway, apply_filters('rcp_subscription_data', $subscription_data));
        // process a free or trial subscription
    } else {
        // This is a free user registration or trial
        $member->set_expiration_date($member_expires);
        // if the subscription is a free trial, we need to record it in the user meta
        if ($member_expires != 'none') {
            // activate the user's trial subscription
            $member->set_status('active');
            // this is so that users can only sign up for one trial
            update_user_meta($user_data['id'], 'rcp_has_trialed', 'yes');
            update_user_meta($user_data['id'], 'rcp_is_trialing', 'yes');
            rcp_email_subscription_status($user_data['id'], 'trial');
        } else {
            update_user_meta($user_data['id'], 'rcp_subscription_level', $subscription_id);
            update_user_meta($user_data['id'], 'rcp_subscription_key', $subscription_key);
            // Ensure no pending level details are set
            delete_user_meta($user_data['id'], 'rcp_pending_subscription_level');
            delete_user_meta($user_data['id'], 'rcp_pending_subscription_key');
            // set the user's status to free
            $member->set_status('free');
            rcp_email_subscription_status($user_data['id'], 'free');
        }
        if ($user_data['need_new']) {
            if (!isset($rcp_options['disable_new_user_notices'])) {
                // send an email to the admin alerting them of the registration
                wp_new_user_notification($user_data['id']);
            }
            // log the new user in
            rcp_login_user_in($user_data['id'], $user_data['login']);
        }
        // send the newly created user to the redirect page after logging them in
        wp_redirect(rcp_get_return_url($user_data['id']));
        exit;
    }
    // end price check
}