/**
  * Process registration
  *
  * @since 2.1
  */
 public function process_signup()
 {
     global $rcp_options;
     $args = array('USER' => $this->username, 'PWD' => $this->password, 'SIGNATURE' => $this->signature, 'VERSION' => '124', 'METHOD' => $this->auto_renew ? 'CreateRecurringPaymentsProfile' : 'DoDirectPayment', 'AMT' => $this->amount, 'CURRENCYCODE' => strtoupper($this->currency), 'SHIPPINGAMT' => 0, 'TAXAMT' => 0, 'DESC' => $this->subscription_name, 'SOFTDESCRIPTOR' => get_bloginfo('name') . ' - ' . $this->subscription_name, 'SOFTDESCRIPTORCITY' => get_bloginfo('admin_email'), 'CUSTOM' => $this->user_id, 'NOTIFYURL' => add_query_arg('listener', 'EIPN', home_url('index.php')), 'EMAIL' => $this->email, 'CREDITCARDTYPE' => '', 'ACCT' => sanitize_text_field($_POST['rcp_card_number']), 'EXPDATE' => sanitize_text_field($_POST['rcp_card_exp_month'] . $_POST['rcp_card_exp_year']), 'CVV2' => sanitize_text_field($_POST['rcp_card_cvc']), 'ZIP' => sanitize_text_field($_POST['rcp_card_zip']), 'BUTTONSOURCE' => 'EasyDigitalDownloads_SP', 'PROFILESTARTDATE' => date('Y-m-d\\TH:i:s', strtotime('+' . $this->length . ' ' . $this->length_unit, time())), 'BILLINGPERIOD' => ucwords($this->length_unit), 'BILLINGFREQUENCY' => $this->length, 'FAILEDINITAMTACTION' => 'CancelOnFailure', 'TOTALBILLINGCYCLES' => $this->auto_renew ? 0 : 1);
     if ($this->auto_renew) {
         $initamt = round($this->amount + $this->signup_fee, 2);
         if ($initamt >= 0) {
             $args['INITAMT'] = $initamt;
         }
     }
     $request = wp_remote_post($this->api_endpoint, array('timeout' => 45, 'sslverify' => false, 'httpversion' => '1.1', 'body' => $args));
     $body = wp_remote_retrieve_body($request);
     $code = wp_remote_retrieve_response_code($request);
     $message = wp_remote_retrieve_response_message($request);
     if (is_wp_error($request)) {
         do_action('rcp_paypal_pro_signup_payment_failed', $request, $this);
         $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
         $error .= '<p>' . $request->get_error_message() . '</p>';
         wp_die($error, __('Error', 'rcp'), array('response' => '401'));
     } elseif (200 == $code && 'OK' == $message) {
         if (is_string($body)) {
             wp_parse_str($body, $body);
         }
         if (false !== strpos(strtolower($body['ACK']), 'failure')) {
             do_action('rcp_paypal_pro_signup_payment_failed', $request, $this);
             $error = '<p>' . __('PayPal subscription creation failed.', 'rcp') . '</p>';
             $error .= '<p>' . __('Error message:', 'rcp') . ' ' . $body['L_LONGMESSAGE0'] . '</p>';
             $error .= '<p>' . __('Error code:', 'rcp') . ' ' . $body['L_ERRORCODE0'] . '</p>';
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } else {
             // Successful signup
             $member = new RCP_Member($this->user_id);
             if ($member->just_upgraded() && rcp_can_member_cancel($member->ID)) {
                 $cancelled = rcp_cancel_member_payment_profile($member->ID, false);
             }
             if (isset($body['PROFILEID'])) {
                 $member->set_payment_profile_id($body['PROFILEID']);
             }
             if (isset($body['PROFILESTATUS']) && 'ActiveProfile' === $body['PROFILESTATUS']) {
                 // Confirm a one-time payment
                 $member->renew($this->auto_renew);
             }
             wp_redirect(esc_url_raw(rcp_get_return_url()));
             exit;
             exit;
         }
     } else {
         wp_die(__('Something has gone wrong, please try again', 'rcp'), __('Error', 'rcp'), array('back_link' => true, 'response' => '401'));
     }
 }
 /**
  * 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 a member cancellation request
 *
 * @access      public
 * @since       2.1
 */
function rcp_process_member_cancellation() {

	if( ! isset( $_GET['rcp-action'] ) || $_GET['rcp-action'] !== 'cancel' ) {
		return;
	}

	if( ! is_user_logged_in() ) {
		return;
	}

	if( wp_verify_nonce( $_GET['_wpnonce'], 'rcp-cancel-nonce' ) ) {

		global $rcp_options;

		$success  = rcp_cancel_member_payment_profile( get_current_user_id() );
		$redirect = remove_query_arg( array( 'rcp-action', '_wpnonce', 'member-id' ), rcp_get_current_url() );

		if( ! $success && rcp_is_paypal_subscriber() ) {
			// No profile ID stored, so redirect to PayPal to cancel manually
			$redirect = 'https://www.paypal.com/cgi-bin/customerprofileweb?cmd=_manage-paylist';
		}

		if( $success ) {

			do_action( 'rcp_process_member_cancellation', get_current_user_id() );

			$redirect = add_query_arg( 'profile', 'cancelled', $redirect );

		}
	
		wp_redirect( $redirect ); 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;
 }
Ejemplo n.º 5
0
function rcp_process_data()
{
    if (!is_admin()) {
        return;
    }
    if (!empty($_POST)) {
        /****************************************
         * subscription levels
         ****************************************/
        // add a new subscription level
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'add-level') {
            if (!current_user_can('rcp_manage_levels')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $levels = new RCP_Levels();
            $add = $levels->insert($_POST);
            if ($add) {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-member-levels&rcp_message=level_added';
            } else {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-member-levels&rcp_message=level_not_added';
            }
            wp_safe_redirect($url);
            exit;
        }
        // edit a subscription level
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'edit-subscription') {
            if (!current_user_can('rcp_manage_levels')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $levels = new RCP_Levels();
            $update = $levels->update($_POST['subscription_id'], $_POST);
            if ($update) {
                // clear the cache
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-member-levels&rcp_message=level_updated';
            } else {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-member-levels&rcp_message=level_not_updated';
            }
            wp_safe_redirect($url);
            exit;
        }
        // add a subscription for an existing member
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'add-subscription') {
            if (!current_user_can('rcp_manage_members')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            if (isset($_POST['expiration']) && strtotime('NOW') > strtotime($_POST['expiration']) && 'none' !== $_POST['expiration']) {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-members&rcp_message=user_not_added';
                header("Location:" . $url);
            } else {
                $levels = new RCP_Levels();
                $user = get_user_by('login', $_POST['user']);
                $expiration = isset($_POST['expiration']) ? sanitize_text_field($_POST['expiration']) : 'none';
                $level_id = absint($_POST['level']);
                rcp_set_expiration_date($user->ID, $expiration);
                rcp_set_status($user->ID, 'active');
                update_user_meta($user->ID, 'rcp_signup_method', 'manual');
                // Add a role, if needed, to the user
                $subscription = $levels->get_level($level_id);
                update_user_meta($user->ID, 'rcp_subscription_level', $level_id);
                // Add the new user role
                $role = !empty($subscription->role) ? $subscription->role : 'subscriber';
                $user->add_role($role);
                if (isset($_POST['recurring'])) {
                    update_user_meta($user->ID, 'rcp_recurring', 'yes');
                } else {
                    delete_user_meta($user->ID, 'rcp_recurring');
                }
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-members&rcp_message=user_added';
                header("Location:" . $url);
            }
        }
        // bulk edit members
        if (isset($_POST['rcp-bulk-action']) && $_POST['rcp-bulk-action']) {
            if (!wp_verify_nonce($_POST['rcp_bulk_edit_nonce'], 'rcp_bulk_edit_nonce')) {
                wp_die(__('Nonce verification failed.', 'rcp'));
            }
            if (!current_user_can('rcp_manage_members')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            if (empty($_POST['member-ids'])) {
                wp_die(__('Please select at least one member to edit.', 'rcp'));
            }
            $member_ids = array_map('absint', $_POST['member-ids']);
            $action = !empty($_POST['rcp-bulk-action']) ? sanitize_text_field($_POST['rcp-bulk-action']) : false;
            foreach ($member_ids as $member_id) {
                $member = new RCP_Member($member_id);
                if (!empty($_POST['expiration']) && 'delete' !== $action) {
                    $member->set_expiration_date(date('Y-m-d H:i:s', strtotime($_POST['expiration'])));
                }
                if ($action) {
                    switch ($action) {
                        case 'mark-active':
                            $member->set_status('active');
                            break;
                        case 'mark-expired':
                            $member->set_status('expired');
                            break;
                        case 'mark-cancelled':
                            $member->set_status('cancelled');
                            break;
                        case 'delete':
                            wp_delete_user($member->ID);
                            break;
                    }
                }
            }
            wp_redirect(admin_url('admin.php?page=rcp-members&rcp_message=members_updated'));
            exit;
        }
        // edit a member's subscription
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'edit-member') {
            if (!current_user_can('rcp_manage_members')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $levels = new RCP_Levels();
            $user_id = absint($_POST['user']);
            $member = new RCP_Member($user_id);
            $status = sanitize_text_field($_POST['status']);
            $level_id = absint($_POST['level']);
            $expiration = isset($_POST['expiration']) ? sanitize_text_field($_POST['expiration']) : 'none';
            $expiration = 'none' !== $expiration ? date('Y-m-d 23:59:59', strtotime($_POST['expiration'])) : $expiration;
            if (!empty($_POST['expiration'])) {
                $member->set_expiration_date($expiration);
            }
            if (isset($_POST['level'])) {
                $current_id = rcp_get_subscription_id($user_id);
                $new_level = $levels->get_level($level_id);
                $old_level = $levels->get_level($current_id);
                if ($current_id != $level_id) {
                    update_user_meta($user_id, 'rcp_subscription_level', $level_id);
                    // Remove the old user role
                    $role = !empty($old_level->role) ? $old_level->role : 'subscriber';
                    $member->remove_role($role);
                    // Add the new user role
                    $role = !empty($new_level->role) ? $new_level->role : 'subscriber';
                    $member->add_role($role);
                }
            }
            if (isset($_POST['recurring'])) {
                $member->set_recurring(true);
            } else {
                $member->set_recurring(false);
            }
            if (isset($_POST['trialing'])) {
                update_user_meta($user_id, 'rcp_is_trialing', 'yes');
            } else {
                delete_user_meta($user_id, 'rcp_is_trialing');
            }
            if (isset($_POST['signup_method'])) {
                update_user_meta($user_id, 'rcp_signup_method', $_POST['signup_method']);
            }
            if (isset($_POST['notes'])) {
                update_user_meta($user_id, 'rcp_notes', wp_kses($_POST['notes'], array()));
            }
            if (isset($_POST['status'])) {
                rcp_set_status($user_id, $status);
            }
            if (isset($_POST['payment-profile-id'])) {
                $member->set_payment_profile_id($_POST['payment-profile-id']);
            }
            do_action('rcp_edit_member', $user_id);
            wp_redirect(admin_url('admin.php?page=rcp-members&edit_member=' . $user_id . '&rcp_message=user_updated'));
            exit;
        }
        /****************************************
         * discount codes
         ****************************************/
        // add a new discount code
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'add-discount') {
            if (!current_user_can('rcp_manage_discounts')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $discounts = new RCP_Discounts();
            // Setup unsanitized data
            $data = array('name' => $_POST['name'], 'description' => $_POST['description'], 'amount' => $_POST['amount'], 'unit' => isset($_POST['unit']) && $_POST['unit'] == '%' ? '%' : 'flat', 'code' => $_POST['code'], 'status' => 'active', 'expiration' => $_POST['expiration'], 'max_uses' => $_POST['max'], 'subscription_id' => $_POST['subscription']);
            $add = $discounts->insert($data);
            if ($add) {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-discounts&rcp_message=discount_added';
            } else {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-discounts&rcp_message=discount_not_added';
            }
            wp_safe_redirect($url);
            exit;
        }
        // edit a discount code
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'edit-discount') {
            if (!current_user_can('rcp_manage_discounts')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $discounts = new RCP_Discounts();
            // Setup unsanitized data
            $data = array('name' => $_POST['name'], 'description' => $_POST['description'], 'amount' => $_POST['amount'], 'unit' => isset($_POST['unit']) && $_POST['unit'] == '%' ? '%' : 'flat', 'code' => $_POST['code'], 'status' => $_POST['status'], 'expiration' => $_POST['expiration'], 'max_uses' => $_POST['max'], 'subscription_id' => $_POST['subscription']);
            $update = $discounts->update($_POST['discount_id'], $data);
            if ($update) {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-discounts&discount-updated=1';
            } else {
                $url = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=rcp-discounts&discount-updated=0';
            }
            wp_safe_redirect($url);
            exit;
        }
        // add a new manual payment
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'add-payment') {
            if (!current_user_can('rcp_manage_payments')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $payments = new RCP_Payments();
            $user = get_user_by('login', $_POST['user']);
            if ($user) {
                $data = array('amount' => empty($_POST['amount']) ? 0.0 : sanitize_text_field($_POST['amount']), 'user_id' => $user->ID, 'date' => empty($_POST['date']) ? date('Y-m-d H:i:s', current_time('timestamp')) : date('Y-m-d', strtotime($_POST['date'], current_time('timestamp'))) . ' ' . date('H:i:s', current_time('timestamp')), 'payment_type' => 'manual', 'subscription' => rcp_get_subscription($user->ID), 'subscription_key' => rcp_get_subscription_key($user->ID), 'transaction_id' => sanitize_text_field($_POST['transaction-id']), 'status' => sanitize_text_field($_POST['status']));
                $add = $payments->insert($data);
            }
            if (!empty($add)) {
                $cache_args = array('earnings' => 1, 'subscription' => 0, 'user_id' => 0, 'date' => '');
                $cache_key = md5(implode(',', $cache_args));
                delete_transient($cache_key);
                $url = admin_url('admin.php?page=rcp-payments&rcp_message=payment_added');
            } else {
                $url = admin_url('admin.php?page=rcp-payments&rcp_message=payment_not_added');
            }
            wp_safe_redirect($url);
            exit;
        }
        // edit a payment
        if (isset($_POST['rcp-action']) && $_POST['rcp-action'] == 'edit-payment') {
            if (!current_user_can('rcp_manage_payments')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $payments = new RCP_Payments();
            $payment_id = absint($_POST['payment-id']);
            $user = get_user_by('login', $_POST['user']);
            if ($user && $payment_id) {
                $data = array('amount' => empty($_POST['amount']) ? 0.0 : sanitize_text_field($_POST['amount']), 'user_id' => $user->ID, 'date' => empty($_POST['date']) ? date('Y-m-d H:i:s', current_time('timestamp')) : date('Y-m-d', strtotime($_POST['date'], current_time('timestamp'))) . ' ' . date('H:i:s', current_time('timestamp')), 'subscription' => rcp_get_subscription($user->ID), 'subscription_key' => rcp_get_subscription_key($user->ID), 'transaction_id' => sanitize_text_field($_POST['transaction-id']), 'status' => sanitize_text_field($_POST['status']));
                $update = $payments->update($payment_id, $data);
            }
            if (!empty($update)) {
                $cache_args = array('earnings' => 1, 'subscription' => 0, 'user_id' => 0, 'date' => '');
                $cache_key = md5(implode(',', $cache_args));
                delete_transient($cache_key);
                $url = admin_url('admin.php?page=rcp-payments&rcp_message=payment_updated');
            } else {
                $url = admin_url('admin.php?page=rcp-payments&rcp_message=payment_not_updated');
            }
            wp_safe_redirect($url);
            exit;
        }
    }
    /*************************************
     * delete data
     *************************************/
    if (!empty($_GET)) {
        /* member processing */
        if (isset($_GET['revoke_access'])) {
            if (!current_user_can('rcp_manage_members')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            rcp_set_status(urldecode(absint($_GET['revoke_access'])), 'cancelled');
        }
        if (isset($_GET['activate_member'])) {
            if (!current_user_can('rcp_manage_members')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            rcp_set_status(urldecode(absint($_GET['activate_member'])), 'active');
        }
        if (isset($_GET['cancel_member'])) {
            if (!current_user_can('rcp_manage_members')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            rcp_cancel_member_payment_profile(urldecode(absint($_GET['cancel_member'])));
            wp_safe_redirect(admin_url(add_query_arg('rcp_message', 'member_cancelled', 'admin.php?page=rcp-members')));
            exit;
        }
        /* subscription processing */
        if (isset($_GET['delete_subscription']) && $_GET['delete_subscription'] > 0) {
            if (!current_user_can('rcp_manage_levels')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $members_of_subscription = rcp_get_members_of_subscription(absint($_GET['delete_subscription']));
            // cancel all active members of this subscription
            if ($members_of_subscription) {
                foreach ($members_of_subscription as $member) {
                    rcp_set_status($member, 'cancelled');
                }
            }
            $levels = new RCP_Levels();
            $levels->remove($_GET['delete_subscription']);
        }
        if (isset($_GET['activate_subscription']) && $_GET['activate_subscription'] > 0) {
            if (!current_user_can('rcp_manage_levels')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $levels = new RCP_Levels();
            $update = $levels->update(absint($_GET['activate_subscription']), array('status' => 'active'));
            delete_transient('rcp_subscription_levels');
        }
        if (isset($_GET['deactivate_subscription']) && $_GET['deactivate_subscription'] > 0) {
            if (!current_user_can('rcp_manage_levels')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $levels = new RCP_Levels();
            $update = $levels->update(absint($_GET['deactivate_subscription']), array('status' => 'inactive'));
            delete_transient('rcp_subscription_levels');
        }
        /* discount processing */
        if (!empty($_GET['delete_discount'])) {
            if (!current_user_can('rcp_manage_discounts')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $discounts = new RCP_Discounts();
            $discounts->delete($_GET['delete_discount']);
        }
        if (!empty($_GET['activate_discount'])) {
            if (!current_user_can('rcp_manage_discounts')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $discounts = new RCP_Discounts();
            $discounts->update($_GET['activate_discount'], array('status' => 'active'));
        }
        if (!empty($_GET['deactivate_discount'])) {
            if (!current_user_can('rcp_manage_discounts')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $discounts = new RCP_Discounts();
            $discounts->update($_GET['deactivate_discount'], array('status' => 'disabled'));
        }
        if (!empty($_GET['rcp-action']) && $_GET['rcp-action'] == 'delete_payment' && wp_verify_nonce($_GET['_wpnonce'], 'rcp_delete_payment_nonce')) {
            if (!current_user_can('rcp_manage_payments')) {
                wp_die(__('You do not have permission to perform this action.', 'rcp'));
            }
            $payments = new RCP_Payments();
            $payments->delete(absint($_GET['payment_id']));
            wp_safe_redirect(admin_url(add_query_arg('rcp_message', 'payment_deleted', 'admin.php?page=rcp-payments')));
            exit;
        }
    }
}
 /**
  * Process PayPal IPN
  *
  * @since 2.1
  */
 public function process_webhooks()
 {
     if (!isset($_GET['listener']) || strtoupper($_GET['listener']) != 'IPN') {
         return;
     }
     global $rcp_options;
     nocache_headers();
     if (!class_exists('IpnListener')) {
         // instantiate the IpnListener class
         include RCP_PLUGIN_DIR . 'includes/gateways/paypal/paypal-ipnlistener.php';
     }
     $listener = new IpnListener();
     $verified = false;
     if ($this->test_mode) {
         $listener->use_sandbox = true;
     }
     /*
     if( isset( $rcp_options['ssl'] ) ) {
     	$listener->use_ssl = true;
     } else {
     	$listener->use_ssl = false;
     }
     */
     //To post using the fsockopen() function rather than cURL, use:
     if (isset($rcp_options['disable_curl'])) {
         $listener->use_curl = false;
     }
     try {
         $listener->requirePostMethod();
         $verified = $listener->processIpn();
     } catch (Exception $e) {
         status_header(402);
         //die( 'IPN exception: ' . $e->getMessage() );
     }
     /*
     The processIpn() method returned true if the IPN was "VERIFIED" and false if it
     was "INVALID".
     */
     if ($verified || isset($_POST['verification_override']) || ($this->test_mode || isset($rcp_options['disable_ipn_verify']))) {
         status_header(200);
         $user_id = 0;
         $posted = apply_filters('rcp_ipn_post', $_POST);
         // allow $_POST to be modified
         if (!empty($posted['subscr_id'])) {
             $user_id = rcp_get_member_id_from_profile_id($posted['subscr_id']);
         }
         if (empty($user_id) && !empty($posted['custom']) && is_numeric($posted['custom'])) {
             $user_id = absint($posted['custom']);
         }
         if (empty($user_id) && !empty($posted['payer_email'])) {
             $user = get_user_by('email', $posted['payer_email']);
             $user_id = $user ? $user->ID : false;
         }
         $member = new RCP_Member($user_id);
         if (!$member || !$member->ID > 0) {
             die('no member found');
         }
         $subscription_id = $member->get_pending_subscription_id();
         if (empty($subscription_id)) {
             $subscription_id = $member->get_subscription_id();
         }
         if (!$subscription_id) {
             die('no subscription for member found');
         }
         if (!rcp_get_subscription_details($subscription_id)) {
             die('no subscription level found');
         }
         $subscription_name = $posted['item_name'];
         $subscription_key = $posted['item_number'];
         $amount = number_format((double) $posted['mc_gross'], 2);
         $amount2 = number_format((double) $posted['mc_amount3'], 2);
         $payment_status = $posted['payment_status'];
         $currency_code = $posted['mc_currency'];
         $subscription_price = number_format((double) rcp_get_subscription_price($subscription_id), 2);
         $pending_amount = get_user_meta($member->ID, 'rcp_pending_subscription_amount', true);
         $pending_amount = number_format((double) $pending_amount, 2);
         // Check for invalid amounts in the IPN data
         if (!empty($pending_amount) && !empty($amount) && in_array($posted['txn_type'], array('web_accept', 'subscr_payment'))) {
             if ($amount < $pending_amount) {
                 rcp_add_member_note($member->ID, sprintf(__('Incorrect amount received in the IPN. Amount received was %s. The amount should have been %s. PayPal Transaction ID: %s', 'rcp'), $amount, $pending_amount, sanitize_text_field($posted['txn_id'])));
                 die('incorrect amount');
             } else {
                 delete_user_meta($member->ID, 'rcp_pending_subscription_amount');
             }
         }
         // setup the payment info in an array for storage
         $payment_data = array('date' => date('Y-m-d H:i:s', strtotime($posted['payment_date'], current_time('timestamp'))), 'subscription' => $posted['item_name'], 'payment_type' => $posted['txn_type'], 'subscription_key' => $subscription_key, 'amount' => $amount, 'user_id' => $user_id, 'transaction_id' => $posted['txn_id']);
         do_action('rcp_valid_ipn', $payment_data, $user_id, $posted);
         if ($posted['txn_type'] == 'web_accept' || $posted['txn_type'] == 'subscr_payment') {
             // only check for an existing payment if this is a payment IPD request
             if (rcp_check_for_existing_payment($posted['txn_type'], $posted['payment_date'], $subscription_key)) {
                 $log_data = array('post_title' => __('Duplicate Payment', 'rcp'), 'post_content' => __('A duplicate payment was detected. The new payment was still recorded, so you may want to check into both payments.', 'rcp'), 'post_parent' => 0, 'log_type' => 'gateway_error');
                 $log_meta = array('user_subscription' => $posted['item_name'], 'user_id' => $user_id);
                 $log_entry = WP_Logging::insert_log($log_data, $log_meta);
                 die('duplicate IPN detected');
             }
             if (strtolower($currency_code) != strtolower($rcp_options['currency'])) {
                 // the currency code is invalid
                 $log_data = array('post_title' => __('Invalid Currency Code', 'rcp'), 'post_content' => sprintf(__('The currency code in an IPN request did not match the site currency code. Payment data: %s', 'rcp'), json_encode($payment_data)), 'post_parent' => 0, 'log_type' => 'gateway_error');
                 $log_meta = array('user_subscription' => $posted['item_name'], 'user_id' => $user_id);
                 $log_entry = WP_Logging::insert_log($log_data, $log_meta);
                 die('invalid currency code');
             }
         }
         if (isset($rcp_options['email_ipn_reports'])) {
             wp_mail(get_bloginfo('admin_email'), __('IPN report', 'rcp'), $listener->getTextReport());
         }
         /* now process the kind of subscription/payment */
         $rcp_payments = new RCP_Payments();
         // Subscriptions
         switch ($posted['txn_type']) {
             case "subscr_signup":
                 // when a new user signs up
                 // store the recurring payment ID
                 update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']);
                 if ($member->just_upgraded() && rcp_can_member_cancel($member->ID)) {
                     $cancelled = rcp_cancel_member_payment_profile($member->ID, false);
                 }
                 $member->set_payment_profile_id($posted['subscr_id']);
                 do_action('rcp_ipn_subscr_signup', $user_id);
                 die('successful subscr_signup');
                 break;
             case "subscr_payment":
                 // when a user makes a recurring payment
                 update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']);
                 $member->set_payment_profile_id($posted['subscr_id']);
                 $member->renew(true);
                 // record this payment in the database
                 $rcp_payments->insert($payment_data);
                 do_action('rcp_ipn_subscr_payment', $user_id);
                 die('successful subscr_payment');
                 break;
             case "subscr_cancel":
                 if (!$member->just_upgraded()) {
                     // user is marked as cancelled but retains access until end of term
                     $member->set_status('cancelled');
                     // set the use to no longer be recurring
                     delete_user_meta($user_id, 'rcp_paypal_subscriber');
                     do_action('rcp_ipn_subscr_cancel', $user_id);
                     die('successful subscr_cancel');
                 }
                 break;
             case "subscr_failed":
                 do_action('rcp_ipn_subscr_failed');
                 die('successful subscr_failed');
                 break;
             case "subscr_eot":
                 // user's subscription has reached the end of its term
                 if ('cancelled' !== $member->get_status($user_id)) {
                     $member->set_status('expired');
                 }
                 do_action('rcp_ipn_subscr_eot', $user_id);
                 die('successful subscr_eot');
                 break;
             case "web_accept":
                 switch (strtolower($payment_status)) {
                     case 'completed':
                         if ($member->just_upgraded() && rcp_can_member_cancel($member->ID)) {
                             $cancelled = rcp_cancel_member_payment_profile($member->ID, false);
                             if ($cancelled) {
                                 $member->set_payment_profile_id('');
                             }
                         }
                         // set this user to active
                         $member->renew();
                         $rcp_payments->insert($payment_data);
                         break;
                     case 'denied':
                     case 'expired':
                     case 'failed':
                     case 'voided':
                         $member->set_status('cancelled');
                         break;
                 }
                 die('successful web_accept');
                 break;
             case "cart":
             case "express_checkout":
             default:
                 break;
         }
     } else {
         if (isset($rcp_options['email_ipn_reports'])) {
             // an invalid IPN attempt was made. Send an email to the admin account to investigate
             wp_mail(get_bloginfo('admin_email'), __('Invalid IPN', 'rcp'), $listener->getTextReport());
         }
         status_header(400);
         die('invalid IPN');
     }
 }
 /**
  * Process PayPal IPN
  *
  * @since 2.1
  */
 public function process_webhooks()
 {
     if (!isset($_GET['listener']) || strtoupper($_GET['listener']) != 'EIPN') {
         return;
     }
     $user_id = 0;
     $posted = apply_filters('rcp_ipn_post', $_POST);
     // allow $_POST to be modified
     if (!empty($posted['recurring_payment_id'])) {
         $user_id = rcp_get_member_id_from_profile_id($posted['recurring_payment_id']);
     }
     if (empty($user_id) && !empty($posted['custom']) && is_numeric($posted['custom'])) {
         $user_id = absint($posted['custom']);
     }
     if (empty($user_id) && !empty($posted['payer_email'])) {
         $user = get_user_by('email', $posted['payer_email']);
         $user_id = $user ? $user->ID : false;
     }
     $member = new RCP_Member($user_id);
     if (!$member || !$member->ID > 0) {
         die('no member found');
     }
     $subscription_id = $member->get_pending_subscription_id();
     if (empty($subscription_id)) {
         $subscription_id = $member->get_subscription_id();
     }
     if (!$subscription_id) {
         die('no subscription for member found');
     }
     if (!rcp_get_subscription_details($subscription_id)) {
         die('no subscription level found');
     }
     $amount = number_format((double) $posted['mc_gross'], 2);
     // setup the payment info in an array for storage
     $payment_data = array('date' => date('Y-m-d H:i:s', strtotime($posted['payment_date'])), 'subscription' => $member->get_subscription_name(), 'payment_type' => $posted['txn_type'], 'subscription_key' => $member->get_subscription_key(), 'amount' => $amount, 'user_id' => $user_id, 'transaction_id' => $posted['txn_id']);
     do_action('rcp_valid_ipn', $payment_data, $user_id, $posted);
     if (isset($rcp_options['email_ipn_reports'])) {
         wp_mail(get_bloginfo('admin_email'), __('IPN report', 'rcp'), $listener->getTextReport());
     }
     /* now process the kind of subscription/payment */
     $rcp_payments = new RCP_Payments();
     // Subscriptions
     switch ($posted['txn_type']) {
         case "recurring_payment_profile_created":
             if (isset($posted['initial_payment_txn_id'])) {
                 $transaction_id = 'Completed' == $posted['initial_payment_status'] ? $posted['initial_payment_txn_id'] : '';
             } else {
                 $transaction_id = $posted['ipn_track_id'];
             }
             if (empty($transaction_id) || $rcp_payments->payment_exists($transaction_id)) {
                 break;
             }
             // setup the payment info in an array for storage
             $payment_data = array('date' => date('Y-m-d H:i:s', strtotime($posted['time_created'])), 'subscription' => $member->get_subscription_name(), 'payment_type' => $posted['txn_type'], 'subscription_key' => $member->get_subscription_key(), 'amount' => number_format((double) $posted['initial_payment_amount'], 2), 'user_id' => $user_id, 'transaction_id' => sanitize_text_field($transaction_id));
             $rcp_payments->insert($payment_data);
             $expiration = date('Y-m-d 23:59:59', strtotime($posted['next_payment_date']));
             $member->renew($member->is_recurring(), 'active', $expiration);
             break;
         case "recurring_payment":
             // when a user makes a recurring payment
             update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']);
             $member->set_payment_profile_id($posted['recurring_payment_id']);
             $member->renew(true);
             // record this payment in the database
             $rcp_payments->insert($payment_data);
             do_action('rcp_ipn_subscr_payment', $user_id);
             die('successful recurring_payment');
             break;
         case "recurring_payment_profile_cancel":
             if (!$member->just_upgraded()) {
                 // user is marked as cancelled but retains access until end of term
                 $member->set_status('cancelled');
                 // set the use to no longer be recurring
                 delete_user_meta($user_id, 'rcp_paypal_subscriber');
                 do_action('rcp_ipn_subscr_cancel', $user_id);
                 die('successful recurring_payment_profile_cancel');
             }
             break;
         case "recurring_payment_failed":
         case "recurring_payment_suspended_due_to_max_failed_payment":
             if ('cancelled' !== $member->get_status($user_id)) {
                 $member->set_status('expired');
             }
             do_action('rcp_ipn_subscr_failed');
             die('successful recurring_payment_failed or recurring_payment_suspended_due_to_max_failed_payment');
             break;
         case "web_accept":
             switch (strtolower($posted['payment_status'])) {
                 case 'completed':
                     if ($member->just_upgraded() && rcp_can_member_cancel($member->ID)) {
                         $cancelled = rcp_cancel_member_payment_profile($member->ID, false);
                         if ($cancelled) {
                             $member->set_payment_profile_id('');
                         }
                     }
                     $payment_data = array('date' => date('Y-m-d H:i:s', strtotime($posted['payment_date'])), 'subscription' => $member->get_subscription_name(), 'payment_type' => $posted['txn_type'], 'subscription_key' => $member->get_subscription_key(), 'amount' => number_format((double) $posted['mc_gross'], 2), 'user_id' => $user_id, 'transaction_id' => sanitize_text_field($posted['txn_id']));
                     $rcp_payments->insert($payment_data);
                     // set this user to active
                     $member->renew();
                     break;
                 case 'denied':
                 case 'expired':
                 case 'failed':
                 case 'voided':
                     $member->set_status('cancelled');
                     break;
             }
             die('successful web_accept');
             break;
     }
 }