function pw_edd_give_subscription_on_purchase($payment_id)
{
    $user_id = edd_get_payment_user_id($payment_id);
    if (empty($user_id) || $user_id < 1) {
        return;
    }
    if (!class_exists('EDD_Recurring_Customer')) {
        return;
    }
    $customer = new EDD_Recurring_Customer();
    $customer->set_as_subscriber($user_id);
    $customer->set_customer_payment_id($payment_id);
    $customer->set_customer_status($user_id, 'active');
    $customer->set_customer_expiration($user_id, strtotime('+1 year'));
}
 function eddsss_subscription_status_shortcode()
 {
     if (!is_user_logged_in() || !class_exists('EDD_Recurring_Customer')) {
         return;
     }
     $user_id = get_current_user_id();
     $status = EDD_Recurring_Customer::get_customer_status($user_id);
     if ($status !== 'active' && $status !== 'cancelled' && $status !== 'expired') {
         return;
     }
     // Check if expired and set to expired if so
     if (EDD_Recurring_Customer::is_customer_expired($user_id)) {
         $status = 'expired';
         EDD_Recurring_Customer::set_customer_status($user_id, $status);
     }
     $message = '';
     switch ($status) {
         case 'active':
             $message = sprintf(__('Your subscription is active and will renew on %s.', 'edd'), date_i18n(get_option('date_format'), EDD_Recurring_Customer::get_customer_expiration($user_id)));
             break;
         case 'cancelled':
             $message = sprintf(__('Your subscription is cancelled and expires on %s.', 'edd'), date_i18n(get_option('date_format'), EDD_Recurring_Customer::get_customer_expiration($user_id)));
             break;
         case 'expired':
             $message = sprintf(__('Your subscription expired on %s.', 'edd'), date_i18n(get_option('date_format'), EDD_Recurring_Customer::get_customer_expiration($user_id)));
             break;
     }
     if (!empty($message)) {
         return '<div id="edd-subscription-status" class="' . esc_attr($status) . '">' . $message . '</div>';
     }
 }
function pw_edd_recurring_limit_one_subscription($valid_data, $post_data)
{
    if (!class_exists('EDD_Recurring_Customer')) {
        return;
    }
    if (!is_user_logged_in()) {
        return;
    }
    $purchase_data = array('downloads' => edd_get_cart_contents());
    if (EDD_Recurring_Customer::is_customer_active() && EDD_Recurring()->is_purchase_recurring($purchase_data)) {
        edd_set_error('edd-one-subscription', __('You already have an active subscription so may not purchase a second one.', 'edd'));
    }
}
function ck_edd_user_download_button_recurring($purchase_form, $args)
{
    if (!class_exists('EDD_Recurring_Customer')) {
        return $purchase_form;
    }
    if (!EDD_Recurring_Customer::is_customer_active(get_current_user_id())) {
        return $purchase_form;
    }
    if (!is_user_logged_in()) {
        return $purchase_form;
    }
    $download_id = (string) $args['download_id'];
    $current_user_id = get_current_user_id();
    // If the user has purchased this item, itterate through their purchases to get the specific
    // purchase data and pull out the key and email associated with it. This is necessary for the
    // generation of the download link
    if (edd_has_user_purchased($current_user_id, $download_id, $variable_price_id = null)) {
        $user_purchases = edd_get_users_purchases($current_user_id, -1, false, 'complete');
        foreach ($user_purchases as $purchase) {
            $cart_items = edd_get_payment_meta_cart_details($purchase->ID);
            $item_ids = wp_list_pluck($cart_items, 'id');
            if (in_array($download_id, $item_ids)) {
                $email = edd_get_payment_user_email($purchase->ID);
                $payment_key = edd_get_payment_key($purchase->ID);
            }
        }
        // Attempt to get the file data associated with this download
        $download_data = edd_get_download_files($download_id, null);
        if ($download_data) {
            // Setup the style and colors associated with the settings
            global $edd_options;
            $style = isset($edd_options['button_style']) ? $edd_options['button_style'] : 'button';
            $color = isset($edd_options['checkout_color']) ? $edd_options['checkout_color'] : 'blue';
            $new_purchase_form = '';
            foreach ($download_data as $filekey => $file) {
                // Generate the file URL and then make a link to it
                $file_url = edd_get_download_file_url($payment_key, $email, $filekey, $download_id, null);
                $new_purchase_form .= '<a href="' . $file_url . '" class="' . $style . ' ' . $color . ' edd-submit"><span class="edd-add-to-cart-label">Download ' . $file['name'] . '</span></a>&nbsp;';
            }
        }
        // As long as we ended up with links to show, use them.
        if (!empty($new_purchase_form)) {
            $purchase_form = '<h4>' . __('You already own this product. Download it now:', 'edd') . '</h4>' . $new_purchase_form;
        }
    }
    return $purchase_form;
}
 /**
  * Setup final data
  *
  * @access      private
  * @since       1.0
  * @return      array
  */
 function reports_data()
 {
     global $wpdb;
     $reports_data = array();
     $subscribers = $this->query();
     if (!empty($subscribers->results)) {
         foreach ($subscribers->results as $subscriber) {
             $expiration = EDD_Recurring_Customer::get_customer_expiration($subscriber->ID);
             $exp_date = !empty($expiration) ? date(get_option('date_format'), $expiration) : '';
             $status = EDD_Recurring_Customer::get_customer_status($subscriber->ID);
             $status = !empty($status) ? $status : __('none', 'edd-recurring');
             $recurring_id = EDD_Recurring_Customer::get_customer_id($subscriber->ID);
             $recurring_id = !empty($recurring_id) ? $recurring_id : __('none', 'edd-recurring');
             $reports_data[] = array('ID' => $subscriber->ID, 'username' => $subscriber->user_login, 'status' => $status, 'expiration' => $exp_date, 'recurring_id' => $recurring_id);
         }
     }
     return $reports_data;
 }
 /**
  * Displays a payment update form
  *
  * @since  x.x
  * @return string
  */
 public function update_payment_form()
 {
     global $user_ID;
     if (!is_user_logged_in()) {
         return;
     }
     if (!EDD_Recurring_Customer::is_customer_active($user_ID)) {
         return;
     }
     if ('cancelled' === EDD_Recurring_Customer::get_customer_status($user_ID)) {
         return;
     }
     // Gateways can choose to show the form or not by using this filter
     $show_cc_form = apply_filters('edd_recurring_customer_can_update_card', false, $user_ID);
     if (!$show_cc_form) {
         $form_fields = array();
         $form_fields['cc_number'] = array('type' => 'text', 'options' => array('name' => 'edd-recurring-card-number', 'label' => __('Credit Card Number', 'edd-recurring'), 'placeholder' => __('Credit Card Number', 'edd-recurring'), 'autocomplete' => false));
         $form_fields['cc_name'] = array('type' => 'text', 'options' => array('name' => 'edd-recurring-card-name', 'label' => __('Name on Card', 'edd-recurring'), 'placeholder' => __('Name on Card', 'edd-recurring'), 'autocomplete' => true));
         $form_fields['cvc_number'] = array('type' => 'text', 'options' => array('name' => 'edd-recurring-cvc-number', 'class' => 'small-text', 'label' => __('CVC Number', 'edd-recurring'), 'placeholder' => __('###', 'edd-recurring'), 'autocomplete' => false));
         $form_fields['exp_head'] = array('type' => 'legend', 'options' => array('text' => __('Card Expiration', 'edd-recurring')));
         $form_fields['exp_month'] = array('type' => 'month_dropdown');
         $form_fields['exp_year'] = array('type' => 'year_dropdown', 'number_of_years' => 10);
         $elements = apply_filters('edd_recurring_update_form_elements', $form_fields, $user_ID);
     }
     $form_output = '';
     if (isset($_GET['updated']) && $_GET['updated'] == true && !edd_get_errors()) {
         $form_output = '<p class="edd_success"><strong>' . __('Success', 'edd') . ':</strong> ' . __('Your profile has been edited successfully.', 'edd') . '</p>';
     }
     $form_output .= '<div id="edd-recurring-update-wrapper">';
     $form_output .= '<form action="' . remove_query_arg('updated', edd_get_current_page_url()) . '" id="edd-recurring-form" method="POST">';
     $form_input_html = '';
     if (!$show_cc_form) {
         // Iterate through all the form elements, and add them to the HTML
         foreach ($elements as $element) {
             switch ($element['type']) {
                 case 'month_dropdown':
                     $form_input_html .= EDD()->html->{$element}['type']();
                     break;
                 case 'year_dropdown':
                     $form_input_html .= EDD()->html->{$element}['type']('edd-recurring-exp-year', null, 0, $element['number_of_years']);
                     break;
                 case 'legend':
                     $form_input_html .= '<legend>' . $element['options']['text'] . '</legend>';
                     break;
                 default:
                     $form_input_html .= EDD()->html->{$element}['type']($element['options']);
                     $form_input_html .= '<br />';
                     break;
             }
         }
     }
     ob_start();
     edd_print_errors();
     $form_output .= ob_get_clean();
     $form_output .= apply_filters('edd_recurring_update_form_html', $form_input_html, $user_ID);
     $recurring_gateway = apply_filters('edd_recurring_update_gateway', '', $user_ID);
     $form_output .= '<input name="edd-recurring-update-gateway" type="hidden" value="' . $recurring_gateway . '" />';
     $form_output .= wp_nonce_field('update-payment', 'edd_recurring_update_nonce', true, false);
     $form_output .= '<input type="hidden" name="edd_action" value="recurring_update_payment" />';
     $form_output .= '<input type="submit" name="edd-recurring-update-submit" id="edd-recurring-update-submit" value="' . esc_attr(__('Update Payment', 'edd-recurring')) . '" />';
     $form_output .= '</form>';
     $form_output .= '</div>';
     return '<div id="edd_checkout_form_wrap">' . $form_output . '</div>';
 }
/**
 * Listen for Stripe events, primarily recurring payments
 *
 * @access      public
 * @since       1.5
 * @return      void
 */
function edds_stripe_event_listener()
{
    if (!class_exists('EDD_Recurring')) {
        return;
    }
    if (isset($_GET['edd-listener']) && $_GET['edd-listener'] == 'stripe') {
        global $edd_options;
        if (!class_exists('Stripe')) {
            require_once EDDS_PLUGIN_DIR . '/Stripe/Stripe.php';
        }
        $secret_key = edd_is_test_mode() ? trim($edd_options['test_secret_key']) : trim($edd_options['live_secret_key']);
        Stripe::setApiKey($secret_key);
        // retrieve the request's body and parse it as JSON
        $body = @file_get_contents('php://input');
        $event_json = json_decode($body);
        // for extra security, retrieve from the Stripe API
        $event_id = $event_json->id;
        if (isset($event_json->id)) {
            status_header(200);
            $event = Stripe_Event::retrieve($event_json->id);
            $invoice = $event->data->object;
            switch ($event->type) {
                case 'invoice.payment_succeeded':
                    // Process a subscription payment
                    // retrieve the customer who made this payment (only for subscriptions)
                    $user_id = EDD_Recurring_Customer::get_user_id_by_customer_id($invoice->customer);
                    // retrieve the customer ID from WP database
                    $customer_id = EDD_Recurring_Customer::get_customer_id($user_id);
                    // check to confirm this is a stripe subscriber
                    if ($user_id && $customer_id) {
                        $cu = Stripe_Customer::retrieve($customer_id);
                        // Get all subscriptions of this customer
                        $plans = $cu->subscriptions->data;
                        $subscriptions = wp_list_pluck($plans, 'plan');
                        $subscription_ids = !empty($subscriptions) ? wp_list_pluck($subscriptions, 'id') : array();
                        // Make sure this charge is for the user's subscription
                        if (!empty($subscription_ids) && !in_array($invoice->lines->data[0]->plan->id, $subscription_ids)) {
                            die('-3');
                        }
                        // Retrieve the original payment details
                        $parent_payment_id = EDD_Recurring_Customer::get_customer_payment_id($user_id);
                        if (false !== get_transient('_edd_recurring_payment_' . $parent_payment_id)) {
                            die('2');
                            // This is the initial payment
                        }
                        try {
                            // Store the payment
                            EDD_Recurring()->record_subscription_payment($parent_payment_id, $invoice->total / 100, $invoice->charge);
                            // Set the customer's status to active
                            EDD_Recurring_Customer::set_customer_status($user_id, 'active');
                            // Calculate the customer's new expiration date
                            $new_expiration = EDD_Recurring_Customer::calc_user_expiration($user_id, $parent_payment_id);
                            // Set the customer's new expiration date
                            EDD_Recurring_Customer::set_customer_expiration($user_id, $new_expiration);
                        } catch (Exception $e) {
                            die('3');
                            // Something not as expected
                        }
                    }
                    break;
                case 'customer.subscription.deleted':
                    // Process a cancellation
                    // retrieve the customer who made this payment (only for subscriptions)
                    $user_id = EDD_Recurring_Customer::get_user_id_by_customer_id($invoice->customer);
                    $parent_payment_id = EDD_Recurring_Customer::get_customer_payment_id($user_id);
                    // Set the customer's status to active
                    EDD_Recurring_Customer::set_customer_status($user_id, 'cancelled');
                    edd_update_payment_status($parent_payment_id, 'cancelled');
                    break;
            }
            do_action('edds_stripe_event_' . $event->type, $event);
            die('1');
            // Completed successfully
        } else {
            status_header(500);
            die('-1');
            // Failed
        }
        die('-2');
        // Failed
    }
}
 /**
  * Check if user has access to content
  *
  * @since  2.2.7
  * @return bool
  */
 public function can_access_content($has_access, $user_id, $restricted_to)
 {
     if ($has_access && is_array($restricted_to)) {
         foreach ($restricted_to as $item) {
             if (get_post_meta(get_the_ID(), '_edd_cr_active_only', true)) {
                 if (!EDD_Recurring_Customer::is_customer_active($user_id)) {
                     $has_access = false;
                     break;
                 }
             }
         }
     }
     return $has_access;
 }
 /**
  * Processes the "end of term (eot)" IPN notice
  *
  * @since  1.0
  * @return void
  */
 public static function process_paypal_subscr_eot($ipn_data)
 {
     $user_id = edd_get_payment_user_id($ipn_data['custom']);
     // set the customer status
     EDD_Recurring_Customer::set_customer_status($user_id, 'expired');
 }
 public static function create_payment($data)
 {
     if (wp_verify_nonce($data['edd_create_payment_nonce'], 'edd_create_payment_nonce')) {
         global $edd_options;
         if (empty($data['downloads'][0]['id'])) {
             wp_die(sprintf(__('Please select at least one %s to add to the payment.', 'edd-manual-purchases'), edd_get_label_singular()));
         }
         $user = strip_tags(trim($data['user']));
         if (empty($user)) {
             wp_die(__('Please enter a username, user ID, or email for the customer this payment belongs to.', 'edd-manual-purchases'));
         }
         if (is_numeric($user)) {
             $user = get_userdata($user);
         } elseif (is_email($user)) {
             $user = get_user_by('email', $user);
         } elseif (is_string($user)) {
             $user = get_user_by('login', $user);
         } else {
             return;
         }
         // no user assigned
         $user_id = $user ? $user->ID : 0;
         $email = $user ? $user->user_email : strip_tags(trim($data['user']));
         if (isset($data['first'])) {
             $user_first = sanitize_text_field($data['first']);
         } else {
             $user_first = $user ? $user->first_name : '';
         }
         if (isset($data['last'])) {
             $user_last = sanitize_text_field($data['last']);
         } else {
             $user_last = $user ? $user->last_name : '';
         }
         $user_info = array('id' => $user_id, 'email' => $email, 'first_name' => $user_first, 'last_name' => $user_last, 'discount' => 'none');
         $price = !empty($data['amount']) ? edd_sanitize_amount(strip_tags(trim($data['amount']))) : false;
         $cart_details = array();
         $total = 0;
         foreach ($data['downloads'] as $key => $download) {
             // calculate total purchase cost
             if (isset($download['options'])) {
                 $prices = get_post_meta($download['id'], 'edd_variable_prices', true);
                 $price_key = $download['options']['price_id'];
                 $item_price = $prices[$price_key]['amount'];
             } else {
                 $item_price = edd_get_download_price($download['id']);
             }
             $cart_details[$key] = array('name' => get_the_title($download['id']), 'id' => $download['id'], 'item_number' => $download, 'price' => $price ? $price : $item_price, 'subtotal' => $price ? $price : $item_price, 'quantity' => 1, 'tax' => 0);
             $total += $item_price;
         }
         // assign total to the price given, if any
         if ($price) {
             $total = $price;
         }
         $date = !empty($data['date']) ? date('Y-m-d H:i:s', strtotime(strip_tags(trim($data['date'])))) : false;
         if (!$date) {
             $date = date('Y-m-d H:i:s', current_time('timestamp'));
         }
         if (strtotime($date, time()) > time()) {
             $date = date('Y-m-d H:i:s', current_time('timestamp'));
         }
         $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'pending';
         $tax = !empty($_POST['tax']) ? edd_sanitize_amount(sanitize_text_field($_POST['tax'])) : 0;
         $purchase_data = array('price' => edd_sanitize_amount($total), 'tax' => $tax, 'post_date' => $date, 'purchase_key' => strtolower(md5(uniqid())), 'user_email' => $email, 'user_info' => $user_info, 'currency' => edd_get_currency(), 'downloads' => $data['downloads'], 'cart_details' => $cart_details, 'status' => 'pending');
         $payment_id = edd_insert_payment($purchase_data);
         edd_update_payment_meta($payment_id, '_edd_payment_tax', $tax);
         if (empty($data['receipt']) || $data['receipt'] != '1') {
             remove_action('edd_complete_purchase', 'edd_trigger_purchase_receipt', 999);
         }
         if (!empty($data['expiration']) && class_exists('EDD_Recurring_Customer') && $user_id > 0) {
             $expiration = strtotime($data['expiration'] . ' 23:59:59');
             EDD_Recurring_Customer::set_as_subscriber($user_id);
             EDD_Recurring_Customer::set_customer_payment_id($user_id, $payment_id);
             EDD_Recurring_Customer::set_customer_status($user_id, 'active');
             EDD_Recurring_Customer::set_customer_expiration($user_id, $expiration);
         }
         if (!empty($data['shipped'])) {
             update_post_meta($payment_id, '_edd_payment_shipping_status', '2');
         }
         // increase stats and log earnings
         edd_update_payment_status($payment_id, $status);
         wp_redirect(admin_url('edit.php?post_type=download&page=edd-payment-history&edd-message=payment_created'));
         exit;
     }
 }