Example #1
0
 /**
  * Revokes a referral when the payment is deleted
  *
  * @access  public
  * @since   1.0
  */
 public function revoke_referral_on_delete($payment_id = 0)
 {
     if (!affiliate_wp()->settings->get('revoke_on_refund')) {
         return;
     }
     $payments = new RCP_Payments();
     $payment = $payments->get_payment($payment_id);
     $this->reject_referral($payment->subscription_key);
 }
 /**
  * Process registration
  *
  * @since 2.1
  */
 public function process_signup()
 {
     // setup the payment info in an array for storage
     $payment_data = array('subscription' => $this->subscription_name, 'payment_type' => 'manual', 'subscription_key' => $this->subscription_key, 'amount' => $this->amount, 'user_id' => $this->user_id, 'transaction_id' => $this->generate_transaction_id());
     $rcp_payments = new RCP_Payments();
     $rcp_payments->insert($payment_data);
     $this->renew_member(false, 'pending');
     wp_redirect($this->return_url);
     exit;
 }
 /**
  * Process registration
  *
  * @since 2.1
  */
 public function process_signup()
 {
     $member = new RCP_Member($this->user_id);
     $old_level = get_user_meta($member->ID, '_rcp_old_subscription_id', true);
     if (!empty($old_level) && $old_level == $this->subscription_id) {
         $expiration = $member->calculate_expiration();
     } else {
         delete_user_meta($member->ID, 'rcp_pending_expiration_date');
         $expiration = $member->calculate_expiration(true);
     }
     $member->renew(false, 'pending', $expiration);
     // setup the payment info in an array for storage
     $payment_data = array('subscription' => $this->subscription_name, 'payment_type' => 'manual', 'subscription_key' => $this->subscription_key, 'amount' => $this->amount + $this->signup_fee, 'user_id' => $this->user_id, 'transaction_id' => $this->generate_transaction_id());
     $rcp_payments = new RCP_Payments();
     $rcp_payments->insert($payment_data);
     wp_redirect($this->return_url);
     exit;
 }
/**
 * Generate Invoice
 *
 * @since 2.6
*/
function rcp_generate_invoice($payment_id = 0)
{
    global $rcp_options, $rcp_payment, $rcp_member;
    if (empty($payment_id)) {
        return;
    }
    $payments_db = new RCP_Payments();
    $payment = $payments_db->get_payment($payment_id);
    if (!$payment) {
        wp_die(__('This payment record does not exist', 'rcp'));
    }
    if ($payment->user_id != get_current_user_id() && !current_user_can('rcp_manage_payments')) {
        wp_die(__('You do not have permission to download this invoice', 'rcp'));
    }
    $rcp_payment = $payment;
    $rcp_member = new RCP_Member($payment->user_id);
    rcp_get_template_part('invoice');
    die;
    // Stop the rest of the page from processsing and being sent to the browser
}
 /**
  * Get the data being exported
  *
  * @access      public
  * @since       1.5
  * @return      array
  */
 public function get_data()
 {
     global $wpdb;
     $data = array();
     $args = array();
     if (!empty($_POST['rcp-year'])) {
         $args['date'] = array();
         $args['date']['year'] = absint($_POST['rcp-year']);
         if (!empty($_POST['rcp-month'])) {
             $args['date']['month'] = absint($_POST['rcp-month']);
         }
     }
     $args['number'] = 999999;
     $rcp_db = new RCP_Payments();
     $payments = $rcp_db->get_payments($args);
     foreach ($payments as $payment) {
         $user = get_userdata($payment->user_id);
         $data[] = array('id' => $payment->id, 'subscription' => $payment->subscription, 'amount' => $payment->amount, 'user_id' => $payment->user_id, 'user_login' => $user->user_login, 'payment_type' => $payment->payment_type, 'subscription_key' => $payment->subscription_key, 'date' => $payment->date);
     }
     $data = apply_filters('rcp_export_get_data', $data);
     $data = apply_filters('rcp_export_get_data_' . $this->export_type, $data);
     return $data;
 }
<?php

$payment_id = !empty($_GET['payment_id']) ? absint($_GET['payment_id']) : 0;
$payments = new RCP_Payments();
$payment = $payments->get_payment($payment_id);
$user = get_userdata($payment->user_id);
?>
<h2>
	<?php 
_e('Edit Payment', 'rcp');
?>
 - 
	<a href="<?php 
echo admin_url('/admin.php?page=rcp-payments');
?>
" class="button-secondary">
		<?php 
_e('Cancel', 'rcp');
?>
	</a>
</h2>
<form id="rcp-edit-member" action="" method="post">
	<table class="form-table">
		<tbody>
			<tr valign="top">
				<th scope="row" valign="top">
					<label for="rcp-user-id"><?php 
_e('User', 'rcp');
?>
</label>
				</th>
 /**
  * Proccess webhooks
  *
  * @since 2.3
  */
 public function process_webhooks()
 {
     if (isset($_GET['listener']) && $_GET['listener'] == '2checkout') {
         global $wpdb;
         $hash = strtoupper(md5($_POST['sale_id'] . $this->seller_id . $_POST['invoice_id'] . $this->secret_word));
         if (!hash_equals($hash, $_POST['md5_hash'])) {
             die('-1');
         }
         if (empty($_POST['message_type'])) {
             die('-2');
         }
         if (empty($_POST['vendor_id'])) {
             die('-3');
         }
         $subscription_key = sanitize_text_field($_POST['vendor_order_id']);
         $member_id = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = 'rcp_subscription_key' AND meta_value = %s LIMIT 1", $subscription_key));
         if (!$member_id) {
             die('-4');
         }
         $member = new RCP_Member($member_id);
         if (!rcp_is_2checkout_subscriber($member->ID)) {
             return;
         }
         $payments = new RCP_Payments();
         switch (strtoupper($_POST['message_type'])) {
             case 'ORDER_CREATED':
                 break;
             case 'REFUND_ISSUED':
                 $payment = $payments->get_payment_by('transaction_id', $_POST['invoice_id']);
                 $payments->update($payment->id, array('status' => 'refunded'));
                 if (!empty($_POST['recurring'])) {
                     $member->cancel();
                     $member->add_note(__('Subscription cancelled via refund 2Checkout', 'rcp'));
                 }
                 break;
             case 'RECURRING_INSTALLMENT_SUCCESS':
                 $payment_data = array('date' => date('Y-m-d H:i:s', strtotime($_POST['timestamp'], current_time('timestamp'))), 'subscription' => $member->get_subscription_name(), 'payment_type' => sanitize_text_field($_POST['payment_type']), 'subscription_key' => $subscription_key, 'amount' => sanitize_text_field($_POST['item_list_amount_1']), 'user_id' => $member->ID, 'transaction_id' => sanitize_text_field($_POST['invoice_id']));
                 $recurring = !empty($_POST['recurring']);
                 $member->renew($recurring);
                 $payments->insert($payment_data);
                 $member->add_note(__('Subscription renewed in 2Checkout', 'rcp'));
                 break;
             case 'RECURRING_INSTALLMENT_FAILED':
                 break;
             case 'RECURRING_STOPPED':
                 if (!$member->just_upgraded()) {
                     $member->cancel();
                     $member->add_note(__('Subscription cancelled in 2Checkout', 'rcp'));
                 }
                 break;
             case 'RECURRING_COMPLETE':
                 break;
             case 'RECURRING_RESTARTED':
                 $member->set_status('active');
                 $member->add_note(__('Subscription restarted in 2Checkout', 'rcp'));
                 break;
             case 'FRAUD_STATUS_CHANGED':
                 switch ($_POST['fraud_status']) {
                     case 'pass':
                         break;
                     case 'fail':
                         $member->set_status('pending');
                         $member->add_note(__('Payment flagged as fraudulent in 2Checkout', 'rcp'));
                         break;
                     case 'wait':
                         break;
                 }
                 break;
         }
         do_action('rcp_2co_' . strtolower($_POST['message_type']) . '_ins', $member);
         die('success');
     }
 }
 public function process_webhooks()
 {
     if (!isset($_GET['listener']) || strtolower($_GET['listener']) != 'stripe') {
         return;
     }
     // Ensure listener URL is not cached by W3TC
     if (!defined('DONOTCACHEPAGE')) {
         define('DONOTCACHEPAGE', true);
     }
     \Stripe\Stripe::setApiKey($this->secret_key);
     // retrieve the request's body and parse it as JSON
     $body = @file_get_contents('php://input');
     $event_json_id = json_decode($body);
     $expiration = '';
     // for extra security, retrieve from the Stripe API
     if (isset($event_json_id->id)) {
         $rcp_payments = new RCP_Payments();
         $event_id = $event_json_id->id;
         try {
             $event = \Stripe\Event::retrieve($event_id);
             $payment_event = $event->data->object;
             if (empty($payment_event->customer)) {
                 die('no customer attached');
             }
             // retrieve the customer who made this payment (only for subscriptions)
             $user = rcp_get_member_id_from_profile_id($payment_event->customer);
             if (empty($user)) {
                 // Grab the customer ID from the old meta keys
                 global $wpdb;
                 $user = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '_rcp_stripe_user_id' AND meta_value = %s LIMIT 1", $payment_event->customer));
             }
             if (empty($user)) {
                 die('no user ID found');
             }
             $member = new RCP_Member($user);
             // check to confirm this is a stripe subscriber
             if ($member) {
                 if (!$member->get_subscription_id()) {
                     die('no subscription ID for member');
                 }
                 if ($event->type == 'charge.succeeded' || $event->type == 'invoice.payment_succeeded') {
                     // setup payment data
                     $payment_data = array('date' => date_i18n('Y-m-d g:i:s', $event->created), 'payment_type' => 'Credit Card', 'user_id' => $member->ID, 'amount' => '', 'transaction_id' => '');
                     if ($event->type == 'charge.succeeded') {
                         // Successful one-time payment
                         if (empty($payment_event->invoice)) {
                             $payment_data['amount'] = $payment_event->amount / rcp_stripe_get_currency_multiplier();
                             $payment_data['transaction_id'] = $payment_event->id;
                             // Successful subscription payment
                         } else {
                             $invoice = \Stripe\Invoice::retrieve($payment_event->invoice);
                             $payment_data['amount'] = $invoice->amount_due / rcp_stripe_get_currency_multiplier();
                             $payment_data['transaction_id'] = $payment_event->id;
                         }
                         // Successful subscription paid made with account credit where no charge is created
                     } elseif ($event->type == 'invoice.payment_succeeded' && empty($payment_event->charge)) {
                         $payment_data['amount'] = $payment_event->amount_due / rcp_stripe_get_currency_multiplier();
                         $payment_data['transaction_id'] = $payment_event->id;
                         $invoice = $payment_event;
                     }
                     if (!empty($payment_data['transaction_id']) && !$rcp_payments->payment_exists($payment_data['transaction_id'])) {
                         if (!empty($invoice->subscription)) {
                             $customer = \Stripe\Customer::retrieve($member->get_payment_profile_id());
                             $subscription = $customer->subscriptions->retrieve($invoice->subscription);
                             if (!empty($subscription)) {
                                 $expiration = date('Y-m-d 23:59:59', $subscription->current_period_end);
                                 $member->set_recurring();
                             }
                             $member->set_merchant_subscription_id($subscription->id);
                         }
                         $member->renew($member->is_recurring(), 'active', $expiration);
                         // These must be retrieved after the status is set to active in order for upgrades to work properly
                         $payment_data['subscription'] = $member->get_subscription_name();
                         $payment_data['subscription_key'] = $member->get_subscription_key();
                         // record this payment if it hasn't been recorded yet
                         $rcp_payments->insert($payment_data);
                         do_action('rcp_stripe_charge_succeeded', $user, $payment_data);
                         die('rcp_stripe_charge_succeeded action fired successfully');
                     } else {
                         die('duplicate payment found');
                     }
                 }
                 // failed payment
                 if ($event->type == 'charge.failed') {
                     do_action('rcp_stripe_charge_failed', $invoice);
                     die('rcp_stripe_charge_failed action fired successfully');
                 }
                 // Cancelled / failed subscription
                 if ($event->type == 'customer.subscription.deleted') {
                     if (!$member->just_upgraded()) {
                         $member->set_status('cancelled');
                         die('member cancelled successfully');
                     }
                 }
                 do_action('rcp_stripe_' . $event->type, $payment_event);
             }
         } catch (Exception $e) {
             // something failed
             die('PHP exception: ' . $e->getMessage());
         }
         die('1');
     }
     die('no event ID found');
 }
/**
 * Generate PDF Invoice
 *
 * Loads and stores all of the data for the payment.  The HTML2PDF class is
 * instantiated and do_action() is used to call the invoice template which goes
 * ahead and renders the invoice.
 *
 * @since 2.0
 * @uses HTML2PDF
 * @uses wp_is_mobile()
*/
function rcp_generate_pdf_invoice($payment_id = 0)
{
    global $rcp_options;
    include_once RCP_PLUGIN_DIR . '/includes/libraries/tcpdf/tcpdf.php';
    include_once RCP_PLUGIN_DIR . '/includes/class-rcp-pdf-invoice.php';
    if (empty($payment_id)) {
        return;
    }
    $payments_db = new RCP_Payments();
    $payment = $payments_db->get_payment($payment_id);
    if (!$payment) {
        wp_die(__('This payment record does not exist', 'rcp'));
    }
    if ($payment->user_id != get_current_user_id() && !current_user_can('manage_options')) {
        wp_die(__('You do not have permission to download this invoice', 'rcp'));
    }
    $userdata = get_userdata($payment->user_id);
    $company_name = isset($rcp_options['invoice_company']) ? $rcp_options['invoice_company'] : '';
    $payment_date = date_i18n(get_option('date_format'), strtotime($payment->date));
    $pdf = new RCP_PDF_Invoice('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetDisplayMode('real');
    $pdf->setJPEGQuality(100);
    $pdf->SetTitle(sprintf(__('Invoice #%d', 'rcp'), $payment->id));
    $pdf->SetCreator(__('Restrict Content Pro', 'rcp'));
    $pdf->SetAuthor(get_option('blogname'));
    $pdf->SetMargins(8, 8, 8);
    $pdf->SetX(8);
    $pdf->AddPage();
    $font = isset($rcp_options['invoice_enable_char_support']) ? 'freesans' : 'Helvetica';
    $pdf->Ln(5);
    if (isset($rcp_options['invoice_logo']) && !empty($rcp_options['invoice_logo'])) {
        $pdf->Image($rcp_options['invoice_logo'], 8, 20, '', '11', '', false, 'LTR', false, 96);
    } else {
        $pdf->SetFont($font, '', 22);
        $pdf->SetTextColor(50, 50, 50);
        $pdf->Cell(0, 0, $company_name, 0, 2, 'L', false);
    }
    $pdf->SetFont($font, '', 18);
    $pdf->SetY(45);
    $pdf->Cell(0, 0, __('Invoice', 'rcp'), 0, 2, 'L', false);
    $pdf->SetXY(8, 60);
    $pdf->SetFont($font, 'B', 10);
    $pdf->Cell(0, 6, __('From', 'rcp'), 0, 2, 'L', false);
    $pdf->SetFont($font, '', 10);
    if (!empty($rcp_options['invoice_name'])) {
        $pdf->Cell(0, $pdf->calculate_line_height($rcp_options['invoice_name']), $rcp_options['invoice_name'], 0, 2, 'L', false);
    }
    if (!empty($rcp_options['invoice_address'])) {
        $pdf->Cell(0, $pdf->calculate_line_height($rcp_options['invoice_address']), $rcp_options['invoice_address'], 0, 2, 'L', false);
    }
    if (!empty($rcp_options['invoice_address_2'])) {
        $pdf->Cell(0, $pdf->calculate_line_height($rcp_options['invoice_address_2']), $rcp_options['invoice_address_2'], 0, 2, 'L', false);
    }
    if (!empty($rcp_options['invoice_city_state_zip'])) {
        $pdf->Cell(0, $pdf->calculate_line_height($rcp_options['invoice_city_state_zip']), $rcp_options['invoice_city_state_zip'], 0, 2, 'L', false);
    }
    if (!empty($rcp_options['invoice_email'])) {
        $pdf->SetTextColor(41, 102, 152);
        $pdf->Cell(0, $pdf->calculate_line_height($rcp_options['invoice_email']), $rcp_options['invoice_email'], 0, 2, 'L', false);
    }
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Ln(12);
    $pdf->Ln();
    $pdf->SetXY(60, 60);
    $pdf->SetFont($font, 'B', 10);
    $pdf->Cell(0, 6, __('To', 'rcp'), 0, 2, 'L', false);
    $pdf->SetFont($font, '', 10);
    $pdf->Cell(0, $pdf->calculate_line_height($userdata->display_name), $userdata->display_name, 0, 2, 'L', false);
    $pdf->SetTextColor(41, 102, 152);
    $pdf->Cell(0, 6, $userdata->user_email, 0, 2, 'L', false);
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Ln(5);
    $pdf->SetX(60);
    $pdf->SetTextColor(110, 110, 110);
    $pdf->Cell(30, 6, __('Invoice Date', 'rcp'), 0, 0, 'L', false);
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Cell(0, 6, $payment_date, 0, 2, 'L', false);
    $pdf->SetX(60);
    $pdf->SetTextColor(110, 110, 110);
    $pdf->Cell(30, 6, __('Invoice ID', 'rcp'), 0, 0, 'L', false);
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Cell(0, 6, '#' . $payment->id, 0, 2, 'L', false);
    $pdf->SetX(60);
    $pdf->SetTextColor(110, 110, 110);
    $pdf->Cell(30, 6, __('Subscription Key', 'rcp'), 0, 0, 'L', false);
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Cell(0, 6, $payment->subscription_key, 0, 2, 'L', false);
    $pdf->SetX(60);
    $pdf->SetX(60);
    $pdf->SetTextColor(110, 110, 110);
    $pdf->Cell(30, 6, __('Payment Method', 'rcp'), 0, 0, 'L', false);
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Cell(0, 6, $payment->payment_type, 0, 2, 'L', false);
    $pdf->SetX(60);
    $pdf->SetTextColor(110, 110, 110);
    $pdf->Cell(30, 6, __('Transaction ID', 'rcp'), 0, 0, 'L', false);
    $pdf->SetTextColor(50, 50, 50);
    $pdf->Cell(0, 6, $payment->transaction_id, 0, 2, 'L', false);
    $pdf->Ln(5);
    $pdf->SetX(61);
    $pdf->SetFillColor(224, 224, 224);
    $pdf->SetDrawColor(209, 209, 209);
    $pdf->SetFont($font, 'B', 10);
    $pdf->Cell(140, 8, __('Invoice Items', 'rcp'), 1, 2, 'C', true);
    $pdf->Ln(0.2);
    $pdf->SetX(61);
    $pdf->SetDrawColor(194, 221, 231);
    $pdf->SetFillColor(238, 238, 238);
    $pdf->SetFont($font, '', 9);
    $pdf->Cell(102, 7, __('Subscription', 'rcp'), 'BL', 0, 'C', false);
    $pdf->Cell(38, 7, __('Amount', 'rcp'), 'BR', 0, 'C', false);
    $pdf->Ln(0.2);
    $pdf->Ln();
    $pdf->SetX(61);
    $pdf->SetDrawColor(238, 238, 238);
    $pdf->SetX(61);
    $pdf->SetFont($font, '', 10);
    $amount = utf8_encode(html_entity_decode(rcp_currency_filter($payment->amount), ENT_COMPAT, 'UTF-8'));
    if (function_exists('iconv')) {
        // Ensure characters like euro; are properly converted. See GithuB issue #472 and #1570
        $amount = iconv('UTF-8', 'windows-1252', $amount);
    }
    $pdf->Cell(102, 8, html_entity_decode($payment->subscription), 'B', 0, 'L', false);
    $pdf->SetFillColor(250, 250, 250);
    $pdf->Cell(38, 8, $amount, 'B', 2, 'R', true);
    $pdf->Ln(5);
    $pdf->SetX(61);
    $pdf->SetFillColor(224, 224, 224);
    $pdf->SetDrawColor(209, 209, 209);
    $pdf->SetFont($font, 'B', 10);
    $pdf->Cell(140, 8, __('Invoice Totals', 'rcp'), 1, 2, 'C', true);
    $pdf->Ln(0.2);
    $pdf->SetDrawColor(238, 238, 238);
    $pdf->SetFillColor(250, 250, 250);
    $pdf->SetX(61);
    $pdf->SetFont($font, 'B', 11);
    $pdf->Cell(102, 10, __('Total', 'rcp'), 'B', 0, 'L', false);
    $pdf->Cell(38, 10, $amount, 'B', 2, 'R', true);
    $pdf->Ln(10);
    if (!empty($rcp_options['invoice_notes'])) {
        $pdf->SetX(60);
        $pdf->SetFont($font, '', 13);
        $pdf->Cell(0, 6, __('Additional Notes', 'rcp'), 0, 2, 'L', false);
        $pdf->Ln(2);
        $pdf->SetX(60);
        $pdf->SetFont($font, '', 10);
        $pdf->MultiCell(0, 6, $rcp_options['invoice_notes'], 0, 'L', false);
    }
    if (wp_is_mobile()) {
        $pdf->Output(apply_filters('rcp_invoice_filename_prefix', 'Invoice-') . $payment->id . '.pdf', 'I');
    } else {
        $pdf->Output(apply_filters('rcp_invoice_filename_prefix', 'Invoice-') . $payment->id . '.pdf', 'D');
    }
    die;
    // Stop the rest of the page from processsing and being sent to the browser
}
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['custom']) && is_numeric($posted['custom'])) {
             $user_id = absint($posted['custom']);
         } else {
             if (!empty($posted['subscr_id'])) {
                 $user_id = rcp_get_member_id_from_profile_id($posted['subscr_id']);
             } else {
                 if (!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->get_subscription_id()) {
             die('no member found');
         }
         if (!rcp_get_subscription_details($member->get_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($member->get_subscription_id()), 2);
         // setup the payment info in an array for storage
         $payment_data = array('date' => date('Y-m-d g: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']);
                 $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":
                 // 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':
                         // 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;
     }
     $posted = apply_filters('rcp_ipn_post', $_POST);
     // allow $_POST to be modified
     $user_id = absint($posted['custom']);
     $member = new RCP_Member($user_id);
     if (!$member || !$member->get_subscription_id()) {
         die('no member found');
     }
     if (!rcp_get_subscription_details($member->get_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 g: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":
             // when a user makes a recurring payment
             // record this payment in the database
             $rcp_payments->insert($payment_data);
             update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']);
             $member->set_payment_profile_id($posted['recurring_payment_id']);
             $this->renew_member(true);
             do_action('rcp_ipn_subscr_payment', $user_id);
             die('successful recurring_payment');
             break;
         case "recurring_payment_profile_cancel":
             // 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;
     }
 }
/**
 * Renders the Restrict > Payments page
 *
 * @since  1.0
 * @return void
*/
function rcp_payments_page()
{
    global $rcp_options;
    $current_page = admin_url('/admin.php?page=rcp-payments');
    ?>

	<div class="wrap">

		<?php 
    if (isset($_GET['view']) && 'new-payment' == $_GET['view']) {
        include 'new-payment.php';
    } elseif (isset($_GET['view']) && 'edit-payment' == $_GET['view']) {
        include 'edit-payment.php';
    } else {
        ?>
		<h2>
			<?php 
        _e('Payments', 'rcp');
        ?>
			<a href="<?php 
        echo admin_url('/admin.php?page=rcp-payments&view=new-payment');
        ?>
" class="add-new-h2">
				<?php 
        _e('Create Payment', 'rcp');
        ?>
			</a>
		</h2>

		<?php 
        do_action('rcp_payments_page_top');
        $rcp_payments = new RCP_Payments();
        $page = isset($_GET['p']) ? $_GET['p'] : 1;
        $per_page = 20;
        $search = !empty($_GET['s']) ? urldecode($_GET['s']) : '';
        $user = get_current_user_id();
        $screen = get_current_screen();
        $screen_option = $screen->get_option('per_page', 'option');
        $per_page = get_user_meta($user, $screen_option, true);
        if (empty($per_page) || $per_page < 1) {
            $per_page = $screen->get_option('per_page', 'default');
        }
        $total_pages = 1;
        $offset = $per_page * ($page - 1);
        $user_id = isset($_GET['user_id']) ? $_GET['user_id'] : 0;
        $payments = $rcp_payments->get_payments(array('offset' => $offset, 'number' => $per_page, 'user_id' => $user_id, 's' => $search));
        $payment_count = $rcp_payments->count(array('user_id' => $user_id));
        $total_pages = ceil($payment_count / $per_page);
        ?>
		<form id="rcp-member-search" method="get" action="<?php 
        menu_page_url('rcp-payments');
        ?>
">
			<label class="screen-reader-text" for="rcp-member-search-input"><?php 
        _e('Search Payments', 'rcp');
        ?>
</label>
			<input type="search" id="rcp-member-search-input" name="s" value="<?php 
        echo esc_attr($search);
        ?>
"/>
			<input type="hidden" name="page" value="rcp-payments"/>
			<input type="submit" name="" id="rcp-member-search-submit" class="button" value="<?php 
        _e('Search Payments', 'rcp');
        ?>
"/>
		</form>
		<p class="total"><strong><?php 
        _e('Total Earnings', 'rcp');
        ?>
: <?php 
        echo rcp_currency_filter(number_format_i18n($rcp_payments->get_earnings(), 2));
        ?>
</strong></p>
		<?php 
        if (!empty($user_id)) {
            ?>
		<p><a href="<?php 
            echo admin_url('admin.php?page=rcp-payments');
            ?>
" class="button-secondary" title="<?php 
            _e('View all payments', 'rcp');
            ?>
"><?php 
            _e('Reset User Filter', 'rcp');
            ?>
</a></p>
		<?php 
        }
        ?>
		<table class="wp-list-table widefat fixed posts rcp-payments">
			<thead>
				<tr>
					<th style="width: 40px;"><?php 
        _e('ID', 'rcp');
        ?>
</th>
					<th style="width: 90px;"><?php 
        _e('User', 'rcp');
        ?>
</th>
					<th style="width: 150px;"><?php 
        _e('Subscription', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Date', 'rcp');
        ?>
</th>
					<th style="width: 90px;"><?php 
        _e('Amount', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Type', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Transaction ID', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Status', 'rcp');
        ?>
</th>
					<?php 
        do_action('rcp_payments_page_table_header');
        ?>
					<?php 
        if (current_user_can('rcp_manage_payments')) {
            ?>
						<th><?php 
            _e('Actions', 'rcp');
            ?>
</th>
					<?php 
        }
        ?>
				</tr>
			</thead>
			<tfoot>
				<tr>
					<th style="width: 40px;"><?php 
        _e('ID', 'rcp');
        ?>
</th>
					<th><?php 
        _e('User', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Subscription', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Date', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Amount', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Type', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Transaction ID', 'rcp');
        ?>
</th>
					<th><?php 
        _e('Status', 'rcp');
        ?>
</th>
					<?php 
        do_action('rcp_payments_page_table_footer');
        ?>
					<?php 
        if (current_user_can('rcp_manage_payments')) {
            ?>
						<th><?php 
            _e('Actions', 'rcp');
            ?>
</th>
					<?php 
        }
        ?>
				</tr>
			</tfoot>
			<tbody>
				<?php 
        if ($payments) {
            $i = 0;
            $total_earnings = 0;
            foreach ($payments as $payment) {
                $user = get_userdata($payment->user_id);
                ?>
							<tr class="rcp_payment <?php 
                if (rcp_is_odd($i)) {
                    echo 'alternate';
                }
                ?>
">
								<td><?php 
                echo absint($payment->id);
                ?>
</td>
								<td>
									<a href="<?php 
                echo esc_url(add_query_arg('user_id', $payment->user_id, menu_page_url('rcp-payments', false)));
                ?>
" title="<?php 
                _e('View payments by this user', 'rcp');
                ?>
">
										<?php 
                echo isset($user->display_name) ? esc_html($user->display_name) : '';
                ?>
									</a>
								</td>
								<td><?php 
                echo esc_html($payment->subscription);
                ?>
</td>
								<td><?php 
                echo esc_html($payment->date);
                ?>
</td>
								<td><?php 
                echo rcp_currency_filter($payment->amount);
                ?>
</td>
								<td><?php 
                echo esc_html($payment->payment_type);
                ?>
</td>
								<td><?php 
                echo $payment->transaction_id;
                ?>
</td>
								<td><?php 
                echo rcp_get_payment_status_label($payment);
                ?>
</td>
								<?php 
                do_action('rcp_payments_page_table_column', $payment->id);
                ?>
								<?php 
                if (current_user_can('rcp_manage_payments')) {
                    ?>
									<td>
										<a href="<?php 
                    echo rcp_get_pdf_download_url($payment->id);
                    ?>
" class="rcp-payment-invoice"><?php 
                    _e('Download Invoice', 'rcp');
                    ?>
</a>
										<span>&nbsp;|&nbsp;</span>
										<a href="<?php 
                    echo esc_url(add_query_arg(array('payment_id' => $payment->id, 'view' => 'edit-payment'), admin_url('admin.php?page=rcp-payments')));
                    ?>
" class="rcp-edit-payment"><?php 
                    _e('Edit', 'rcp');
                    ?>
</a>
										<span>&nbsp;|&nbsp;</span>
										<a href="<?php 
                    echo wp_nonce_url(add_query_arg(array('payment_id' => $payment->id, 'rcp-action' => 'delete_payment'), admin_url('admin.php?page=rcp-payments')), 'rcp_delete_payment_nonce');
                    ?>
" class="rcp-delete-payment"><?php 
                    _e('Delete', 'rcp');
                    ?>
</a>
									</td>
								<?php 
                }
                ?>
							</tr>
						<?php 
                $i++;
                $total_earnings = $total_earnings + $payment->amount;
            }
        } else {
            ?>
					<tr><td colspan="8"><?php 
            _e('No payments recorded yet', 'rcp');
            ?>
</td></tr>
				<?php 
        }
        ?>
			</table>
			<?php 
        if ($total_pages > 1) {
            ?>
				<div class="tablenav">
					<div class="tablenav-pages alignright">
						<?php 
            $base = 'admin.php?' . remove_query_arg('p', $_SERVER['QUERY_STRING']) . '%_%';
            echo paginate_links(array('base' => $base, 'format' => '&p=%#%', 'prev_text' => __('&laquo; Previous'), 'next_text' => __('Next &raquo;'), 'total' => $total_pages, 'current' => $page, 'end_size' => 1, 'mid_size' => 5));
            ?>
				    </div>
				</div><!--end .tablenav-->
			<?php 
        }
        ?>
			<?php 
        do_action('rcp_payments_page_bottom');
        ?>
		<?php 
    }
    ?>
	</div><!--end wrap-->
	<?php 
}
 /**
  * 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;
     }
 }
function rcp_filter_email_tags($message, $user_id, $display_name)
{
    $user = get_userdata($user_id);
    $site_name = stripslashes_deep(html_entity_decode(get_bloginfo('name'), ENT_COMPAT, 'UTF-8'));
    $rcp_payments = new RCP_Payments();
    $message = str_replace('%blogname%', $site_name, $message);
    $message = str_replace('%username%', $user->user_login, $message);
    $message = str_replace('%useremail%', $user->user_email, $message);
    $message = str_replace('%firstname%', html_entity_decode($user->user_firstname, ENT_COMPAT, 'UTF-8'), $message);
    $message = str_replace('%lastname%', html_entity_decode($user->user_lastname, ENT_COMPAT, 'UTF-8'), $message);
    $message = str_replace('%displayname%', html_entity_decode($display_name, ENT_COMPAT, 'UTF-8'), $message);
    $message = str_replace('%expiration%', rcp_get_expiration_date($user_id), $message);
    $message = str_replace('%subscription_name%', html_entity_decode(rcp_get_subscription($user_id), ENT_COMPAT, 'UTF-8'), $message);
    $message = str_replace('%subscription_key%', rcp_get_subscription_key($user_id), $message);
    $message = str_replace('%amount%', html_entity_decode(rcp_currency_filter($rcp_payments->last_payment_of_user($user_id)), ENT_COMPAT, 'UTF-8'), $message);
    return apply_filters('rcp_email_tags', $message, $user_id);
}
/**
 * Displays the earnings graph.
 *
 * @access  public
 * @since   1.8
*/
function rcp_earnings_graph()
{
    global $rcp_options, $wpdb;
    // Retrieve the queried dates
    $dates = rcp_get_report_dates();
    // Determine graph options
    switch ($dates['range']) {
        case 'today':
            $time_format = '%d/%b';
            $tick_size = 'hour';
            $day_by_day = true;
            break;
        case 'last_year':
            $time_format = '%b';
            $tick_size = 'month';
            $day_by_day = false;
            break;
        case 'this_year':
            $time_format = '%b';
            $tick_size = 'month';
            $day_by_day = false;
            break;
        case 'last_quarter':
            $time_format = '%b';
            $tick_size = 'month';
            $day_by_day = false;
            break;
        case 'this_quarter':
            $time_format = '%b';
            $tick_size = 'month';
            $day_by_day = false;
            break;
        case 'other':
            if ($dates['m_end'] - $dates['m_start'] >= 2) {
                $time_format = '%b';
                $tick_size = 'month';
                $day_by_day = false;
            } else {
                $time_format = '%d/%b';
                $tick_size = 'day';
                $day_by_day = true;
            }
            break;
        default:
            $time_format = '%d/%b';
            // Show days by default
            $tick_size = 'day';
            // Default graph interval
            $day_by_day = true;
            break;
    }
    $time_format = apply_filters('rcp_graph_timeformat', $time_format);
    $tick_size = apply_filters('rcp_graph_ticksize', $tick_size);
    $earnings = (double) 0.0;
    // Total earnings for time period shown
    $subscription = isset($_GET['subscription']) ? absint($_GET['subscription']) : false;
    $payments_db = new RCP_Payments();
    $args = array('subscription' => rcp_get_subscription_name($subscription), 'date' => array());
    ob_start();
    ?>
	<script type="text/javascript">
	   jQuery( document ).ready( function($) {
	   		$.plot(
	   			$("#rcp_earnings_graph"),
	   			[{
   					data: [
	   					<?php 
    if ($dates['range'] == 'this_week' || $dates['range'] == 'last_week') {
        //Day by day
        $day = $dates['day'];
        $day_end = $dates['day_end'];
        $month = $dates['m_start'];
        while ($day <= $day_end) {
            $args = array('date' => array('day' => $day, 'month' => $month, 'year' => $dates['year']), 'fields' => 'amount');
            $args['date'] = array('day' => $day, 'month' => $month, 'year' => $dates['year']);
            $payments = $payments_db->get_earnings($args);
            $earnings += $payments;
            $date = mktime(0, 0, 0, $month, $day, $dates['year']);
            ?>
								[<?php 
            echo $date * 1000;
            ?>
, <?php 
            echo $payments;
            ?>
],
								<?php 
            $day++;
        }
    } else {
        $y = $dates['year'];
        while ($y <= $dates['year_end']) {
            if ($dates['year'] == $dates['year_end']) {
                $month_start = $dates['m_start'];
                $month_end = $dates['m_end'];
            } elseif ($y == $dates['year']) {
                $month_start = $dates['m_start'];
                $month_end = 12;
            } else {
                $month_start = 1;
                $month_end = 12;
            }
            $i = $month_start;
            while ($i <= $month_end) {
                if ($day_by_day) {
                    $num_of_days = cal_days_in_month(CAL_GREGORIAN, $i, $y);
                    $d = 1;
                    while ($d <= $num_of_days) {
                        $args['date'] = array('day' => $d, 'month' => $i, 'year' => $y);
                        $payments = $payments_db->get_earnings($args);
                        $earnings += $payments;
                        $date = mktime(0, 0, 0, $i, $d, $y);
                        ?>
											[<?php 
                        echo $date * 1000;
                        ?>
, <?php 
                        echo $payments;
                        ?>
],
										<?php 
                        $d++;
                    }
                } else {
                    $args['date'] = array('day' => null, 'month' => $i, 'year' => $y);
                    $payments = $payments_db->get_earnings($args);
                    $earnings += $payments;
                    $date = mktime(0, 0, 0, $i, 1, $y);
                    ?>
										[<?php 
                    echo $date * 1000;
                    ?>
, <?php 
                    echo $payments;
                    ?>
],
									<?php 
                }
                $i++;
            }
            $y++;
        }
    }
    ?>
,
	   				],
	   				yaxis: 2,
   					label: "<?php 
    _e('Earnings', 'rcp');
    ?>
",
   					id: 'sales'
   				}],
	   		{
               	series: {
                   lines: { show: true },
                   points: { show: true }
            	},
            	grid: {
           			show: true,
					aboveData: false,
					color: '#ccc',
					backgroundColor: '#fff',
					borderWidth: 2,
					borderColor: '#ccc',
					clickable: false,
					hoverable: true
           		},
            	xaxis: {
	   				mode: "time",
	   				timeFormat: "<?php 
    echo $time_format;
    ?>
",
	   				minTickSize: [1, "<?php 
    echo $tick_size;
    ?>
"]
   				},
   				yaxis: {
   					min: 0,
   					minTickSize: 1,
   					tickDecimals: 0
   				}

            });

			function rcp_flot_tooltip(x, y, contents) {
		        $('<div id="rcp-flot-tooltip">' + contents + '</div>').css( {
		            position: 'absolute',
		            display: 'none',
		            top: y + 5,
		            left: x + 5,
		            border: '1px solid #fdd',
		            padding: '2px',
		            'background-color': '#fee',
		            opacity: 0.80
		        }).appendTo("body").fadeIn(200);
		    }

		    var previousPoint = null;
		    $("#rcp_earnings_graph").bind("plothover", function (event, pos, item) {
	            if (item) {
	                if (previousPoint != item.dataIndex) {
	                    previousPoint = item.dataIndex;
	                    $("#rcp-flot-tooltip").remove();
	                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);
                    	if( rcp_vars.currency_pos == 'before' ) {
							rcp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + rcp_vars.currency_sign + y );
                    	} else {
							rcp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + y + rcp_vars.currency_sign );
                    	}
	                }
	            } else {
	                $("#rcp-flot-tooltip").remove();
	                previousPoint = null;
	            }
		    });
	   });
    </script>
	<h2><?php 
    _e('Earnings Report', 'rcp');
    ?>
</h2>
	<div class="metabox-holder" style="padding-top: 0;">
		<div class="postbox">
			<div class="inside">
				<?php 
    rcp_reports_graph_controls();
    ?>
				<div id="rcp_earnings_graph" style="height: 300px;"></div>
				<p class="rcp_graph_totals"><strong><?php 
    _e('Total earnings for period shown: ', 'rcp');
    echo rcp_currency_filter(number_format_i18n($earnings, 2));
    ?>
</strong></p>
			</div>
		</div>
	</div>
	<?php 
    echo ob_get_clean();
}
Example #17
0
function rcp_check_ipn()
{
    global $rcp_options;
    if (!class_exists('IpnListener')) {
        // instantiate the IpnListener class
        include RCP_PLUGIN_DIR . 'includes/gateways/paypal/ipnlistener.php';
    }
    $listener = new IpnListener();
    if (isset($rcp_options['sandbox'])) {
        $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) {
        //exit(0);
    }
    /*
    The processIpn() method returned true if the IPN was "VERIFIED" and false if it
    was "INVALID".
    */
    if ($verified || isset($_POST['verification_override']) || (isset($rcp_options['sandbox']) || isset($rcp_options['disable_ipn_verify']))) {
        $posted = apply_filters('rcp_ipn_post', $_POST);
        // allow $_POST to be modified
        $user_id = $posted['custom'];
        $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_id = rcp_get_subscription_id($user_id);
        $subscription_price = number_format((double) rcp_get_subscription_price(rcp_get_subscription_id($user_id)), 2);
        $user_data = get_userdata($user_id);
        if (!$user_data || !$subscription_id) {
            return;
        }
        if (!rcp_get_subscription_details($subscription_id)) {
            return;
        }
        // setup the payment info in an array for storage
        $payment_data = array('date' => date('Y-m-d g:i:s', strtotime($posted['payment_date'])), '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);
                return;
                // this IPN request has already been processed
            }
            /* do some quick checks to make sure all necessary data validates */
            if ($amount < $subscription_price && $amount2 < $subscription_price) {
                /*
                				// the subscription price doesn't match, so lets check to see if it matches with a discount code
                				if( ! rcp_check_paypal_return_price_after_discount( $subscription_price, $amount, $amount2, $user_id ) ) {
                	$log_data = array(
                					    'post_title'    => __( 'Price Mismatch', 'rcp' ),
                					    'post_content'  =>  sprintf( __( 'The price in an IPN request did not match the subscription price. 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 );
                	//return;
                				}
                */
            }
            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);
                return;
            }
        }
        if (isset($rcp_options['email_ipn_reports'])) {
            wp_mail(get_bloginfo('admin_email'), __('IPN report', 'rcp'), $listener->getTextReport());
        }
        if (rcp_get_subscription_key($user_id) != $subscription_key) {
            // the subscription key is invalid
            $log_data = array('post_title' => __('Subscription Key Mismatch', 'rcp'), 'post_content' => sprintf(__('The subscription key in an IPN request did not match the subscription key recorded for the user. 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);
            return;
        }
        /* 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']);
                // set the user's status to active
                rcp_set_status($user_id, 'active');
                if (!isset($rcp_options['disable_new_user_notices'])) {
                    wp_new_user_notification($user_id);
                }
                // send welcome email
                rcp_email_subscription_status($user_id, 'active');
                update_user_meta($user_id, 'rcp_recurring', 'yes');
                do_action('rcp_ipn_subscr_signup', $user_id);
                break;
            case "subscr_payment":
                // when a user makes a recurring payment
                // record this payment in the database
                $rcp_payments->insert($payment_data);
                $subscription = rcp_get_subscription_details(rcp_get_subscription_id($user_id));
                // update the user's expiration to correspond with the new payment
                $member_new_expiration = date('Y-m-d H:i:s', strtotime('+' . $subscription->duration . ' ' . $subscription->duration_unit . ' 23:59:59'));
                rcp_set_expiration_date($user_id, $member_new_expiration);
                update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']);
                // make sure the user's status is active
                rcp_set_status($user_id, 'active');
                update_user_meta($user_id, 'rcp_recurring', 'yes');
                delete_user_meta($user_id, '_rcp_expired_email_sent');
                do_action('rcp_ipn_subscr_payment', $user_id);
                break;
            case "subscr_cancel":
                // user is marked as cancelled but retains access until end of term
                rcp_set_status($user_id, 'cancelled');
                // set the use to no longer be recurring
                delete_user_meta($user_id, 'rcp_recurring');
                delete_user_meta($user_id, 'rcp_paypal_subscriber');
                // send sub cancelled email
                rcp_email_subscription_status($user_id, 'cancelled');
                do_action('rcp_ipn_subscr_cancel', $user_id);
                break;
            case "subscr_failed":
                do_action('rcp_ipn_subscr_failed');
                break;
            case "subscr_eot":
                // user's subscription has reach the end of its term
                // set the use to no longer be recurring
                delete_user_meta($user_id, 'rcp_recurring');
                if ('cancelled' !== rcp_get_status($user_id)) {
                    rcp_set_status($user_id, 'expired');
                    // send expired email
                    rcp_email_subscription_status($user_id, 'expired');
                }
                do_action('rcp_ipn_subscr_eot', $user_id);
                break;
            case "cart":
                return;
                // get out of here
            // get out of here
            case "express_checkout":
                return;
                // get out of here
            // get out of here
            case "web_accept":
                switch (strtolower($payment_status)) {
                    case 'completed':
                        if (isset($_POST['verification_override'])) {
                            // this is a method for providing a new expiration if it doesn't exist
                            $subscription = rcp_get_subscription_details_by_name($payment_data['subscription']);
                            // update the user's expiration to correspond with the new payment
                            $member_new_expiration = date('Y-m-d H:i:s', strtotime('+' . $subscription->duration . ' ' . $subscription->duration_unit . ' 23:59:59'));
                            rcp_set_expiration_date($user_id, $member_new_expiration);
                        }
                        // set this user to active
                        rcp_set_status($user_id, 'active');
                        $rcp_payments->insert($payment_data);
                        rcp_email_subscription_status($user_id, 'active');
                        if (!isset($rcp_options['disable_new_user_notices'])) {
                            // send welcome email here
                            wp_new_user_notification($user_id);
                        }
                        delete_user_meta($user_id, '_rcp_expired_email_sent');
                        break;
                    case 'denied':
                    case 'expired':
                    case 'failed':
                    case 'voided':
                        rcp_set_status($user_id, 'cancelled');
                        // send cancelled email here
                        break;
                }
                break;
            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());
        }
    }
}
 public function process_webhooks()
 {
     if (!isset($_GET['listener']) || strtolower($_GET['listener']) != 'stripe') {
         return;
     }
     // Ensure listener URL is not cached by W3TC
     define('DONOTCACHEPAGE', true);
     \Stripe\Stripe::setApiKey($this->secret_key);
     // retrieve the request's body and parse it as JSON
     $body = @file_get_contents('php://input');
     $event_json_id = json_decode($body);
     // for extra security, retrieve from the Stripe API
     if (isset($event_json_id->id)) {
         $rcp_payments = new RCP_Payments();
         $event_id = $event_json_id->id;
         try {
             $event = \Stripe\Event::retrieve($event_id);
             $invoice = $event->data->object;
             if (empty($invoice->customer)) {
                 die('no customer attached');
             }
             // retrieve the customer who made this payment (only for subscriptions)
             $user = rcp_get_member_id_from_profile_id($invoice->customer);
             if (empty($user)) {
                 // Grab the customer ID from the old meta keys
                 global $wpdb;
                 $user = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '_rcp_stripe_user_id' AND meta_value = %s LIMIT 1", $invoice->customer));
             }
             if (empty($user)) {
                 die('no user ID found');
             }
             $member = new RCP_Member($user);
             // check to confirm this is a stripe subscriber
             if ($member) {
                 // successful payment
                 if ($event->type == 'charge.succeeded') {
                     if (!$member->get_subscription_id()) {
                         die('no subscription ID for member');
                     }
                     $payment_data = array('date' => date('Y-m-d g:i:s', $event->created), 'subscription' => $member->get_subscription_name(), 'payment_type' => 'Credit Card', 'subscription_key' => $member->get_subscription_key(), 'amount' => $invoice->amount / 100, 'user_id' => $member->ID, 'transaction_id' => $invoice->id);
                     if (!rcp_check_for_existing_payment($payment_data['payment_type'], $payment_data['date'], $payment_data['subscription_key'])) {
                         // record this payment if it hasn't been recorded yet
                         $rcp_payments->insert($payment_data);
                         $member->renew($member->is_recurring());
                         do_action('rcp_stripe_charge_succeeded', $user, $payment_data);
                         die('rcp_stripe_charge_succeeded action fired successfully');
                     } else {
                         die('duplicate payment found');
                     }
                 }
                 // failed payment
                 if ($event->type == 'charge.failed') {
                     do_action('rcp_stripe_charge_failed', $invoice);
                     die('rcp_stripe_charge_failed action fired successfully');
                 }
                 // Cancelled / failed subscription
                 if ($event->type == 'customer.subscription.deleted') {
                     $member->set_status('cancelled');
                     die('member cancelled successfully');
                 }
                 do_action('rcp_stripe_' . $event->type, $invoice);
             }
         } catch (Exception $e) {
             // something failed
             die('PHP exception: ' . $e->getMessage());
         }
         die('1');
     }
     die('no event ID found');
 }
function rcp_check_for_email_signup($payment_id, $args, $amount)
{
    global $rcp_options;
    $payments = new RCP_Payments();
    $last_payment = $payments->last_payment_of_user($args['user_id']);
    // Check if this is the subscribers first payment. We only add to list on the first one
    if ($last_payment && $layment_payment->id != $payment_id) {
        return;
    }
    $user_object = get_userdata($args['user_id']);
    $email = $user_object->user_email;
    rcp_subscribe_email($email);
    update_user_meta($user_id, 'rcp_subscribed_to_mailchimp', 'yes');
}
/**
 * Retrieve the payments for a specific user
 *
 * @since       v1.5
 * @access      public
 * @param       $user_id INT the ID of the user to get payments for
 * @return      array
*/
function rcp_get_user_payments( $user_id = 0 ) {

	if( empty( $user_id ) ) {
		$user_id = get_current_user_id();
	}

	$payments = new RCP_Payments;
	return $payments->get_payments( array( 'user_id' => $user_id ) );
}
/**
 * Retrieves the payment status label for a payment
 *
 * @since 2.1
 * @return string
 */
function rcp_get_payment_status_label( $payment ) {

	if( is_numeric( $payment ) ) {
		$payments = new RCP_Payments();
		$payment  = $payments->get_payment( $payment );
	}

	if( ! $payment ) {
		return '';
	}

	$label  = '';
	$status = ! empty( $payment->status ) ? $payment->status : 'complete';

	switch( $status ) {

		case 'pending' :

			$label = __( 'Pending', 'rcp' );

			break;

		case 'refunded' :

			$label = __( 'Refunded', 'rcp' );

			break;

		case 'complete' :
		default :

			$label = __( 'Complete', 'rcp' );

			break;
	}

	return apply_filters( 'rcp_payment_status_label', $label, $status, $payment );

}