/**
 * Create a log for preapproval payments
 *
 * @since Astoundify Crowdfunding 0.1-alpha
 *
 * @param int $payment_id the ID number of the payment
 * @param string $new_status the status of the payment, probably "publish"
 * @param string $old_status the status of the payment prior to being marked as "complete", probably "pending"
 * @return void
 */
function atcf_pending_purchase($payment_id, $new_status, $old_status)
{
    global $edd_logs;
    // Make sure that payments are only completed once
    if ($old_status == 'publish' || $old_status == 'complete') {
        return;
    }
    // Make sure the payment completion is only processed when new status is complete
    if ($new_status != 'preapproval' && $new_status != 'complete') {
        return;
    }
    if (edd_is_test_mode() && !apply_filters('edd_log_test_payment_stats', false)) {
        return;
    }
    $payment_data = edd_get_payment_meta($payment_id);
    $downloads = maybe_unserialize($payment_data['downloads']);
    $user_info = maybe_unserialize($payment_data['user_info']);
    if (!is_array($downloads)) {
        return;
    }
    foreach ($downloads as $download) {
        if (!isset($download['quantity'])) {
            $download['quantity'] = 1;
        }
        for ($i = 0; $i < $download['quantity']; $i++) {
            $edd_logs->insert_log(array('post_parent' => $download['id'], 'log_type' => 'preapproval'), array('payment_id' => $payment_id));
        }
    }
}
/**
 * Process the payment through Payza
 *
 * @param array   $purchase_data
 */
function edds_process_payza_payment($purchase_data)
{
    global $edd_options;
    // record the pending payment
    $payment_data = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => edd_get_currency(), 'downloads' => $purchase_data['downloads'], 'cart_details' => $purchase_data['cart_details'], 'user_info' => $purchase_data['user_info'], 'status' => 'pending');
    // Inserts a new payment
    $payment = edd_insert_payment($payment_data);
    if ($payment) {
        require_once 'payza.gateway.php';
        // Request details
        $merchant_id = trim($edd_options['payza_merchant_id']);
        $currency = edd_get_currency();
        $return_url = edd_get_success_page_url('?payment-confirmation=payza');
        $cancel_url = edd_get_failed_transaction_uri();
        $ipn_url = trailingslashit(home_url()) . '?edd-listener=PAYZA_IPN';
        // Create a new instance of the mb class
        $payza = new wp_payza_gateway($merchant_id, 'item', $currency, $return_url, $cancel_url, $ipn_url, edd_is_test_mode());
        // Get a new session ID
        $redirect_url = $payza->transaction($payment, $purchase_data['cart_details']);
        if ($redirect_url) {
            // Redirects the user
            wp_redirect($redirect_url);
            exit;
        } else {
            edd_send_back_to_checkout('?payment-mode=payza');
        }
    } else {
        edd_send_back_to_checkout('?payment-mode=payza');
    }
}
 /**
  * Get EDD details
  *
  * ## OPTIONS
  *
  * None. Returns basic info regarding your EDD instance.
  *
  * ## EXAMPLES
  *
  * wp edd details
  *
  * @access		public
  * @param		array $args
  * @param		array $assoc_args
  * @return		void
  */
 public function details($args, $assoc_args)
 {
     $symlink_file_downloads = edd_get_option('symlink_file_downloads', false);
     $purchase_page = edd_get_option('purchase_page', '');
     $success_page = edd_get_option('success_page', '');
     $failure_page = edd_get_option('failure_page', '');
     WP_CLI::line(sprintf(__('You are running EDD version: %s', 'easy-digital-downloads'), EDD_VERSION));
     WP_CLI::line("\n" . sprintf(__('Test mode is: %s', 'easy-digital-downloads'), edd_is_test_mode() ? __('Enabled', 'easy-digital-downloads') : __('Disabled', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Ajax is: %s', 'easy-digital-downloads'), edd_is_ajax_enabled() ? __('Enabled', 'easy-digital-downloads') : __('Disabled', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Guest checkouts are: %s', 'easy-digital-downloads'), edd_no_guest_checkout() ? __('Disabled', 'easy-digital-downloads') : __('Enabled', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Symlinks are: %s', 'easy-digital-downloads'), apply_filters('edd_symlink_file_downloads', isset($symlink_file_downloads)) && function_exists('symlink') ? __('Enabled', 'easy-digital-downloads') : __('Disabled', 'easy-digital-downloads')));
     WP_CLI::line("\n" . sprintf(__('Checkout page is: %s', 'easy-digital-downloads'), !edd_get_option('purchase_page', false) ? __('Valid', 'easy-digital-downloads') : __('Invalid', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Checkout URL is: %s', 'easy-digital-downloads'), !empty($purchase_page) ? get_permalink($purchase_page) : __('Undefined', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Success URL is: %s', 'easy-digital-downloads'), !empty($success_page) ? get_permalink($success_page) : __('Undefined', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Failure URL is: %s', 'easy-digital-downloads'), !empty($failure_page) ? get_permalink($failure_page) : __('Undefined', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Downloads slug is: %s', 'easy-digital-downloads'), defined('EDD_SLUG') ? '/' . EDD_SLUG : '/downloads'));
     WP_CLI::line("\n" . sprintf(__('Taxes are: %s', 'easy-digital-downloads'), edd_use_taxes() ? __('Enabled', 'easy-digital-downloads') : __('Disabled', 'easy-digital-downloads')));
     WP_CLI::line(sprintf(__('Tax rate is: %s', 'easy-digital-downloads'), edd_get_tax_rate() * 100 . '%'));
     $rates = edd_get_tax_rates();
     if (!empty($rates)) {
         foreach ($rates as $rate) {
             WP_CLI::line(sprintf(__('Country: %s, State: %s, Rate: %s', 'easy-digital-downloads'), $rate['country'], $rate['state'], $rate['rate']));
         }
     }
 }
 /**
  * Get the Export Data
  *
  * @access public
  * @since 1.4.4
  * @global object $wpdb Used to query the database using the WordPress
  *   Database API
  * @return array $data The data for the CSV file
  */
 public function get_data()
 {
     global $wpdb, $edd_options;
     $data = array();
     $payments = edd_get_payments(array('offset' => 0, 'number' => -1, 'mode' => edd_is_test_mode() ? 'test' : 'live', 'status' => isset($_POST['edd_export_payment_status']) ? $_POST['edd_export_payment_status'] : 'any', 'month' => isset($_POST['month']) ? absint($_POST['month']) : date('n'), 'year' => isset($_POST['year']) ? absint($_POST['year']) : date('Y')));
     foreach ($payments as $payment) {
         $payment_meta = edd_get_payment_meta($payment->ID);
         $user_info = edd_get_payment_meta_user_info($payment->ID);
         $downloads = edd_get_payment_meta_cart_details($payment->ID);
         $total = isset($payment_meta['amount']) ? $payment_meta['amount'] : 0.0;
         $user_id = isset($user_info['id']) && $user_info['id'] != -1 ? $user_info['id'] : $user_info['email'];
         $products = '';
         $skus = '';
         if ($downloads) {
             foreach ($downloads as $key => $download) {
                 // Download ID
                 $id = isset($payment_meta['cart_details']) ? $download['id'] : $download;
                 // If the download has variable prices, override the default price
                 $price_override = isset($payment_meta['cart_details']) ? $download['price'] : null;
                 $price = edd_get_download_final_price($id, $user_info, $price_override);
                 // Display the Downoad Name
                 $products .= get_the_title($id) . ' - ';
                 if (edd_use_skus()) {
                     $sku = edd_get_download_sku($id);
                     if (!empty($sku)) {
                         $skus .= $sku;
                     }
                 }
                 if (isset($downloads[$key]['item_number']) && isset($downloads[$key]['item_number']['options'])) {
                     $price_options = $downloads[$key]['item_number']['options'];
                     if (isset($price_options['price_id'])) {
                         $products .= edd_get_price_option_name($id, $price_options['price_id']) . ' - ';
                     }
                 }
                 $products .= html_entity_decode(edd_currency_filter($price));
                 if ($key != count($downloads) - 1) {
                     $products .= ' / ';
                     if (edd_use_skus()) {
                         $skus .= ' / ';
                     }
                 }
             }
         }
         if (is_numeric($user_id)) {
             $user = get_userdata($user_id);
         } else {
             $user = false;
         }
         $data[] = array('id' => $payment->ID, 'email' => $payment_meta['email'], 'first' => $user_info['first_name'], 'last' => $user_info['last_name'], 'products' => $products, 'skus' => $skus, 'amount' => html_entity_decode(edd_format_amount($total)), 'tax' => html_entity_decode(edd_get_payment_tax($payment->ID, $payment_meta)), 'discount' => isset($user_info['discount']) && $user_info['discount'] != 'none' ? $user_info['discount'] : __('none', 'edd'), 'gateway' => edd_get_gateway_admin_label(get_post_meta($payment->ID, '_edd_payment_gateway', true)), 'key' => $payment_meta['key'], 'date' => $payment->post_date, 'user' => $user ? $user->display_name : __('guest', 'edd'), 'status' => edd_get_payment_status($payment, true));
         if (!edd_use_skus()) {
             unset($data['skus']);
         }
     }
     $data = apply_filters('edd_export_get_data', $data);
     $data = apply_filters('edd_export_get_data_' . $this->export_type, $data);
     return $data;
 }
function pw_edd_process_payment($purchase_data)
{
    global $edd_options;
    /**********************************
     * set transaction mode
     **********************************/
    if (edd_is_test_mode()) {
        $paytm_redirect = 'https://pguat.paytm.com/oltp-web/processTransaction?';
    } else {
        if ($edd_options['paytm_select_mode'] == '1') {
            $paytm_redirect = 'https://secure.paytm.in/oltp-web/processTransaction?';
        } else {
            $paytm_redirect = 'https://pguat.paytm.com/oltp-web/processTransaction?';
        }
    }
    // check for any stored errors
    $errors = edd_get_errors();
    if (!$errors) {
        $purchase_summary = edd_get_purchase_summary($purchase_data);
        /****************************************
         * setup the payment details to be stored
         ****************************************/
        $payment = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => $edd_options['currency'], 'downloads' => $purchase_data['downloads'], 'gateway' => 'paytm', 'cart_details' => $purchase_data['cart_details'], 'user_info' => $purchase_data['user_info'], 'status' => 'pending');
        // record the pending payment
        $payment = edd_insert_payment($payment);
        $merchant_payment_confirmed = false;
        $secret_key = $edd_options['paytm_mer_access_key'];
        $params = array('REQUEST_TYPE' => 'DEFAULT', 'MID' => $edd_options['paytm_merchant_id'], 'TXN_AMOUNT' => $purchase_data['price'], 'CHANNEL_ID' => "WEB", 'INDUSTRY_TYPE_ID' => $edd_options['paytm_industry_type'], 'WEBSITE' => $edd_options['paytm_website_name'], 'CUST_ID' => $purchase_data['user_email'], 'ORDER_ID' => $purchase_data['purchase_key'], 'EMAIL' => $purchase_data['user_email']);
        if ($edd_options['paytm_callback'] == '1') {
            $params['CALLBACK_URL'] = get_site_url() . '/?edd-listener=PAYTM_IPN&payment_id=' . $payment;
        }
        $checksum = getChecksumFromArray($params, $secret_key);
        $params['CHECKSUMHASH'] = $checksum;
        foreach ($params as $key => $val) {
            $submit_Params .= trim($key) . '=' . trim(urlencode($val)) . '&';
        }
        $submit_Params = substr($submit_Params, 0, -1);
        $request = $paytm_redirect . $submit_Params;
        wp_redirect($request);
        exit;
    } else {
        $fail = true;
        // errors were detected
    }
    if ($fail !== false) {
        // if errors are present, send the user back to the purchase page so they can be corrected
        edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
    }
}
/**
 * Track number of purchases for each pledge amount.
 *
 * @since Astoundify Crowdfunding 0.9
 *
 * @param int $payment the ID number of the payment
 * @param array $payment_data The payment data for the cart
 * @return void
 */
function atcf_log_pledge_limit($payment_id, $new_status, $old_status)
{
    global $edd_logs;
    // Make sure that payments are only completed once
    if ($old_status != 'pending') {
        return;
    }
    // Make sure the payment completion is only processed when new status is complete
    if (in_array($new_status, array('refunded', 'failed', 'revoked', 'cancelled', 'abandoned'))) {
        return;
    }
    if (edd_is_test_mode() && !apply_filters('edd_log_test_payment_stats', false)) {
        return;
    }
    atcf_update_backer_count($payment_id, 'increase');
}
 private function load($fileName)
 {
     if (class_exists('Easy_Digital_Downloads')) {
         global $edd_options;
         if (edd_is_test_mode()) {
             $mode = 'yes';
         } else {
             $mode = 'no';
         }
         $this->config = array('acct1.UserName' => $mode == 'yes' ? $edd_options['epap_test_api_username'] : $edd_options['epap_live_api_username'], 'acct1.Password' => $mode == 'yes' ? $edd_options['epap_test_api_password'] : $edd_options['epap_live_api_password'], 'acct1.Signature' => $mode == 'yes' ? $edd_options['epap_test_api_signature'] : $edd_options['epap_live_api_signature'], 'acct1.AppId' => $mode == 'yes' ? $edd_options['epap_test_app_id'] : $edd_options['epap_live_app_id'], 'service.Binding' => 'SOAP', 'service.EndPoint' => $mode == 'yes' ? 'https://api-3t.sandbox.paypal.com/2.0/' : 'https://api-3t.paypal.com/2.0/', 'service.RedirectURL' => $mode == 'yes' ? 'https://sandbox.paypal.com/webscr&cmd=' : 'https://paypal.com/webscr&cmd=', 'service.DevCentralURL' => 'https://developer.paypal.com', 'http.ConnectionTimeOut' => '10', 'http.Retry' => '5', 'log.FileName' => 'PayPal.log', 'log.LogLevel' => 'INFO', 'log.LogEnabled' => 'true');
     } else {
         $this->config = @parse_ini_file($fileName);
     }
     if ($this->config == null || count($this->config) == 0) {
         throw new PPConfigurationException("Config file {$fileName} not found", "303");
     }
 }
/**
 * Log preapproved payment total for campaigns. 
 * 
 * @since 1.8.7
 *
 * @param int $payment the ID number of the payment
 * @param string $new_status
 * @param string $old_status
 * @return void
 */
function atcf_log_preapproval_payment_total($payment_id, $new_status, $old_status)
{
    global $edd_logs;
    // If we're in test mode, don't proceed unless expected.
    if (edd_is_test_mode() && !apply_filters('edd_log_test_payment_stats', false)) {
        return;
    }
    // Don't do anything if $new_status and $old_status are the same
    if ($new_status == $old_status) {
        return;
    }
    // If the status has become preapproved.
    if ('preapproval' == $new_status) {
        atcf_update_preapproval_total($payment_id, 'increase');
    } elseif ('preapproval' == $old_status) {
        atcf_update_preapproval_total($payment_id, 'decrease');
    }
}
/**
 * Get Users Purchases
 *
 * Retrieves a list of all purchases by a specific user.
 *
 * @access public
 * @since  1.0
 * @param  int|string $user   User ID or email address
 * @param  int $number        Number of purchases to retrieve
 *
 * @return array List of all user purchases
 */
function edd_get_users_purchases($user = 0, $number = -1)
{
    if (empty($user)) {
        global $user_ID;
        $user = $user_ID;
    }
    $purchases = get_transient('edd_user_' . $user . '_purchases');
    if (false === $purchases || edd_is_test_mode()) {
        $mode = edd_is_test_mode() ? 'test' : 'live';
        $purchases = edd_get_payments(array('mode' => $mode, 'user' => $user));
        set_transient('edd_user_' . $user . '_purchases', $purchases, 7200);
    }
    // no purchases
    if (!$purchases) {
        return false;
    }
    return $purchases;
}
/**
 * Complete a purchase
 *
 * Performs all necessary actions to complete a purchase.
 * Triggered by the edd_update_payment_status() function.
 *
 * @since 1.0.8.3
 * @param int $payment_id the ID number of the payment
 * @param string $new_status the status of the payment, probably "publish"
 * @param string $old_status the status of the payment prior to being marked as "complete", probably "pending"
 * @return void
*/
function edd_complete_purchase($payment_id, $new_status, $old_status)
{
    if ($old_status == 'publish' || $old_status == 'complete') {
        return;
    }
    // Make sure that payments are only completed once
    // Make sure the payment completion is only processed when new status is complete
    if ($new_status != 'publish' && $new_status != 'complete') {
        return;
    }
    if (edd_is_test_mode() && !apply_filters('edd_log_test_payment_stats', false)) {
        return;
    }
    $payment_data = edd_get_payment_meta($payment_id);
    $downloads = maybe_unserialize($payment_data['downloads']);
    $user_info = maybe_unserialize($payment_data['user_info']);
    $cart_details = maybe_unserialize($payment_data['cart_details']);
    if (is_array($downloads)) {
        // Increase purchase count and earnings
        foreach ($downloads as $download) {
            edd_record_sale_in_log($download['id'], $payment_id, $user_info);
            edd_increase_purchase_count($download['id']);
            $amount = null;
            if (is_array($cart_details)) {
                foreach ($cart_details as $key => $item) {
                    if (array_search($download['id'], $item)) {
                        $cart_item_id = $key;
                    }
                }
                $amount = isset($cart_details[$cart_item_id]['price']) ? $cart_details[$cart_item_id]['price'] : null;
            }
            $amount = edd_get_download_final_price($download['id'], $user_info, $amount);
            edd_increase_earnings($download['id'], $amount);
        }
        // Clear the total earnings cache
        delete_transient('edd_earnings_total');
    }
    if (isset($user_info['discount']) && $user_info['discount'] != 'none') {
        edd_increase_discount_usage($user_info['discount']);
    }
    // Empty the shopping cart
    edd_empty_cart();
}
/**
 * Get Users Purchases
 *
 * Retrieves a list of all purchases by a specific user.
 *
 * @access      public
 * @since       1.0 
 * @return      array
*/
function edd_get_users_purchases($user_id = 0)
{
    if (empty($user_id)) {
        global $user_ID;
        $user_id = $user_ID;
    }
    $purchases = get_transient('edd_user_' . $user_id . '_purchases');
    if (false === $purchases || edd_is_test_mode()) {
        $mode = edd_is_test_mode() ? 'test' : 'live';
        $purchases = get_posts(array('meta_query' => array('relation' => 'AND', array('key' => '_edd_payment_mode', 'value' => $mode), array('key' => '_edd_payment_user_id', 'value' => $user_id)), 'post_type' => 'edd_payment', 'posts_per_page' => -1));
        set_transient('edd_user_' . $user_id . '_purchases', $purchases, 7200);
    }
    if ($purchases) {
        // return the download list
        return $purchases;
    }
    // no downloads
    return false;
}
/**
 * Payment actions
 *
 * @since 1.1
*/
function edd_csau_payment_actions($payment_id)
{
    $cart_details = edd_get_payment_meta_cart_details($payment_id);
    if (is_array($cart_details)) {
        // Increase purchase count and earnings
        foreach ($cart_details as $download) {
            // "bundle" or "default"
            $download_type = edd_get_download_type($download['id']);
            $price_id = isset($download['options']['price_id']) ? (int) $download['options']['price_id'] : false;
            // Increase earnings, and fire actions once per quantity number
            for ($i = 0; $i < $download['quantity']; $i++) {
                if (!edd_is_test_mode() || apply_filters('edd_log_test_payment_stats', false)) {
                    if (isset($download['item_number']['cross_sell'])) {
                        $type = 'cross_sell';
                    } elseif (isset($download['item_number']['upsell'])) {
                        $type = 'upsell';
                    } else {
                        $type = null;
                    }
                    if ($type) {
                        edd_csau_increase_purchase_count($download['id'], $type);
                        edd_csau_increase_earnings($download['id'], $download['price'], $type);
                        edd_csau_record_sale_in_log($download['id'], $payment_id, $price_id, $type);
                    }
                }
                $types[] = $type;
                $types = array_unique(array_filter($types));
            }
        }
        // Clear the total earnings cache
        delete_transient('edd_' . $type . '_earnings_total');
    }
    if ($types) {
        foreach ($types as $type) {
            // store the total amount of cross-sell earnings
            update_post_meta($payment_id, '_edd_payment_' . $type . '_total', edd_csau_calculate_sales($payment_id, $type));
            $amount = edd_csau_get_payment_amount($payment_id, $type);
            // increase earnings
            edd_csau_increase_total_earnings($amount, $type);
        }
    }
}
/**
 * Insert Payment
 *
 * @access      public
 * @since       1.0 
 * @return      void
*/
function edd_insert_payment($payment_data = array())
{
    if (empty($payment_data)) {
        return false;
    }
    // construct the payment title
    if (isset($payment_data['user_info']['first_name']) || isset($payment_data['user_info']['last_name'])) {
        $payment_title = $payment_data['user_info']['first_name'] . ' ' . $payment_data['user_info']['last_name'];
    } else {
        $payment_title = $payment_data['user_email'];
    }
    if (isset($payment_data['status'])) {
        $status = $payment_data['status'];
    } else {
        $status = 'pending';
    }
    // create a blank payment
    $payment = wp_insert_post(array('post_title' => $payment_title, 'post_status' => $status, 'post_type' => 'edd_payment', 'post_date' => $payment_data['date']));
    if ($payment) {
        $payment_meta = array('amount' => $payment_data['price'], 'date' => $payment_data['date'], 'email' => $payment_data['user_email'], 'key' => $payment_data['purchase_key'], 'currency' => $payment_data['currency'], 'downloads' => serialize($payment_data['downloads']), 'user_info' => serialize($payment_data['user_info']), 'cart_details' => serialize($payment_data['cart_details']), 'user_id' => $payment_data['user_info']['id']);
        $mode = edd_is_test_mode() ? 'test' : 'live';
        $gateway = isset($_POST['edd-gateway']) ? $_POST['edd-gateway'] : '';
        // record the payment details
        update_post_meta($payment, '_edd_payment_meta', apply_filters('edd_payment_meta', $payment_meta, $payment_data));
        update_post_meta($payment, '_edd_payment_user_id', $payment_data['user_info']['id']);
        update_post_meta($payment, '_edd_payment_user_email', $payment_data['user_email']);
        update_post_meta($payment, '_edd_payment_user_ip', edd_get_ip());
        update_post_meta($payment, '_edd_payment_purchase_key', $payment_data['purchase_key']);
        update_post_meta($payment, '_edd_payment_total', $payment_data['price']);
        update_post_meta($payment, '_edd_payment_mode', $mode);
        update_post_meta($payment, '_edd_payment_gateway', $gateway);
        // clear the user's purchased cache
        delete_transient('edd_user_' . $payment_data['user_info']['id'] . '_purchases');
        do_action('edd_insert_payment', $payment, $payment_data);
        return $payment;
        // return the ID
    }
    // return false if no payment was inserted
    return false;
}
function edd_fd_process_payment($purchase_data)
{
    global $edd_options;
    // setup gateway appropriately for test mode
    if (edd_is_test_mode()) {
        $endpoint = 'https://api.demo.globalgatewaye4.firstdata.com/transaction/v11/wsdl';
    } else {
        $endpoint = 'https://api.globalgatewaye4.firstdata.com/transaction/v11/wsdl';
    }
    // check the posted cc deails
    $cc = edd_fd_check_cc_details($purchase_data);
    // fcheck for errors before we continue to processing
    if (!edd_get_errors()) {
        $purchase_summary = edd_get_purchase_summary($purchase_data);
        $payment = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => edd_get_currency(), 'downloads' => $purchase_data['downloads'], 'cart_details' => $purchase_data['cart_details'], 'user_info' => $purchase_data['user_info'], 'status' => 'pending');
        // record the pending payment
        $payment = edd_insert_payment($payment);
        $address = esc_textarea($_POST['card_address'] . ' ' . $_POST['card_address_2'] . '|' . $_POST['card_zip'] . '|' . $_POST['card_city'] . '|' . $_POST['card_state'] . '|' . $_POST['billing_country']);
        $firstdata['Transaction'] = array('ExactID' => $edd_options['firstdata_gateway_id'], 'Password' => $edd_options['firstdata_gateway_password'], 'Transaction_Type' => $edd_options['firstdata_transaction_type'], 'DollarAmount' => $purchase_data['price'], 'Card_Number' => $cc['card_number'], 'Expiry_Date' => $cc['card_exp_month'] . $cc['card_exp_year'], 'CardHoldersName' => $cc['card_name'], 'VerificationStr1' => $address, 'VerificationStr2' => $cc['card_cvc'], 'CVD_Presence_Ind' => 1, 'Reference_No' => $payment, 'ZipCode' => $cc['card_zip'], 'Customer_Ref' => $purchase_data['user_info']['id'], 'Client_IP' => $_SERVER['REMOTE_ADDR'], 'Client_Email' => $purchase_data['user_email'], 'Currency' => $edd_options['currency'], 'Ecommerce_Flag' => is_ssl() ? 8 : 7);
        try {
            $api = @new SoapClient($endpoint);
            $result = $api->__soapCall('SendAndCommit', $firstdata);
        } catch (Exception $e) {
            edd_set_error('firstdata_api_error', sprintf(__('FirstData System Error: %s', 'edd_firstdata'), $e->getMessage()));
            edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
            $fail = true;
        }
        if (isset($result) && $result->Transaction_Approved) {
            edd_update_payment_status($payment, 'complete');
            edd_send_to_success_page();
        } elseif ($result->Transaction_Error) {
            edd_set_error('firstdata_decline', sprintf(__('Transaction Declined: %s', 'edd_firstdata'), $result->EXact_Message));
            edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
            $fail = true;
        }
    } else {
        $fail = true;
    }
}
/**
 * Admin Messages
 *
 * @since 1.0
 * @global $edd_options Array of all the EDD Options
 * @return void
 */
function edd_admin_messages()
{
    global $edd_options;
    if (isset($_GET['edd-message']) && 'discount_updated' == $_GET['edd-message'] && current_user_can('manage_shop_discounts')) {
        add_settings_error('edd-notices', 'edd-discount-updated', __('Discount code updated.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'discount_update_failed' == $_GET['edd-message'] && current_user_can('manage_shop_discounts')) {
        add_settings_error('edd-notices', 'edd-discount-updated-fail', __('There was a problem updating your discount code, please try again.', 'edd'), 'error');
    }
    if (isset($_GET['edd-message']) && 'payment_deleted' == $_GET['edd-message'] && current_user_can('view_shop_reports')) {
        add_settings_error('edd-notices', 'edd-payment-deleted', __('The payment has been deleted.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'email_sent' == $_GET['edd-message'] && current_user_can('view_shop_reports')) {
        add_settings_error('edd-notices', 'edd-payment-sent', __('The purchase receipt has been resent.', 'edd'), 'updated');
    }
    if (isset($_GET['page']) && 'edd-payment-history' == $_GET['page'] && current_user_can('view_shop_reports') && edd_is_test_mode()) {
        add_settings_error('edd-notices', 'edd-payment-sent', sprintf(__('Note: Test Mode is enabled, only test payments are shown below. %sSettings%s.', 'edd'), '<a href="' . admin_url('edit.php?post_type=download&page=edd-settings') . '">', '</a>'), 'updated');
    }
    if ((empty($edd_options['purchase_page']) || 'trash' == get_post_status($edd_options['purchase_page'])) && current_user_can('edit_pages')) {
        add_settings_error('edd-notices', 'set-checkout', sprintf(__('No checkout page has been configured. Visit <a href="%s">Settings</a> to set one.', 'edd'), admin_url('edit.php?post_type=download&page=edd-settings')));
    }
    settings_errors('edd-notices');
}
/**
 * Complete a purchase
 *
 * Performs all necessary actions to complete a purchase. 
 * Triggered by the edd_update_payment_status() function.
 *
 * @param		 int $payment_id the ID number of the payment
 * @param		 string $new_status the status of the payment, probably "publish"
 * @param		 string $old_status the status of the payment prior to being marked as "complete", probably "pending"
 * @access      private
 * @since       1.0.8.3
 * @return      void
*/
function edd_complete_purchase($payment_id, $new_status, $old_status)
{
    if ($old_status == 'publish' || $old_status == 'complete') {
        return;
    }
    // make sure that payments are only completed once
    if (!edd_is_test_mode()) {
        $payment_data = edd_get_payment_meta($payment_id);
        $downloads = maybe_unserialize($payment_data['downloads']);
        $user_info = maybe_unserialize($payment_data['user_info']);
        $cart_details = maybe_unserialize($payment_data['cart_details']);
        if (is_array($downloads)) {
            // increase purchase count and earnings
            foreach ($downloads as $download) {
                edd_record_sale_in_log($download['id'], $payment_id, $user_info, $payment_data['date']);
                edd_increase_purchase_count($download['id']);
                $amount = null;
                if (is_array($cart_details)) {
                    foreach ($cart_details as $key => $item) {
                        if (array_search($download['id'], $item)) {
                            $cart_item_id = $key;
                        }
                    }
                    $amount = isset($cart_details[$cart_item_id]['price']) ? $cart_details[$cart_item_id]['price'] : null;
                }
                $amount = edd_get_download_final_price($download['id'], $user_info, $amount);
                edd_increase_earnings($download['id'], $amount);
            }
        }
        if (isset($user_info['discount'])) {
            edd_increase_discount_usage($user_info['discount']);
        }
    }
    // empty the shopping cart
    edd_empty_cart();
}
/**
 * Get PayPal Redirect
 *
 * @since 1.0.8.2
 * @param bool    $ssl_check Is SSL?
 * @return string
 */
function edd_get_paypal_redirect($ssl_check = false)
{
    if (is_ssl() || !$ssl_check) {
        $protocal = 'https://';
    } else {
        $protocal = 'http://';
    }
    // Check the current payment mode
    if (edd_is_test_mode()) {
        // Test mode
        $paypal_uri = $protocal . 'www.sandbox.paypal.com/cgi-bin/webscr';
    } else {
        // Live mode
        $paypal_uri = $protocal . 'www.paypal.com/cgi-bin/webscr';
    }
    return apply_filters('edd_paypal_uri', $paypal_uri);
}
/**
 * Looks up purchases by email that match the registering user
 *
 * This is for users that purchased as a guest and then came
 * back and created an account.
 *
 * @access      public
 * @since       1.6
 * @param       $user_id INT - the new user's ID
 * @return      void
 */
function edd_add_past_purchases_to_new_user($user_id)
{
    $email = get_user_meta($user_id, 'user_email', true);
    $mode = edd_is_test_mode() ? 'test' : 'live';
    $payments = edd_get_payments(array('s' => $email, 'mode' => $mode));
    if ($payments) {
        foreach ($payments as $payment) {
            if (intval(edd_get_payment_user_id($payment->ID)) > 0) {
                continue;
            }
            // This payment already associated with an account
            $meta = edd_get_payment_meta($payment->ID);
            $meta['user_info'] = maybe_unserialize($meta['user_info']);
            $meta['user_info']['id'] = $user_id;
            $meta['user_info'] = serialize($meta['user_info']);
            // Store the updated user ID in the payment meta
            update_post_meta($payment->ID, '_edd_payment_meta', $meta);
        }
    }
}
/**
 * Adds body classes for EDD pages
 *
 * @since 2.1
 * @param array $class current classes
 * @return array Modified array of classes
 */
function edd_add_body_classes($class)
{
    $classes = (array) $class;
    if (edd_is_checkout()) {
        $classes[] = 'edd-checkout';
        $classes[] = 'edd-page';
    }
    if (edd_is_success_page()) {
        $classes[] = 'edd-success';
        $classes[] = 'edd-page';
    }
    if (edd_is_failed_transaction_page()) {
        $classes[] = 'edd-failed-transaction';
        $classes[] = 'edd-page';
    }
    if (edd_is_purchase_history_page()) {
        $classes[] = 'edd-purchase-history';
        $classes[] = 'edd-page';
    }
    if (edd_is_test_mode()) {
        $classes[] = 'edd-test-mode';
        $classes[] = 'edd-page';
    }
    return array_unique($classes);
}
/**
 * Admin Messages
 *
 * @since 1.0
 * @global $edd_options Array of all the EDD Options
 * @return void
 */
function edd_admin_messages()
{
    global $edd_options;
    if (isset($_GET['edd-message']) && 'discount_added' == $_GET['edd-message'] && current_user_can('manage_shop_discounts')) {
        add_settings_error('edd-notices', 'edd-discount-added', __('Discount code added.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'discount_add_failed' == $_GET['edd-message'] && current_user_can('manage_shop_discounts')) {
        add_settings_error('edd-notices', 'edd-discount-add-fail', __('There was a problem adding your discount code, please try again.', 'edd'), 'error');
    }
    if (isset($_GET['edd-message']) && 'discount_exists' == $_GET['edd-message'] && current_user_can('manage_shop_discounts')) {
        add_settings_error('edd-notices', 'edd-discount-exists', __('A discount with that code already exists, please use a different code.', 'edd'), 'error');
    }
    if (isset($_GET['edd-message']) && 'discount_updated' == $_GET['edd-message'] && current_user_can('manage_shop_discounts')) {
        add_settings_error('edd-notices', 'edd-discount-updated', __('Discount code updated.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'discount_update_failed' == $_GET['edd-message'] && current_user_can('manage_shop_discounts')) {
        add_settings_error('edd-notices', 'edd-discount-updated-fail', __('There was a problem updating your discount code, please try again.', 'edd'), 'error');
    }
    if (isset($_GET['edd-message']) && 'payment_deleted' == $_GET['edd-message'] && current_user_can('view_shop_reports')) {
        add_settings_error('edd-notices', 'edd-payment-deleted', __('The payment has been deleted.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'email_sent' == $_GET['edd-message'] && current_user_can('view_shop_reports')) {
        add_settings_error('edd-notices', 'edd-payment-sent', __('The purchase receipt has been resent.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'payment-note-deleted' == $_GET['edd-message'] && current_user_can('view_shop_reports')) {
        add_settings_error('edd-notices', 'edd-payment-note-deleted', __('The payment note has been deleted.', 'edd'), 'updated');
    }
    if (isset($_GET['page']) && 'edd-payment-history' == $_GET['page'] && current_user_can('view_shop_reports') && edd_is_test_mode()) {
        add_settings_error('edd-notices', 'edd-payment-sent', sprintf(__('Note: Test Mode is enabled, only test payments are shown below. <a href="%s">Settings</a>.', 'edd'), admin_url('edit.php?post_type=download&page=edd-settings')), 'updated');
    }
    if ((empty($edd_options['purchase_page']) || 'trash' == get_post_status($edd_options['purchase_page'])) && current_user_can('edit_pages') && !get_user_meta(get_current_user_id(), '_edd_set_checkout_dismissed')) {
        echo '<div class="error">';
        echo '<p>' . sprintf(__('No checkout page has been configured. Visit <a href="%s">Settings</a> to set one.', 'edd'), admin_url('edit.php?post_type=download&page=edd-settings')) . '</p>';
        echo '<p><a href="' . add_query_arg(array('edd_action' => 'dismiss_notices', 'edd_notice' => 'set_checkout')) . '">' . __('Dismiss Notice', 'edd') . '</a></p>';
        echo '</div>';
    }
    if (isset($_GET['edd-message']) && 'settings-imported' == $_GET['edd-message'] && current_user_can('manage_shop_settings')) {
        add_settings_error('edd-notices', 'edd-settings-imported', __('The settings have been imported.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'note-added' == $_GET['edd-message'] && current_user_can('edit_shop_payments')) {
        add_settings_error('edd-notices', 'edd-note-added', __('The payment note has been added successfully.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'payment-updated' == $_GET['edd-message'] && current_user_can('edit_shop_payments')) {
        add_settings_error('edd-notices', 'edd-payment-updated', __('The payment has been successfully updated.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'api-key-generated' == $_GET['edd-message'] && current_user_can('manage_shop_settings')) {
        add_settings_error('edd-notices', 'edd-api-key-generated', __('API keys successfully generated.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'api-key-exists' == $_GET['edd-message'] && current_user_can('manage_shop_settings')) {
        add_settings_error('edd-notices', 'edd-api-key-exists', __('The specified user already has API keys.', 'edd'), 'error');
    }
    if (isset($_GET['edd-message']) && 'api-key-regenerated' == $_GET['edd-message'] && current_user_can('manage_shop_settings')) {
        add_settings_error('edd-notices', 'edd-api-key-regenerated', __('API keys successfully regenerated.', 'edd'), 'updated');
    }
    if (isset($_GET['edd-message']) && 'api-key-revoked' == $_GET['edd-message'] && current_user_can('manage_shop_settings')) {
        add_settings_error('edd-notices', 'edd-api-key-revoked', __('API keys successfully revoked.', 'edd'), 'updated');
    }
    if (!edd_htaccess_exists() && !get_user_meta(get_current_user_id(), '_edd_htaccess_missing_dismissed', true)) {
        if (!stristr($_SERVER['SERVER_SOFTWARE'], 'apache')) {
            return;
        }
        // Bail if we aren't using Apache... nginx doesn't use htaccess!
        echo '<div class="error">';
        echo '<p>' . sprintf(__('The Easy Digital Downloads .htaccess file is missing from <strong>%s</strong>!', 'edd'), edd_get_upload_dir()) . '</p>';
        echo '<p>' . sprintf(__('First, please resave the Misc settings tab a few times. If this warning continues to appear, create a file called ".htaccess" in the <strong>%s</strong> directory, and copy the following into it:', 'edd'), edd_get_upload_dir()) . '</p>';
        echo '<p><pre>' . edd_get_htaccess_rules() . '</pre>';
        echo '<p><a href="' . add_query_arg(array('edd_action' => 'dismiss_notices', 'edd_notice' => 'htaccess_missing')) . '">' . __('Dismiss Notice', 'edd') . '</a></p>';
        echo '</div>';
    }
    settings_errors('edd-notices');
}
 /**
  * Send purchase details to MailChimp's Ecommerce360 extension.
  *
  * @param  integer $payment_id    [description]
  * @return bool
  */
 public function record_ecommerce360_purchase($payment_id = 0)
 {
     // Make sure an API key has been entered
     if (empty($this->key)) {
         return FALSE;
     }
     // Don't record details if we're in test mode
     if (edd_is_test_mode()) {
         return FALSE;
     }
     $payment = edd_get_payment_meta($payment_id);
     $user_info = edd_get_payment_meta_user_info($payment_id);
     $amount = edd_get_payment_amount($payment_id);
     $cart_details = edd_get_payment_meta_cart_details($payment_id);
     $tax = edd_get_payment_tax($payment_id);
     if (is_array($cart_details)) {
         $items = array();
         // Increase purchase count and earnings
         foreach ($cart_details as $index => $download) {
             // Get the categories that this download belongs to, if any
             $post = edd_get_download($download['id']);
             $terms = get_the_terms($download['id'], 'download_category');
             if ($terms && !is_wp_error($terms)) {
                 $categories = array();
                 foreach ($terms as $term) {
                     $categories[] = $term->name;
                 }
                 $category_id = $terms[0]->term_id;
                 $category_name = join(" - ", $categories);
             } else {
                 $category_id = 1;
                 $category_name = 'Download';
             }
             // "bundle" or "default"
             $download_type = edd_get_download_type($download['id']);
             $download['sku'] = edd_get_download_sku($download['id']);
             // if ( 'bundle' == $download_type ) {
             //   $downloads = edd_get_bundled_products( $download_id );
             //   if ( $downloads ) {
             //     foreach ( $downloads as $d_id ) {
             //       # Do something
             //     }
             //   }
             // }
             $item = array('line_num' => $index + 1, 'product_id' => (int) $download['id'], 'product_name' => $download['name'], 'category_id' => $category_id, 'category_name' => $category_name, 'qty' => $download['quantity'], 'cost' => $download['subtotal']);
             if ($download['sku'] !== '-') {
                 $item['sku'] = $download['sku'];
                 // optional, 30 char limit
             }
             $items[] = $item;
         }
         $order = array('id' => (string) $payment_id, 'email' => $user_info['email'], 'total' => $amount, 'store_id' => self::_edd_ec360_get_store_id(), 'store_name' => home_url(), 'items' => $items, 'order_date' => get_the_date('Y-n-j', $payment_id));
         // Set Ecommerce360 variables if they exist
         $campaign_id = get_post_meta($payment_id, '_edd_mc_campaign_id', true);
         $email_id = get_post_meta($payment_id, '_edd_mc_email_id', true);
         if (!empty($campaign_id)) {
             $order['campaign_id'] = $campaign_id;
         }
         if (!empty($email_id)) {
             $order['email_id'] = $email_id;
         }
         if ($tax != 0) {
             $order['tax'] = $tax;
             // double, optional
         }
         // Send to MailChimp
         $options = array('CURLOPT_FOLLOWLOCATION' => false);
         $mailchimp = new EDD_MailChimp_API($this->key, $options);
         try {
             $result = $mailchimp->call('ecomm/order-add', array('order' => $order));
             edd_insert_payment_note($payment_id, __('Order details have been added to MailChimp successfully', 'eddmc'));
         } catch (Exception $e) {
             edd_insert_payment_note($payment_id, __('MailChimp Ecommerce360 Error: ', 'eddmc') . $e->getMessage());
             return FALSE;
         }
         return TRUE;
     } else {
         return FALSE;
     }
 }
/**
 * Gets the sales tax for the current year
 *
 * @since 1.3.3
 * @param $year int The year to retrieve taxes for, i.e. 2012
 * @uses edd_get_payment_tax()
 * @return float $tax Sales tax
 */
function edd_get_sales_tax_for_year($year = null)
{
    if (empty($year)) {
        return 0;
    }
    // Start at zero
    $tax = 0;
    $args = array('post_type' => 'edd_payment', 'posts_per_page' => -1, 'year' => $year, 'meta_key' => '_edd_payment_mode', 'meta_value' => edd_is_test_mode() ? 'test' : 'live', 'fields' => 'ids');
    $payments = get_posts($args);
    if ($payments) {
        foreach ($payments as $payment) {
            $tax += edd_get_payment_tax($payment);
        }
    }
    return apply_filters('edd_get_sales_tax_for_year', $tax, $year);
}
 /**
  * Load javascript files and localized variables
  *
  * @access public
  * @since  2.4
  * @return void
  */
 public function load_scripts()
 {
     if (!edd_is_checkout()) {
         return;
     }
     $test_mode = edd_is_test_mode();
     $seller_id = edd_get_option('amazon_seller_id', '');
     $client_id = edd_get_option('amazon_client_id', '');
     $default_amazon_scope = array('profile', 'postal_code', 'payments:widget');
     if (edd_use_taxes()) {
         $default_amazon_scope[] = 'payments:shipping_address';
     }
     $default_amazon_button_settings = array('type' => 'PwA', 'color' => 'Gold', 'size' => 'medium', 'scope' => implode(' ', $default_amazon_scope), 'popup' => true);
     $amazon_button_settings = apply_filters('edd_amazon_button_settings', $default_amazon_button_settings);
     $base_url = '';
     $sandbox = $test_mode ? 'sandbox/' : '';
     switch (edd_get_shop_country()) {
         case 'GB':
             $base_url = 'https://static-eu.payments-amazon.com/OffAmazonPayments/uk/' . $sandbox . 'lpa/';
             break;
         case 'DE':
             $base_url = 'https://static-eu.payments-amazon.com/OffAmazonPayments/de/' . $sandbox . 'lpa/';
             break;
         default:
             $base_url = 'https://static-na.payments-amazon.com/OffAmazonPayments/us/' . $sandbox;
             break;
     }
     if (!empty($base_url)) {
         $url = $base_url . 'js/Widgets.js?sellerId=' . $seller_id;
         wp_enqueue_script('edd-amazon-widgets', $url, array('jquery'), null, false);
         wp_localize_script('edd-amazon-widgets', 'edd_amazon', apply_filters('edd_amazon_checkout_vars', array('sellerId' => $seller_id, 'clientId' => $client_id, 'referenceID' => $this->reference_id, 'buttonType' => $amazon_button_settings['type'], 'buttonColor' => $amazon_button_settings['color'], 'buttonSize' => $amazon_button_settings['size'], 'scope' => $amazon_button_settings['scope'], 'popup' => $amazon_button_settings['popup'], 'checkoutUri' => $this->get_amazon_checkout_uri(), 'redirectUri' => $this->get_amazon_authenticate_redirect(), 'signinUri' => $this->get_amazon_signin_redirect())));
     }
 }
/**
 * Insert Payment
 *
 * @since 1.0
 * @param array $payment_data
 * @return int|bool Payment ID if payment is inserted, false otherwise
 */
function edd_insert_payment($payment_data = array())
{
    if (empty($payment_data)) {
        return false;
    }
    // Make sure the payment is inserted with the correct timezone
    date_default_timezone_set(edd_get_timezone_id());
    // Construct the payment title
    if (isset($payment_data['user_info']['first_name']) || isset($payment_data['user_info']['last_name'])) {
        $payment_title = $payment_data['user_info']['first_name'] . ' ' . $payment_data['user_info']['last_name'];
    } else {
        $payment_title = $payment_data['user_email'];
    }
    // Retrieve the ID of the discount used, if any
    if ($payment_data['user_info']['discount'] != 'none') {
        $discount = edd_get_discount_by('code', $payment_data['user_info']['discount']);
    }
    // Find the next payment number, if enabled
    if (edd_get_option('enable_sequential')) {
        $number = edd_get_next_payment_number();
    }
    $args = apply_filters('edd_insert_payment_args', array('post_title' => $payment_title, 'post_status' => isset($payment_data['status']) ? $payment_data['status'] : 'pending', 'post_type' => 'edd_payment', 'post_parent' => isset($payment_data['parent']) ? $payment_data['parent'] : null, 'post_date' => isset($payment_data['post_date']) ? $payment_data['post_date'] : null, 'post_date_gmt' => isset($payment_data['post_date']) ? get_gmt_from_date($payment_data['post_date']) : null), $payment_data);
    // Create a blank payment
    $payment = wp_insert_post($args);
    if ($payment) {
        if (isset($payment_data['tax'])) {
            $cart_tax = $payment_data['tax'];
        } else {
            $taxes = $payment_data['cart_details'] ? wp_list_pluck($payment_data['cart_details'], 'tax') : array();
            $cart_tax = array_sum($taxes);
            $cart_tax += edd_get_cart_fee_tax();
        }
        $payment_meta = array('currency' => $payment_data['currency'], 'downloads' => $payment_data['downloads'], 'user_info' => $payment_data['user_info'], 'cart_details' => $payment_data['cart_details']);
        $mode = edd_is_test_mode() ? 'test' : 'live';
        $gateway = !empty($payment_data['gateway']) ? $payment_data['gateway'] : '';
        $gateway = empty($gateway) && isset($_POST['edd-gateway']) ? $_POST['edd-gateway'] : $gateway;
        if (!$payment_data['price']) {
            // Ensures the _edd_payment_total meta key is created for purchases with an amount of 0
            $payment_data['price'] = '0.00';
        }
        // Create or update a customer
        $customer = new EDD_Customer($payment_data['user_email']);
        $customer_data = array('name' => $payment_data['user_info']['first_name'] . ' ' . $payment_data['user_info']['last_name'], 'email' => $payment_data['user_email'], 'user_id' => $payment_data['user_info']['id']);
        if (empty($customer->id)) {
            $customer->create($customer_data);
        } else {
            // Only update the customer if their name or email has changed
            if ($customer_data['email'] !== $customer->email || $customer_data['name'] !== $customer->name) {
                // We shouldn't be updating the User ID here, that is an admin task
                unset($customer_data['user_id']);
                $customer->update($customer_data);
            }
        }
        $customer->attach_payment($payment, false);
        // Record the payment details
        edd_update_payment_meta($payment, '_edd_payment_meta', apply_filters('edd_payment_meta', $payment_meta, $payment_data));
        edd_update_payment_meta($payment, '_edd_payment_user_id', $payment_data['user_info']['id']);
        edd_update_payment_meta($payment, '_edd_payment_customer_id', $customer->id);
        edd_update_payment_meta($payment, '_edd_payment_user_email', $payment_data['user_email']);
        edd_update_payment_meta($payment, '_edd_payment_user_ip', edd_get_ip());
        edd_update_payment_meta($payment, '_edd_payment_purchase_key', $payment_data['purchase_key']);
        edd_update_payment_meta($payment, '_edd_payment_total', $payment_data['price']);
        edd_update_payment_meta($payment, '_edd_payment_mode', $mode);
        edd_update_payment_meta($payment, '_edd_payment_gateway', $gateway);
        edd_update_payment_meta($payment, '_edd_payment_tax', $cart_tax);
        if (!empty($discount)) {
            edd_update_payment_meta($payment, '_edd_payment_discount_id', $discount->ID);
        }
        if (edd_get_option('enable_sequential')) {
            edd_update_payment_meta($payment, '_edd_payment_number', edd_format_payment_number($number));
            update_option('edd_last_payment_number', $number);
        }
        // Clear the user's purchased cache
        delete_transient('edd_user_' . $payment_data['user_info']['id'] . '_purchases');
        do_action('edd_insert_payment', $payment, $payment_data);
        return $payment;
        // Return the ID
    }
    // Return false if no payment was inserted
    return false;
}
/**
 * Undos a purchase, including the decrease of sale and earning stats. Used for
 * when refunding or deleting a purchase
 *
 * @since 1.0.8.1
 * @param int $download_id Download (Post) ID
 * @param int $payment_id Payment ID
 * @return void
 */
function edd_undo_purchase($download_id, $payment_id)
{
    if (edd_is_test_mode()) {
        return;
    }
    $cart_details = edd_get_payment_meta_cart_details($payment_id);
    $user_info = edd_get_payment_meta_user_info($payment_id);
    if (is_array($cart_details)) {
        foreach ($cart_details as $item) {
            // Decrease earnings/sales and fire action once per quantity number
            for ($i = 0; $i < $item['quantity']; $i++) {
                // get the item's price
                $amount = isset($item['price']) ? $item['price'] : false;
                // variable priced downloads
                if (edd_has_variable_prices($download_id)) {
                    $price_id = isset($item['item_number']['options']['price_id']) ? $item['item_number']['options']['price_id'] : null;
                    $amount = !isset($item['price']) && 0 !== $item['price'] ? edd_get_price_option_amount($download_id, $price_id) : $item['price'];
                }
                if (!$amount) {
                    // This function is only used on payments with near 1.0 cart data structure
                    $amount = edd_get_download_final_price($download_id, $user_info, $amount);
                }
                // decrease earnings
                edd_decrease_earnings($download_id, $amount);
                // decrease purchase count
                edd_decrease_purchase_count($download_id);
            }
        }
    }
}
/**
 * Insert Payment
 *
 * @since 1.0
 * @param array $payment_data
 * @return int|bool Payment ID if payment is inserted, false otherwise
 */
function edd_insert_payment($payment_data = array())
{
    if (empty($payment_data)) {
        return false;
    }
    $payment = new EDD_Payment();
    if (is_array($payment_data['cart_details']) && !empty($payment_data['cart_details'])) {
        foreach ($payment_data['cart_details'] as $item) {
            $args = array('quantity' => $item['quantity'], 'price_id' => isset($item['item_number']['options']['price_id']) ? $item['item_number']['options']['price_id'] : null, 'tax' => $item['tax'], 'item_price' => isset($item['item_price']) ? $item['item_price'] : $item['price'], 'fees' => isset($item['fees']) ? $item['fees'] : array(), 'discount' => isset($item['discount']) ? $item['discount'] : 0);
            $options = isset($item['item_number']['options']) ? $item['item_number']['options'] : array();
            $payment->add_download($item['id'], $args, $options);
        }
    }
    $payment->increase_tax(edd_get_cart_fee_tax());
    $gateway = !empty($payment_data['gateway']) ? $payment_data['gateway'] : '';
    $gateway = empty($gateway) && isset($_POST['edd-gateway']) ? $_POST['edd-gateway'] : $gateway;
    $payment->status = !empty($payment_data['status']) ? $payment_data['status'] : 'pending';
    $payment->currency = !empty($payment_data['currency']) ? $payment_data['currency'] : edd_get_currency();
    $payment->user_info = $payment_data['user_info'];
    $payment->gateway = $gateway;
    $payment->user_id = $payment_data['user_info']['id'];
    $payment->email = $payment_data['user_email'];
    $payment->first_name = $payment_data['user_info']['first_name'];
    $payment->last_name = $payment_data['user_info']['last_name'];
    $payment->email = $payment_data['user_info']['email'];
    $payment->ip = edd_get_ip();
    $payment->key = $payment_data['purchase_key'];
    $payment->mode = edd_is_test_mode() ? 'test' : 'live';
    $payment->parent_payment = !empty($payment_data['parent']) ? absint($payment_data['parent']) : '';
    $payment->discounts = !empty($payment_data['user_info']['discount']) ? $payment_data['user_info']['discount'] : array();
    if (isset($payment_data['post_date'])) {
        $payment->date = $payment_data['post_date'];
    }
    if (edd_get_option('enable_sequential')) {
        $number = edd_get_next_payment_number();
        $payment->number = edd_format_payment_number($number);
        update_option('edd_last_payment_number', $number);
    }
    // Clear the user's purchased cache
    delete_transient('edd_user_' . $payment_data['user_info']['id'] . '_purchases');
    $payment->save();
    do_action('edd_insert_payment', $payment->ID, $payment_data);
    if (!empty($payment->ID)) {
        return $payment->ID;
    }
    // Return false if no payment was inserted
    return false;
}
 /**
  * Get voguepay Redirect
  * @global $edd_options Array of all the EDD Options
  * @param boolean   $ssl_check Need url with ssl or without ssl
  * @return $voguepay_uri
  */
 public function get_voguepay_redirect($ssl_check = false)
 {
     global $edd_options;
     if (is_ssl() || !$ssl_check) {
         $protocal = 'https://';
     } else {
         $protocal = 'http://';
     }
     // Check the current payment mode
     if (edd_is_test_mode()) {
         // Test mode
         $voguepay_uri = $protocal . 'voguepay.com/pay/';
     } else {
         // Live mode
         $voguepay_uri = $protocal . 'voguepay.com/pay/';
     }
     return apply_filters('edd_voguepay_uri', $voguepay_uri);
 }
 /**
  * Retrieve all the data for all the redirects
  *
  * @access public
  * @since 1.0
  * @return array $redirect_data Array of all the data for the redirects
  */
 public function redirect_data()
 {
     $redirect_data = array();
     $per_page = $this->per_page;
     $mode = edd_is_test_mode() ? 'test' : 'live';
     $orderby = isset($_GET['orderby']) ? $_GET['orderby'] : 'ID';
     $order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
     $order_inverse = $order == 'DESC' ? 'ASC' : 'DESC';
     $status = isset($_GET['status']) ? $_GET['status'] : array('active', 'inactive');
     $meta_key = isset($_GET['meta_key']) ? $_GET['meta_key'] : null;
     $search = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : null;
     $order_class = strtolower($order_inverse);
     $redirects = edd_csr_get_redirects(array('posts_per_page' => $per_page, 'paged' => isset($_GET['paged']) ? $_GET['paged'] : 1, 'orderby' => $orderby, 'order' => $order, 'post_status' => $status, 'meta_key' => $meta_key, 's' => $search));
     if ($redirects) {
         foreach ($redirects as $redirect) {
             $redirect_to = edd_csr_get_redirect_page($redirect->ID) ? edd_csr_get_redirect_page($redirect->ID) : '';
             $download = edd_csr_get_redirect_download($redirect->ID) ? get_the_title(edd_csr_get_redirect_download($redirect->ID)) : '';
             $redirect_data[] = array('ID' => $redirect->ID, 'download' => $download, 'redirect' => get_the_title($redirect_to), 'status' => ucwords($redirect->post_status));
         }
     }
     return $redirect_data;
 }
 /**
  * Show relevant notices
  *
  * @since 2.3
  */
 public function show_notices()
 {
     $notices = array('updated' => array(), 'error' => array());
     // Global (non-action-based) messages
     if (edd_get_option('purchase_page', '') == '' || 'trash' == get_post_status(edd_get_option('purchase_page', '')) && current_user_can('edit_pages') && !get_user_meta(get_current_user_id(), '_edd_set_checkout_dismissed')) {
         echo '<div class="error">';
         echo '<p>' . sprintf(__('No checkout page has been configured. Visit <a href="%s">Settings</a> to set one.', 'easy-digital-downloads'), admin_url('edit.php?post_type=download&page=edd-settings')) . '</p>';
         echo '<p><a href="' . add_query_arg(array('edd_action' => 'dismiss_notices', 'edd_notice' => 'set_checkout')) . '">' . __('Dismiss Notice', 'easy-digital-downloads') . '</a></p>';
         echo '</div>';
     }
     if (isset($_GET['page']) && 'edd-payment-history' == $_GET['page'] && current_user_can('view_shop_reports') && edd_is_test_mode()) {
         $notices['updated']['edd-payment-history-test-mode'] = sprintf(__('Note: Test Mode is enabled, only test payments are shown below. <a href="%s">Settings</a>.', 'easy-digital-downloads'), admin_url('edit.php?post_type=download&page=edd-settings'));
     }
     if (stristr($_SERVER['SERVER_SOFTWARE'], 'nginx') && !get_user_meta(get_current_user_id(), '_edd_nginx_redirect_dismissed', true) && current_user_can('manage_shop_settings')) {
         echo '<div class="error">';
         echo '<p>' . sprintf(__('The download files in <strong>%s</strong> are not currently protected due to your site running on NGINX.', 'easy-digital-downloads'), edd_get_upload_dir()) . '</p>';
         echo '<p>' . __('To protect them, you must add a redirect rule as explained in <a href="http://docs.easydigitaldownloads.com/article/682-protected-download-files-on-nginx">this guide</a>.', 'easy-digital-downloads') . '</p>';
         echo '<p>' . __('If you have already added the redirect rule, you may safely dismiss this notice', 'easy-digital-downloads') . '</p>';
         echo '<p><a href="' . add_query_arg(array('edd_action' => 'dismiss_notices', 'edd_notice' => 'nginx_redirect')) . '">' . __('Dismiss Notice', 'easy-digital-downloads') . '</a></p>';
         echo '</div>';
     }
     if (!edd_htaccess_exists() && !get_user_meta(get_current_user_id(), '_edd_htaccess_missing_dismissed', true) && current_user_can('manage_shop_settings')) {
         if (!stristr($_SERVER['SERVER_SOFTWARE'], 'apache')) {
             return;
         }
         // Bail if we aren't using Apache... nginx doesn't use htaccess!
         echo '<div class="error">';
         echo '<p>' . sprintf(__('The Easy Digital Downloads .htaccess file is missing from <strong>%s</strong>!', 'easy-digital-downloads'), edd_get_upload_dir()) . '</p>';
         echo '<p>' . sprintf(__('First, please resave the Misc settings tab a few times. If this warning continues to appear, create a file called ".htaccess" in the <strong>%s</strong> directory, and copy the following into it:', 'easy-digital-downloads'), edd_get_upload_dir()) . '</p>';
         echo '<p><pre>' . edd_get_htaccess_rules() . '</pre>';
         echo '<p><a href="' . add_query_arg(array('edd_action' => 'dismiss_notices', 'edd_notice' => 'htaccess_missing')) . '">' . __('Dismiss Notice', 'easy-digital-downloads') . '</a></p>';
         echo '</div>';
     }
     /* Commented out per https://github.com/easydigitaldownloads/Easy-Digital-Downloads/issues/3475
     		if( ! edd_test_ajax_works() && ! get_user_meta( get_current_user_id(), '_edd_admin_ajax_inaccessible_dismissed', true ) && current_user_can( 'manage_shop_settings' ) ) {
     			echo '<div class="error">';
     				echo '<p>' . __( 'Your site appears to be blocking the WordPress ajax interface. This may causes issues with your store.', 'easy-digital-downloads' ) . '</p>';
     				echo '<p>' . sprintf( __( 'Please see <a href="%s" target="_blank">this reference</a> for possible solutions.', 'easy-digital-downloads' ), 'https://easydigitaldownloads.com/docs/admin-ajax-blocked' ) . '</p>';
     				echo '<p><a href="' . add_query_arg( array( 'edd_action' => 'dismiss_notices', 'edd_notice' => 'admin_ajax_inaccessible' ) ) . '">' . __( 'Dismiss Notice', 'easy-digital-downloads' ) . '</a></p>';
     			echo '</div>';
     		}
     		*/
     if (isset($_GET['edd-message'])) {
         // Shop discounts errors
         if (current_user_can('manage_shop_discounts')) {
             switch ($_GET['edd-message']) {
                 case 'discount_added':
                     $notices['updated']['edd-discount-added'] = __('Discount code added.', 'easy-digital-downloads');
                     break;
                 case 'discount_add_failed':
                     $notices['error']['edd-discount-add-fail'] = __('There was a problem adding your discount code, please try again.', 'easy-digital-downloads');
                     break;
                 case 'discount_exists':
                     $notices['error']['edd-discount-exists'] = __('A discount with that code already exists, please use a different code.', 'easy-digital-downloads');
                     break;
                 case 'discount_updated':
                     $notices['updated']['edd-discount-updated'] = __('Discount code updated.', 'easy-digital-downloads');
                     break;
                 case 'discount_update_failed':
                     $notices['error']['edd-discount-updated-fail'] = __('There was a problem updating your discount code, please try again.', 'easy-digital-downloads');
                     break;
             }
         }
         // Shop reports errors
         if (current_user_can('view_shop_reports')) {
             switch ($_GET['edd-message']) {
                 case 'payment_deleted':
                     $notices['updated']['edd-payment-deleted'] = __('The payment has been deleted.', 'easy-digital-downloads');
                     break;
                 case 'email_sent':
                     $notices['updated']['edd-payment-sent'] = __('The purchase receipt has been resent.', 'easy-digital-downloads');
                     break;
                 case 'payment-note-deleted':
                     $notices['updated']['edd-payment-note-deleted'] = __('The payment note has been deleted.', 'easy-digital-downloads');
                     break;
             }
         }
         // Shop settings errors
         if (current_user_can('manage_shop_settings')) {
             switch ($_GET['edd-message']) {
                 case 'settings-imported':
                     $notices['updated']['edd-settings-imported'] = __('The settings have been imported.', 'easy-digital-downloads');
                     break;
                 case 'api-key-generated':
                     $notices['updated']['edd-api-key-generated'] = __('API keys successfully generated.', 'easy-digital-downloads');
                     break;
                 case 'api-key-exists':
                     $notices['error']['edd-api-key-exists'] = __('The specified user already has API keys.', 'easy-digital-downloads');
                     break;
                 case 'api-key-regenerated':
                     $notices['updated']['edd-api-key-regenerated'] = __('API keys successfully regenerated.', 'easy-digital-downloads');
                     break;
                 case 'api-key-revoked':
                     $notices['updated']['edd-api-key-revoked'] = __('API keys successfully revoked.', 'easy-digital-downloads');
                     break;
             }
         }
         // Shop payments errors
         if (current_user_can('edit_shop_payments')) {
             switch ($_GET['edd-message']) {
                 case 'note-added':
                     $notices['updated']['edd-note-added'] = __('The payment note has been added successfully.', 'easy-digital-downloads');
                     break;
                 case 'payment-updated':
                     $notices['updated']['edd-payment-updated'] = __('The payment has been successfully updated.', 'easy-digital-downloads');
                     break;
             }
         }
         // Customer Notices
         if (current_user_can('edit_shop_payments')) {
             switch ($_GET['edd-message']) {
                 case 'customer-deleted':
                     $notices['updated']['edd-customer-deleted'] = __('Customer successfully deleted', 'easy-digital-downloads');
                     break;
                 case 'user-verified':
                     $notices['updated']['edd-user-verified'] = __('User successfully verified', 'easy-digital-downloads');
                     break;
             }
         }
     }
     if (count($notices['updated']) > 0) {
         foreach ($notices['updated'] as $notice => $message) {
             add_settings_error('edd-notices', $notice, $message, 'updated');
         }
     }
     if (count($notices['error']) > 0) {
         foreach ($notices['error'] as $notice => $message) {
             add_settings_error('edd-notices', $notice, $message, 'error');
         }
     }
     settings_errors('edd-notices');
 }
 /**
  * Get Shmart Redirect
  * @global $edd_options Array of all the EDD Options
  * @param boolean   $ssl_check Need url with ssl or without ssl
  * @return $shmart_uri
  */
 public function get_shmart_redirect($ssl_check = false)
 {
     global $edd_options;
     if (is_ssl() || !$ssl_check) {
         $protocal = 'https://';
     } else {
         $protocal = 'http://';
     }
     // Check the current payment mode
     if (edd_is_test_mode()) {
         // Test mode
         $shmart_uri = $protocal . 'pay.shmart.in/checkout/v2/transactions';
     } else {
         // Live mode
         $shmart_uri = $protocal . 'pay.shmart.in/checkout/v2/transactions';
     }
     return apply_filters('edd_shmart_uri', $shmart_uri);
 }