function edd_process_paytm_gateway_ipn()
{
    global $edd_options;
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] != 'POST') {
        return;
    }
    $payment_id = $_GET['payment_id'];
    if (empty($payment_id)) {
        edd_send_back_to_checkout('?payment-mode=paytm_gateway');
    }
    // Fallback just in case post_max_size is lower than needed
    if (isset($_POST['ORDERID']) && isset($_POST['RESPCODE'])) {
        $order_sent = $_POST['ORDERID'];
        $responseDescription = $_POST['RESPMSG'];
        if ($_POST['RESPCODE'] == '01') {
            // success
            $order_sent = $_POST['ORDERID'];
            $res_code = $_POST['RESPCODE'];
            $responseDescription = $_POST['RESPMSG'];
            $checksum_recv = $_POST['CHECKSUMHASH'];
            $paramList = $_POST;
            $order_amount = $_POST['TXNAMOUNT'];
            //  code by paytm team
            $bool = "FALSE";
            $secret_key = $edd_options['paytm_mer_access_key'];
            $bool = verifychecksum_e($paramList, $secret_key, $checksum_recv);
            if ($bool == "TRUE") {
                $payment_meta = edd_get_payment_meta($payment_id);
                edd_insert_payment_note($payment_id, sprintf(__('Thank you for your order . Your transaction has been successful. Paytm Transaction ID: %s', 'edd'), $_REQUEST['TXNID']));
                edd_set_payment_transaction_id($payment_id, $_REQUEST['TXNID']);
                edd_update_payment_status($payment_id, 'complete');
                edd_empty_cart();
                edd_send_to_success_page();
            } else {
                edd_record_gateway_error(__('Paytm Error', 'edd'), sprintf(__('Transaction Failed Invalid Checksum', 'edd'), ''), $payment_id);
                edd_update_payment_status($payment_id, 'failed');
                edd_insert_payment_note($payment_id, sprintf(__('Transaction Failed Invalid Checksum', 'edd'), ''));
                wp_redirect('?page_id=6&payment-mode=paytm_gateway');
                //edd_send_back_to_checkout( '?payment-mode=paytm_gateway' );
            }
        } else {
            edd_record_gateway_error(__('Paytm Error', 'edd'), sprintf(__('Transaction Failed. %s', 'edd'), $responseDescription), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            edd_insert_payment_note($payment_id, sprintf(__('Transaction Failed. %s', 'edd'), $responseDescription));
            wp_redirect('?page_id=6&payment-mode=paytm_gateway');
        }
    } else {
        edd_record_gateway_error(__('Paytm Error', 'edd'), sprintf(__('Transaction Failed, No Response ', 'edd'), ''), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        edd_insert_payment_note($payment_id, sprintf(__('Transaction Failed, No Response ', 'edd'), ''));
        wp_redirect('?page_id=6&payment-mode=paytm_gateway');
    }
    exit;
}
/**
 * Manual Payment
 *
 * @access      private
 * @since       1.0 
 * @return      void
*/
function edd_manual_payment($purchase_data)
{
    global $edd_options;
    /* 
    * purchase data comes in like this
    *
    $purchase_data = array(
    	'downloads' => array of download IDs,
    	'price' => total price of cart contents,
    	'purchase_key' =>  // random key
    	'user_email' => $user_email,
    	'date' => date('Y-m-d H:i:s'),
    	'user_id' => $user_id,
    	'post_data' => $_POST,
    	'user_info' => array of user's information and used discount code
    	'cart_details' => array of cart details,
    );
    */
    $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'], 'user_info' => $purchase_data['user_info'], 'cart_details' => $purchase_data['cart_details'], 'status' => 'pending');
    // record the pending payment
    $payment = edd_insert_payment($payment);
    if ($payment) {
        edd_update_payment_status($payment, 'publish');
        // empty the shopping cart
        edd_empty_cart();
        edd_send_to_success_page();
    } else {
        // 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']);
    }
}
Esempio n. 3
0
/**
 * Processes the purchase data and uses the Manual Payment gateway to record
 * the transaction in the Purchase History
 *
 * @since 1.0
 * @param array $purchase_data Purchase Data
 * @return void
*/
function edd_manual_payment($purchase_data)
{
    if (!wp_verify_nonce($purchase_data['gateway_nonce'], 'edd-gateway')) {
        wp_die(__('Nonce verification has failed', 'edd'), __('Error', 'edd'), array('response' => 403));
    }
    /*
    * Purchase data comes in like this
    *
    $purchase_data = array(
    	'downloads' => array of download IDs,
    	'price' => total price of cart contents,
    	'purchase_key' =>  // Random key
    	'user_email' => $user_email,
    	'date' => date('Y-m-d H:i:s'),
    	'user_id' => $user_id,
    	'post_data' => $_POST,
    	'user_info' => array of user's information and used discount code
    	'cart_details' => array of cart details,
    );
    */
    $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'], 'user_info' => $purchase_data['user_info'], 'cart_details' => $purchase_data['cart_details'], 'status' => 'pending');
    // Record the pending payment
    $payment = edd_insert_payment($payment_data);
    if ($payment) {
        edd_update_payment_status($payment, 'publish');
        // Empty the shopping cart
        edd_empty_cart();
        edd_send_to_success_page();
    } else {
        edd_record_gateway_error(__('Payment Error', 'edd'), sprintf(__('Payment creation failed while processing a manual (free or test) purchase. Payment data: %s', 'edd'), json_encode($payment_data)), $payment);
        // 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']);
    }
}
function gateway_function_to_process_payment($purchase_data)
{
    // payment processing happens here
    // if (edd_is_test_mode()) {
    //
    // } else {
    //
    // }
    $purchase_summary = edd_get_purchase_summary($purchase_data);
    // var_dump($purchase_data);
    $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');
    // echo $purchase_data['purchase_key'];
    // Record the pending payment
    $payment = edd_insert_payment($payment_data);
    // Setup Yandex.Kassa arguments
    $yandex_args = array('ShopID' => edd_get_option('ya_shop_id', false), 'scid' => edd_get_option('ya_scid', false), 'cps_email' => $purchase_data['user_email'], 'Sum' => $purchase_data['price'], 'orderNumber' => $purchase_data['purchase_key'], 'orderDetails' => $purchase_data['cart_details'], 'CustName' => $purchase_data['user_info']['first_name'], 'paymentType' => 'AC');
    // Build query
    $yandex_redirect = 'https://money.yandex.ru/eshop.xml?';
    $yandex_redirect .= http_build_query($yandex_args);
    // Redirect
    // wp_redirect( $yandex_redirect );
    // if the merchant payment is complete, set a flag
    $merchant_payment_confirmed = false;
    if ($merchant_payment_confirmed) {
        // this is used when processing credit cards on site
        // once a transaction is successful, set the purchase to complete
        edd_update_payment_status($payment, 'complete');
        // go to the success page
        edd_send_to_success_page();
    } else {
        $fail = true;
        // payment wasn't recorded
    }
}
 /**
  * Process the purchase data and send to Payeezy
  *
  * @since 1.0
  * @return void
  */
 public function process_payment($purchase_data)
 {
     global $edd_options;
     $url = edd_is_test_mode() ? 'https://api-cert.payeezy.com/v1/transactions' : 'https://api.payeezy.com/v1/transactions';
     $payeezy = new Payeezy();
     $payeezy::setApiKey(edd_get_option('payeezy_api_key'));
     $payeezy::setApiSecret(edd_get_option('payeezy_api_secret'));
     $payeezy::setMerchantToken(edd_get_option('payeezy_token'));
     $payeezy::setUrl($url);
     $month = $purchase_data['card_info']['card_exp_month'];
     $month = $month > 9 ? $month : '0' . $month;
     // Payeezy requires two digits
     $year = substr($purchase_data['card_info']['card_exp_year'], -2);
     $card_type = edd_detect_cc_type($purchase_data['card_info']['card_number']);
     switch ($card_type) {
         case 'amex':
             $card_type = 'American Express';
             break;
     }
     $response = json_decode($payeezy->purchase(array('amount' => $purchase_data['price'], 'card_number' => $purchase_data['card_info']['card_number'], 'card_type' => $card_type, 'card_holder_name' => $purchase_data['card_info']['card_name'], 'card_cvv' => $purchase_data['card_info']['card_cvc'], 'card_expiry' => $month . $year, 'currency_code' => 'USD')));
     if ('failed' === $response->validation_status) {
         foreach ($response->Error->messages as $error) {
             edd_set_error($error->code, $error->description);
         }
         edd_send_back_to_checkout('?payment-mode=payeezy');
     } elseif ('success' === $response->validation_status) {
         if ('approved' === $response->transaction_status) {
             $payment_data = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['post_data']['edd_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_id = edd_insert_payment($payment_data);
             edd_update_payment_status($payment_id, 'publish');
             edd_set_payment_transaction_id($payment_id, $response->transaction_id);
             // Empty the shopping cart
             edd_empty_cart();
             edd_send_to_success_page();
         } else {
             edd_set_error('payeezy_error', sprintf(__('Transaction not approved. Status: %s', 'edd-payeezy'), $response->transaction_status));
             edd_send_back_to_checkout('?payment-mode=payeezy');
         }
     }
 }
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;
    }
}
 /**
  * Simple wrapper for the api call / response treatement
  *
  * @param string $url
  * @param array $fields
  */
 private function performPayment($url, $fields)
 {
     $result = $this->curlAction($url, $fields);
     $result = $this->getDataTransaction($result);
     if ($result['CODEREPONSE'] == '00000') {
         edd_update_payment_status($this->payment, 'publish');
         edd_complete_purchase($this->payment, 'publish', 'pending');
         foreach ($this->purchaseDatas['downloads'] as $download) {
             $log = edd_record_log('Payment', 'Payment', $download['id'], 'sale');
             update_post_meta($log, '_edd_log_payment_id', $this->payment);
         }
         edd_empty_cart();
         edd_send_to_success_page();
     } else {
         if ($result['CODEREPONSE'] == '00001' || $result['CODEREPONSE'] == '00003') {
             $settings = $this->getSettings();
             // if the first prod url failed try the second
             if (!$settings['preprod'] && $url !== $settings['url_prod_2'] && isset($settings['url_prod_2'])) {
                 $this->performPayment($settings['url_prod_2'], $fields);
             }
             edd_record_gateway_error(__('Payment Error', 'edd'), __('Payment gateways unavailable', 'edd'));
             edd_send_back_to_checkout('?payment-mode=' . $this->gateway);
         } else {
             edd_record_gateway_error(__('Payment Error', 'edd'), $result['COMMENTAIRE']);
             edd_send_back_to_checkout('?payment-mode=' . $this->gateway);
         }
     }
 }
Esempio n. 8
0
 /**
  * Update the status of the specified payment
  *
  * @param Pronamic_Pay_Payment $payment
  * @param boolean			  $can_redirect (optional, defaults to false)
  */
 public static function status_update(Pronamic_Pay_Payment $payment, $can_redirect = false)
 {
     $source_id = $payment->get_source_id();
     $data = new Pronamic_WP_Pay_Extensions_EDD_PaymentData($source_id, array());
     // Only update if order is not completed
     $should_update = edd_get_payment_status($source_id) !== Pronamic_WP_Pay_Extensions_EDD_EasyDigitalDownloads::ORDER_STATUS_PUBLISH;
     // Defaults
     $status = null;
     $note = null;
     $url = $data->get_normal_return_url();
     $status = $payment->get_status();
     switch ($status) {
         case Pronamic_WP_Pay_Statuses::CANCELLED:
             $url = $data->get_cancel_url();
             break;
         case Pronamic_WP_Pay_Statuses::EXPIRED:
             if ($should_update) {
                 edd_update_payment_status($source_id, Pronamic_WP_Pay_Extensions_EDD_EasyDigitalDownloads::ORDER_STATUS_ABANDONED);
             }
             $url = $data->get_error_url();
             break;
         case Pronamic_WP_Pay_Statuses::FAILURE:
             if ($should_update) {
                 edd_update_payment_status($source_id, Pronamic_WP_Pay_Extensions_EDD_EasyDigitalDownloads::ORDER_STATUS_FAILED);
             }
             $url = $data->get_error_url();
             break;
         case Pronamic_WP_Pay_Statuses::SUCCESS:
             if ($should_update) {
                 edd_insert_payment_note($source_id, __('Payment completed.', 'pronamic_ideal'));
                 /*
                  * @see https://github.com/easydigitaldownloads/Easy-Digital-Downloads/blob/2.2.8/includes/admin/payments/view-order-details.php#L36
                  * @see https://github.com/easydigitaldownloads/Easy-Digital-Downloads/blob/2.2.8/includes/admin/payments/view-order-details.php#L199-L206
                  * @see https://github.com/easydigitaldownloads/Easy-Digital-Downloads/blob/2.2.8/includes/payments/functions.php#L1312-L1332
                  * @see https://github.com/easydigitaldownloads/Easy-Digital-Downloads/blob/2.2.8/includes/gateways/paypal-standard.php#L555-L576
                  */
             }
             edd_update_payment_status($source_id, Pronamic_WP_Pay_Extensions_EDD_EasyDigitalDownloads::ORDER_STATUS_PUBLISH);
             edd_empty_cart();
             $url = $data->get_success_url();
             break;
         case Pronamic_WP_Pay_Statuses::OPEN:
             if ($should_update) {
                 edd_insert_payment_note($source_id, __('Payment open.', 'pronamic_ideal'));
             }
             break;
         default:
             if ($should_update) {
                 edd_insert_payment_note($source_id, __('Payment unknown.', 'pronamic_ideal'));
             }
             break;
     }
     if ($can_redirect) {
         wp_redirect($url, 303);
         exit;
     }
 }
/**
 * Process PayPal IPN Refunds
 *
 * @since 1.3.4
 * @param array   $data IPN Data
 * @return void
 */
function edd_process_paypal_refund($data, $payment_id = 0)
{
    // Collect payment details
    if (empty($payment_id)) {
        return;
    }
    if (get_post_status($payment_id) == 'refunded') {
        return;
        // Only refund payments once
    }
    $payment_amount = edd_get_payment_amount($payment_id);
    $refund_amount = $data['payment_gross'] * -1;
    if (number_format((double) $refund_amount, 2) < number_format((double) $payment_amount, 2)) {
        edd_insert_payment_note($payment_id, sprintf(__('Partial PayPal refund processed: %s', 'edd'), $data['parent_txn_id']));
        return;
        // This is a partial refund
    }
    edd_insert_payment_note($payment_id, sprintf(__('PayPal Payment #%s Refunded for reason: %s', 'edd'), $data['parent_txn_id'], $data['reason_code']));
    edd_insert_payment_note($payment_id, sprintf(__('PayPal Refund Transaction ID: %s', 'edd'), $data['txn_id']));
    edd_update_payment_status($payment_id, 'refunded');
}
 /**
  * Create sample purchase data for your EDD site
  *
  * ## OPTIONS
  *
  * --number: The number of purchases to create
  * --status=<status>: The status to create purchases as
  * --id=<product_id>: A specific product to create purchase data for
  * --price_id=<price_id>: A price ID of the specified product
  *
  * ## EXAMPLES
  *
  * wp edd payments create --number=10 --status=completed
  * wp edd payments create --number=10 --id=103
  */
 public function payments($args, $assoc_args)
 {
     $error = false;
     // At some point we'll likely add another action for payments
     if (!isset($args) || count($args) == 0) {
         $error = __('No action specified, did you mean', 'easy-digital-downloads');
     } elseif (isset($args) && !in_array('create', $args)) {
         $error = __('Invalid action specified, did you mean', 'easy-digital-downloads');
     }
     if ($error) {
         foreach ($assoc_args as $key => $value) {
             $query .= ' --' . $key . '=' . $value;
         }
         WP_CLI::error(sprintf($error . ' %s?', 'wp edd payments create' . $query));
         return;
     }
     // Setup some defaults
     $number = 1;
     $status = 'complete';
     $id = false;
     $price_id = false;
     if (count($assoc_args) > 0) {
         $number = array_key_exists('number', $assoc_args) ? absint($assoc_args['number']) : $number;
         $id = array_key_exists('id', $assoc_args) ? absint($assoc_args['id']) : $id;
         $price_id = array_key_exists('price_id', $assoc_args) ? absint($assoc_args['id']) : false;
         $tax = array_key_exists('tax', $assoc_args) ? floatval($assoc_args['tax']) : 0;
         $email = array_key_exists('email', $assoc_args) ? sanitize_email($assoc_args['email']) : '*****@*****.**';
         $fname = array_key_exists('fname', $assoc_args) ? sanitize_text_field($assoc_args['fname']) : 'Pippin';
         $lname = array_key_exists('lname', $assoc_args) ? sanitize_text_field($assoc_args['lname']) : 'Williamson';
         // Status requires a bit more validation
         if (array_key_exists('status', $assoc_args)) {
             $stati = array('publish', 'complete', 'pending', 'refunded', 'revoked', 'failed', 'abandoned', 'preapproval', 'cancelled');
             if (in_array($assoc_args['status'], $stati)) {
                 $status = $assoc_args['status'] == 'complete' ? 'publish' : $assoc_args['status'];
             } else {
                 WP_CLI::warning(sprintf(__("Invalid status '%s', defaulting to 'complete'", 'easy-digital-downloads'), $assoc_args['status']));
             }
         }
     }
     // Build the user info array
     $user_info = array('id' => 0, 'email' => $email, 'first_name' => $fname, 'last_name' => $lname, 'discount' => 'none');
     for ($i = 0; $i < $number; $i++) {
         $products = array();
         $total = 0;
         // No specified product
         if (!$id) {
             $products = get_posts(array('post_type' => 'download', 'orderby' => 'rand', 'order' => 'ASC', 'posts_per_page' => 1));
         } else {
             $product = get_post($id);
             if ($product->post_type != 'download') {
                 WP_CLI::error(__('Specified ID is not a product', 'easy-digital-downloads'));
                 return;
             }
             $products[] = $product;
         }
         $cart_details = array();
         // Create the purchases
         foreach ($products as $key => $download) {
             if (!is_a($download, 'WP_Post')) {
                 continue;
             }
             $options = array();
             $final_downloads = array();
             // Deal with variable pricing
             if (edd_has_variable_prices($download->ID)) {
                 $prices = edd_get_variable_prices($download->ID);
                 if (false === $price_id || !array_key_exists($price_id, (array) $prices)) {
                     $price_id = rand(0, count($prices) - 1);
                 }
                 $item_price = $prices[$price_id]['amount'];
                 $options['price_id'] = $price_id;
             } else {
                 $item_price = edd_get_download_price($download->ID);
             }
             $item_number = array('id' => $download->ID, 'quantity' => 1, 'options' => $options);
             $cart_details[$key] = array('name' => $download->post_title, 'id' => $download->ID, 'item_number' => $item_number, 'item_price' => edd_sanitize_amount($item_price), 'subtotal' => edd_sanitize_amount($item_price), 'price' => edd_sanitize_amount($item_price), 'quantity' => 1, 'discount' => 0, 'tax' => $tax);
             $final_downloads[$key] = $item_number;
             $total += $item_price;
         }
         $purchase_data = array('price' => edd_sanitize_amount($total), 'tax' => 0, 'purchase_key' => strtolower(md5(uniqid())), 'user_email' => $email, 'user_info' => $user_info, 'currency' => edd_get_currency(), 'downloads' => $final_downloads, 'cart_details' => $cart_details, 'status' => 'pending');
         $payment_id = edd_insert_payment($purchase_data);
         remove_action('edd_complete_purchase', 'edd_trigger_purchase_receipt', 999);
         if ($status != 'pending') {
             edd_update_payment_status($payment_id, $status);
         }
     }
     WP_CLI::success(sprintf(__('Created %s payments', 'easy-digital-downloads'), $number));
     return;
 }
 /**
  * Listen for PagSeguro IPN
  *
  * PagSeguro instant payment notifications.
  *
  * @return   void
  * @since    1.0
  */
 function listen_for_pagseguro_ipn()
 {
     global $edd_options;
     // check for incoming order id
     $code = isset($_POST['notificationCode']) && trim($_POST['notificationCode']) !== "" ? trim($_POST['notificationCode']) : null;
     $type = isset($_POST['notificationType']) && trim($_POST['notificationType']) !== "" ? trim($_POST['notificationType']) : null;
     // check for the edd-listener in the URL request
     if (is_null($code) || is_null($type)) {
         return;
     }
     // debug notification
     if ($this->debug === true) {
         wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 1: Incoming Notification'), var_export($_POST, true));
     }
     // get credentials
     $credentials = $this->get_credentials();
     // check credentials have been set
     if (is_null($credentials['email']) || is_null($credentials['token'])) {
         return;
     }
     // debug credentials
     if ($this->debug === true) {
         wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 2: Credentials'), 'OK');
     }
     // require PagSeguro files
     $this->load_pagseguro_sdk();
     // verify classes exists
     if (!class_exists('PagSeguroNotificationType')) {
         return;
     }
     // debug sdk
     if ($this->debug === true) {
         wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 3: SDK'), 'OK');
     }
     // get notification
     $notificationType = new PagSeguroNotificationType($type);
     $strType = $notificationType->getTypeFromValue();
     // debug type
     if ($this->debug === true) {
         wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 4: Notification Type'), var_export($strType, true));
     }
     // try to verify the notification
     try {
         // generate credentials
         $credentials = new PagSeguroAccountCredentials($credentials['email'], $credentials['token']);
         // notification service
         $transaction = PagSeguroNotificationService::checkTransaction($credentials, $code);
         // debug check
         if ($this->debug === true) {
             wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 5: Transaction Check'), 'OK');
         }
         // get both values
         $reference = $transaction->getReference();
         $status = $transaction->getStatus();
         // check there is an external reference
         if (isset($reference) && isset($status)) {
             // check for succesful status
             if ($status->getValue() == 3) {
                 // debug status
                 if ($this->debug === true) {
                     wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 6: Status Check'), 'OK');
                 }
                 // update succesful payment
                 edd_update_payment_status($reference, 'publish');
             } else {
                 // debug status
                 if ($this->debug === true) {
                     wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 6: Status Check'), 'ERROR');
                 }
             }
         } else {
             // debug reference/status error
             if ($this->debug === true) {
                 wp_mail(get_bloginfo('admin_email'), __('PagSeguro Gateway Debug 8: Reference/Status Check'), 'ERROR');
             }
         }
     } catch (Exception $e) {
         wp_mail(get_bloginfo('admin_email'), __('PagSeguro IPN Service Error', 'edd-pagseguro-gateway'), $e->getMessage());
         return;
     }
 }
Esempio n. 12
0
function mondca_process_payment($purchase_data)
{
    global $edd_options;
    // check there is a gateway name
    if (!isset($purchase_data['post_data']['edd-gateway'])) {
        return;
    }
    // collect payment data
    $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'], 'user_info' => $purchase_data['user_info'], 'cart_details' => $purchase_data['cart_details'], 'gateway' => 'mondca', 'status' => 'pending');
    if (!mondca_is_credit_card_number($purchase_data['post_data']['card_number'])) {
        edd_set_error('invalid_card_number', __('Credit Card Number is not valid.', 'mondca_patsatech'));
    }
    if (!mondca_is_correct_expire_date(date("y", strtotime($purchase_data['post_data']['card_exp_month'])), $purchase_data['post_data']['card_exp_year'])) {
        edd_set_error('invalid_card_expiry', __('Card Expire Date is not valid.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['card_cvc']) {
        edd_set_error('invalid_card_cvc', __('Card CVV is not entered.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['card_name']) {
        edd_set_error('invalid_card_name', __('CardHolder Name is not entered.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['card_address']) {
        edd_set_error('invalid_card_address', __('Billing Address is not entered.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['card_zip']) {
        edd_set_error('invalid_card_zip', __('Post Code is not entered.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['card_state']) {
        edd_set_error('invalid_card_state', __('State is not entered.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['card_city']) {
        edd_set_error('invalid_card_city', __('City is not entered.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['edd_first']) {
        edd_set_error('invalid_edd_first', __('First Name is not entered.', 'mondca_patsatech'));
    }
    if (!$purchase_data['post_data']['edd_last']) {
        edd_set_error('invalid_edd_last', __('Last Name is not entered.', 'mondca_patsatech'));
    }
    $errors = edd_get_errors();
    if ($errors) {
        // problems? send back
        edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
    } else {
        // record the pending payment
        $payment = edd_insert_payment($payment_data);
        // check payment
        if (!$payment) {
            // problems? send back
            edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
        } else {
            $store_id = $edd_options['mondca_storeid'];
            $api_token = $edd_options['mondca_apitoken'];
            $type = 'purchase';
            //$cust_id = $order->order_key;
            $amount = number_format($purchase_data['price'], 2, '.', '');
            $pan = $purchase_data['post_data']['card_number'];
            $cavv = $purchase_data['post_data']['card_cvc'];
            $expiry_date = substr($purchase_data['post_data']['card_exp_year'], -2) . sprintf("%02s", $purchase_data['post_data']['card_exp_month']);
            $crypt = '7';
            $status_check = 'false';
            $stamp = date("YdmHisB");
            $orderid = $stamp . '|' . $payment;
            /***************** Transactional Associative Array ********************/
            //$arr=explode("|",$teststring);
            $txnArray = array('type' => $type, 'order_id' => $orderid, 'cust_id' => '', 'amount' => $amount, 'pan' => $pan, 'expdate' => $expiry_date, 'cavv' => $cavv);
            /********************** Transaction Object ****************************/
            $mpgTxn = new mpgTransaction($txnArray);
            /************************ Request Object ******************************/
            $mpgRequest = new mpgRequest($mpgTxn);
            /*********************** HTTPSPost Object ****************************/
            $mpgHttpPost = new mpgHttpsPost($store_id, $api_token, $mpgRequest);
            /*************************** Response *********************************/
            $mpgResponse = $mpgHttpPost->getMpgResponse();
            $txnno = $mpgResponse->getTxnNumber();
            $receipt = explode("|", $mpgResponse->getReceiptId());
            $respcode = $mpgResponse->getResponseCode();
            $refnum = $mpgResponse->getReferenceNum();
            $auth = $mpgResponse->getAuthCode();
            $mess = $mpgResponse->getMessage();
            if ($respcode < '50' && $respcode > '0') {
                edd_update_payment_status($payment, 'publish');
                edd_insert_payment_note($payment, sprintf(__('Moneris CA Payment %s. The Transaction Id is %s', 'mondca_patsatech'), $mess, $txnno));
                edd_empty_cart();
                edd_send_to_success_page();
            } else {
                edd_insert_payment_note($payment, sprintf(__('Transaction Error. Message : %s', 'mondca_patsatech'), $mess));
                edd_set_error('error_tranasction_failed', sprintf(__('Transaction Error. Message : %s', 'mondca_patsatech'), $mess));
                edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
            }
        }
    }
}
function edd_veritrans_notification()
{
    global $edd_options;
    require_once plugin_dir_path(__FILE__) . '/lib/Veritrans.php';
    if (edd_is_test_mode()) {
        // set test credentials here
        // error_log('masuk test mode');  //debugan
        Veritrans_Config::$serverKey = $edd_options['vt_sandbox_api_key'];
        Veritrans_Config::$isProduction = false;
    } else {
        // set test credentials here
        // error_log('masuk production mode'); //debugan
        Veritrans_Config::$serverKey = $edd_options['vt_production_api_key'];
        Veritrans_Config::$isProduction = true;
    }
    // error_log('serverKey: '.Veritrans_Config::$serverKey); //debugan
    // error_log('isProduction: '.Veritrans_Config::$isProduction); //debugan
    $notif = new Veritrans_Notification();
    // error_log('$notif '.print_r($notif)); //debugan
    $transaction = $notif->transaction_status;
    $fraud = $notif->fraud_status;
    $order_id = $notif->order_id;
    // error_log('$order_id '.$order_id); //debugan
    // error_log('$fraud '.$fraud); //debugan
    // error_log('$transaction '.$transaction); //debugan
    if ($transaction == 'capture') {
        if ($fraud == 'challenge') {
            // TODO Set payment status in merchant's database to 'challenge'
            edd_update_payment_status($order_id, 'challenge');
            // error_log('challenge gan!'); //debugan
        } else {
            if ($fraud == 'accept') {
                edd_update_payment_status($order_id, 'complete');
                // error_log('accepted gan!'); //debugan
            }
        }
    } else {
        if ($notif->transaction_status != 'credit_card' && $transaction == 'settlement') {
            edd_update_payment_status($order_id, 'complete');
            // error_log('accepted gan!'); //debugan
        } else {
            if ($transaction == 'cancel') {
                edd_update_payment_status($order_id, 'cancel');
                // error_log('cancelled gan!'); //debugan
            } else {
                if ($transaction == 'deny') {
                    edd_update_payment_status($order_id, 'failed');
                    // error_log('denied gan!'); //debugan
                }
            }
        }
    }
}
function sagepay_direct_ipn()
{
    global $edd_options;
    if (isset($_REQUEST['MD']) && isset($_REQUEST['PaRes']) && $_GET['sagepay_direct'] == 'ipn') {
        $request_array = array('MD' => $_REQUEST['MD'], 'PARes' => $_REQUEST['PaRes'], 'VendorTxCode' => EDD()->session->get('sagepay_vtc'));
        $request = http_build_query($request_array);
        if ($edd_options['sagepay_direct_mode'] == 'test') {
            $gateway_url = 'https://test.sagepay.com/gateway/service/direct3dcallback.vsp';
        } else {
            if ($edd_options['sagepay_direct_mode'] == 'live') {
                $gateway_url = 'https://live.sagepay.com/gateway/service/direct3dcallback.vsp';
            }
        }
        $response = wp_remote_post($gateway_url, array('body' => $request, 'method' => 'POST', 'sslverify' => false));
        if (!is_wp_error($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300) {
            $resp = array();
            $lines = preg_split('/\\r\\n|\\r|\\n/', $response['body']);
            foreach ($lines as $line) {
                $key_value = preg_split('/=/', $line, 2);
                if (count($key_value) > 1) {
                    $resp[trim($key_value[0])] = trim($key_value[1]);
                }
            }
            if ($resp['Status'] == "OK" || $resp['Status'] == "REGISTERED" || $resp['Status'] == "AUTHENTICATED") {
                edd_update_payment_status(EDD()->session->get('sagepay_oid'), 'publish');
                edd_set_payment_transaction_id($payment, $resp['VPSTxId']);
                edd_empty_cart();
                edd_send_to_success_page();
            } else {
                if ($resp['Status'] == "3DAUTH") {
                    if ($resp['3DSecureStatus'] == 'OK') {
                        if (isset($resp['ACSURL']) && isset($resp['MD'])) {
                            $array = array('PaReq' => $resp['PAReq'], 'MD' => $resp['MD'], 'TermUrl' => trailingslashit(home_url()) . '?sagepay_direct=ipn');
                            $sagepay_arg_array = array();
                            foreach ($array as $key => $value) {
                                $sagepay_arg_array[] = '<input type="hidden" name="' . esc_attr($key) . '" value="' . esc_attr($value) . '" />';
                            }
                            echo '<form action="' . $resp['ACSURL'] . '" method="post" name="sagepay_direct_3dsecure_form" >
								' . implode('', $sagepay_arg_array) . '
							</form>		
							<b> Please wait while you are being redirected.</b>			
							<script type="text/javascript" event="onload">
								ocument.sagepay_direct_3dsecure_form.submit();
							</script>';
                        }
                    }
                } else {
                    if (isset($resp['StatusDetail'])) {
                        edd_set_error('error_tranasction_failed', __('Transaction Failed. ' . $resp['StatusDetail'], 'sagepay_direct_patsatech'));
                        edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
                    } else {
                        edd_set_error('error_tranasction_failed', __('Transaction Failed with ' . $resp['Status'] . ' status for Unknown Reason.', 'sagepay_direct_patsatech'));
                        edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
                    }
                }
            }
        } else {
            edd_set_error('error_tranasction_failed', __('Gateway Error. Please Notify the Store Owner about this error.', 'sagepay_direct_patsatech'));
            edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
        }
    }
}
 function gourledd_gourlcallback($user_id, $order_id, $payment_details, $box_status)
 {
     if (!in_array($box_status, array("cryptobox_newrecord", "cryptobox_updated"))) {
         return false;
     }
     if (strpos($order_id, "order") === 0) {
         $payment_id = substr($order_id, 5);
     } else {
         return false;
     }
     if (!$user_id || $payment_details["status"] != "payment_received") {
         return false;
     }
     $payment = get_post($payment_id);
     if (!$payment || !$payment->post_status) {
         return false;
     }
     $coinName = ucfirst($payment_details["coinname"]);
     $amount = $payment_details["amount"] . " " . $payment_details["coinlabel"] . "&#160; ( \$" . $payment_details["amountusd"] . " )";
     $payID = $payment_details["paymentID"];
     $confirmed = $payment_details["is_confirmed"] ? __('Yes', GOURLEDD) : __('No', GOURLEDD);
     // a. New Payment Received - Awaiting Transaction Confirmation...
     if ($box_status == "cryptobox_newrecord") {
         // Save Log
         edd_insert_payment_note($payment_id, sprintf(__("<b>%s</b> Payment Received <br/>%s <br/><a href='%s'>Payment ID: %s</a>. <br/>Awaiting network confirmation...", GOURLEDD), __($coinName, GOURLEDD), $amount, GOURL_ADMIN . GOURL . "payments&s=payment_" . $payID, $payID) . ' <br/>');
         edd_set_payment_transaction_id($payment_id, $payment_details["tx"]);
     }
     // b. Existing Payment Confirmed (6+ transaction confirmations)
     if ($payment_details["is_confirmed"]) {
         // Save Log
         edd_insert_payment_note($payment_id, sprintf(__("%s Payment ID: <a href='%s'>%s</a> - <b>Confirmed</b>", GOURLEDD), __($coinName, GOURLEDD), GOURL_ADMIN . GOURL . "payments&s=payment_" . $payID, $payID) . ' <br/>');
     }
     // c. Update Status to Completed
     if ($payment->post_status != 'publish') {
         edd_update_payment_status($payment_id, 'publish');
     }
     return true;
 }
Esempio n. 16
0
 /**
  * Make a payment
  *
  * @return bool|int Payment ID if created succefully, false if not.
  */
 protected function make_payment()
 {
     /** @var array */
     global $edd_options;
     $data = array('status' => 'publish', 'tax' => 0, 'first' => $this->user->first_name, 'last' => $this->user->last_name, 'downloads' => array());
     $user_id = $this->user->ID;
     $email = $this->user->user_email;
     $user_first = sanitize_text_field($data['first']);
     $user_last = sanitize_text_field($data['last']);
     $user_info = array('id' => $user_id, 'email' => $email, 'first_name' => $user_first, 'last_name' => $user_last, 'discount' => 'none');
     $price = 0;
     $cart_details = array();
     $total = 0;
     $download = ids::$trial_id;
     $cart_details[$download] = array('name' => get_the_title($download), 'id' => $download, 'item_number' => $download, 'price' => $price, 'subtotal' => $price, 'quantity' => 1, 'tax' => 0, 'price_id' => ids::$trial_price_id);
     $total = $price;
     $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'));
     }
     $purchase_data = array('price' => edd_sanitize_amount($total), 'tax' => 0, '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);
     $keys = \EDD_Software_Licensing::instance()->get_licenses_of_purchase($payment_id);
     if (is_array($keys) && isset($keys[0]) && is_object($keys[0])) {
         $this->license = $keys[0]->ID;
         update_post_meta($this->license, '_ingsl_is_trial', 1);
         update_post_meta($this->license, '_ingsl_upsold', 0);
     }
     // increase stats and log earnings
     edd_update_payment_status($payment_id, $data['status']);
     return $payment_id;
 }
 /**
  * Process payment submission
  *
  * @access      public
  * @since       1.0.0
  * @param       array $purchase_data The data for a specific purchase
  * @return      void
  */
 public function process_payment($purchase_data)
 {
     if (!wp_verify_nonce($purchase_data['gateway_nonce'], 'edd-gateway')) {
         wp_die(__('Nonce verification has failed', 'edd-wallet'), __('Error', 'edd-wallet'), array('response' => 403));
     }
     $error = false;
     // Double check that we can afford this item
     $value = edd_wallet()->wallet->balance($purchase_data['user_email']);
     if ($value < $purchase_data['price']) {
         edd_record_gateway_error(__('Wallet Gateway Error', 'edd-wallet'), __('User wallet has insufficient funds.', 'edd-wallet'), 0);
         edd_set_error('wallet_error', __('Insufficient funds.', 'edd-wallet'));
         edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
     }
     $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'], 'user_info' => $purchase_data['user_info'], 'cart_details' => $purchase_data['cart_details'], 'status' => 'pending');
     // Record the pending payment
     $payment = edd_insert_payment($payment_data);
     if ($payment) {
         // Update payment status
         edd_update_payment_status($payment, 'publish');
         // Withdraw the funds
         edd_wallet()->wallet->withdraw($purchase_data['user_info']['id'], $payment_data['price'], 'withdrawal', $payment);
         edd_empty_cart();
         edd_send_to_success_page();
     } else {
         edd_record_gateway_error(__('Wallet Gateway Error', 'edd-wallet'), sprintf(__('Payment creation failed while processing a Wallet purchase. Payment data: %s', 'edd-wallet'), json_encode($payment_data)), $payment);
         edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
     }
 }
 /**
  * process_payment function.
  *
  * Submit payment and handle response
  *
  * @access public
  */
 public function process_payment($purchase_data)
 {
     //edd_options contains the values of the admin settings
     global $edd_options;
     if (edd_is_test_mode()) {
         $paystack_public = $edd_options['test_public_key'];
         $paystack_secret = $edd_options['test_secret_key'];
     } else {
         $paystack_public = $edd_options['live_public_key'];
         $paystack_secret = $edd_options['live_secret_key'];
     }
     //txcode POSTed from payment form
     $txcode = isset($_POST['txcode']) ? $_POST['txcode'] : null;
     /**
      * check for checkout fields errors
      *
      */
     // check if there is a gateway name
     if (!isset($purchase_data['post_data']['edd-gateway'])) {
         return;
     }
     // get EDD errors
     $errors = edd_get_errors();
     // Paystack errors
     $paystack_error = null;
     /**
      * end checkout fields error checks
      */
     // if no errors
     if (!$errors) {
         // record purchase summary
         $summary = edd_get_purchase_summary($purchase_data, false);
         // cart quantity
         $quantity = edd_get_cart_quantity();
         /**
          * setup the payment data
          */
         $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_options['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_data);
         $order_id = $payment;
         if (!$payment) {
             // Record the error
             edd_record_gateway_error(__('Payment Error', 'po_paystack'), sprintf(__('Payment creation failed before loading Paystack. Payment data: %s', 'po_paystack'), json_encode($payment_data)), $payment);
             // Problems? send back
             edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
         } else {
             if (!$order_id || !$paystack_public) {
                 edd_record_gateway_error(__('Invalid transaction', 'po_paystack'), sprintf(__('Invalid transaction; possible hack attempt. Payment data: %s', 'po_paystack'), json_encode($payment_data)), $payment);
                 edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
             }
             if (!$txcode) {
                 $error = "Error! An invalid transaction code was reported.";
                 edd_update_payment_status($order_id, 'failed');
                 throw new Exception(__($error));
             } else {
                 $amount = $payment_data['price'] * 100;
                 //convert to kobo
                 if (intval($amount) < 100) {
                     $error = "Invalid transaction. Paystack cannot process orders under 100 kobo in value. Transaction code: " . $txcode;
                     edd_update_payment_status($order_id, 'failed');
                     throw new Exception(__($error));
                 }
                 $email = $payment_data['user_email'];
                 require_once dirname(__FILE__) . '/paystack-class/Paystack.php';
                 // Create the library object
                 $paystack = new Paystack($paystack_secret);
                 list($headers, $body, $code) = $paystack->transaction->verify(['reference' => $txcode]);
                 $resp = $body;
                 if (array_key_exists("status", $resp) && !$resp["status"]) {
                     $error = "Failed with message from Paystack: " . $resp["message"];
                     edd_insert_payment_note($order_id, __($error));
                     edd_update_payment_status($order_id, 'failed');
                     throw new Exception(__($error));
                 } elseif ($resp["data"]["customer"]["email"] !== $email) {
                     $error = "Invalid customer email associated with Transaction code:" . $txcode . " and Paystack reference: " . $resp["data"]['reference'] . ". Possible hack attempt.";
                     edd_insert_payment_note($order_id, __($error));
                     edd_update_payment_status($order_id, 'failed');
                     throw new Exception(__($error));
                 } else {
                     // Authcode and Authdesc. To be used in future version, for recurrent billing
                     $authcode = $resp["data"]["authorization"]["authorization_code"];
                     $authdesc = $resp["data"]["authorization"]["description"];
                     $paystackref = $resp["data"]["reference"];
                     // Complete the order. once a transaction is successful, set the purchase status to complete
                     edd_update_payment_status($payment, 'complete');
                     // record transaction ID, or any other notes you need
                     edd_insert_payment_note($payment, "Paystack.co payment completed (using " . strtoupper($authdesc) . " and Transaction code:" . $txcode . ") with Paystack reference:" . $paystackref);
                     // go to the success page
                     edd_send_to_success_page();
                 }
             }
         }
     } else {
         // errors present
         $fail = true;
     }
     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']);
     }
 }
Esempio n. 19
0
/**
 * Confirm the Payment through IPN
 *
 */
function edds_confirm_payza_payment()
{
    global $edd_options;
    if (isset($_GET['edd-listener']) && $_GET['edd-listener'] === 'PAYZA_IPN') {
        if (isset($_POST['token'])) {
            require_once EDD_PAYZA_PLUGIN_DIR . '/payza.gateway.php';
            $ipn_handler = new wp_payza_ipn(edd_get_currency(), true);
            $transaction_id = $ipn_handler->handle_ipn($_POST['token']);
            if ($transaction_id) {
                edd_update_payment_status($transaction_id, 'publish');
            }
        }
    }
}
     $log_str .= $temp_log_str;
     echo $temp_log_str;
     continue;
 }
 // If no products found in the order then also skip the order.
 if (empty($downloads) || empty($cart_details)) {
     $temp_log_str = "\nNo Products found. So order not migrated ...\n";
     $log_str .= $temp_log_str;
     echo $temp_log_str;
     continue;
 }
 $data = array('currency' => 'USD', 'downloads' => $downloads, 'cart_details' => $cart_details, 'price' => get_post_meta($order->id, '_order_total', true), 'purchase_key' => get_post_meta($order->id, '_order_key', true), 'user_info' => array('id' => $user_id, 'email' => $email, 'first_name' => get_post_meta($order->id, '_billing_first_name', true), 'last_name' => get_post_meta($order->id, '_billing_last_name', true), 'discount' => !empty($wc_coupon) && isset($wc_edd_coupon_map[$wc_coupon->id]) && !empty($wc_edd_coupon_map[$wc_coupon->id]) ? $wc_coupon->code : '', 'address' => array('line1' => get_post_meta($order->id, '_billing_address_1', true), 'line2' => get_post_meta($order->id, '_billing_address_2', true), 'city' => get_post_meta($order->id, '_billing_city', true), 'zip' => get_post_meta($order->id, '_billing_postcode', true), 'country' => get_post_meta($order->id, '_billing_country', true), 'state' => get_post_meta($order->id, '_billing_state', true))), 'user_id' => $user_id, 'user_email' => $email, 'status' => 'pending', 'parent' => $o->post_parent, 'post_date' => $o->post_date, 'gateway' => get_post_meta($order->id, '_payment_method', true));
 $payment_id = edd_insert_payment($data);
 remove_action('edd_update_payment_status', 'edd_trigger_purchase_receipt', 10);
 remove_action('edd_complete_purchase', 'edd_trigger_purchase_receipt', 999);
 edd_update_payment_status($payment_id, $status);
 $wc_edd_order_map[$o->ID] = $payment_id;
 $temp_log_str = "\nWC Order migrated ...\n";
 $log_str .= $temp_log_str;
 echo $temp_log_str;
 // Update relavent data.
 update_post_meta($payment_id, '_edd_payment_user_ip', get_post_meta($order->id, '_customer_ip_address', true));
 update_post_meta($payment_id, '_wc_order_key', get_post_meta($order->id, '_order_key', true));
 update_post_meta($payment_id, '_edd_payment_mode', 'live');
 update_post_meta($payment_id, '_edd_completed_date', get_post_meta($order->id, '_completed_date', true));
 update_post_meta($payment_id, '_wc_order_id', $o->ID);
 // Order Notes
 $args = array('post_id' => $order->id, 'approve' => 'approve');
 $wc_notes = get_comments($args);
 $temp_log_str = "\nOrder Notes fetched ...\n";
 $log_str .= $temp_log_str;
 /**
  * Process IPN messages from Amazon
  *
  * @access public
  * @since  2.4
  * @return void
  */
 public function process_ipn()
 {
     if (!isset($_GET['edd-listener']) || $_GET['edd-listener'] !== 'amazon') {
         return;
     }
     if (isset($_GET['state'])) {
         return;
     }
     // Get the IPN headers and Message body
     $headers = getallheaders();
     $body = file_get_contents('php://input');
     $this->doing_ipn = true;
     try {
         $ipn = new IpnHandler($headers, $body);
         $data = $ipn->toArray();
         $seller_id = $data['SellerId'];
         if ($seller_id != edd_get_option('amazon_seller_id', '')) {
             wp_die(__('Invalid Amazon seller ID', 'edd'), __('IPN Error', 'edd'), array('response' => 401));
         }
         switch ($data['NotificationType']) {
             case 'OrderReferenceNotification':
                 break;
             case 'PaymentAuthorize':
                 break;
             case 'PaymentCapture':
                 $key = $data['CaptureDetails']['CaptureReferenceId'];
                 $status = $data['CaptureDetails']['CaptureStatus']['State'];
                 if ('Declined' === $status) {
                     $payment_id = edd_get_purchase_id_by_key($key);
                     edd_update_payment_status($payment_id, 'failed');
                     edd_insert_payment_note($payment_id, __('Capture declined in Amazon', 'edd'));
                 }
                 break;
             case 'PaymentRefund':
                 $trans_id = substr($data['RefundDetails']['AmazonRefundId'], 0, 19);
                 $status = $data['RefundDetails']['RefundStatus']['State'];
                 if ('Completed' === $status) {
                     $payment_id = edd_get_purchase_id_by_transaction_id($trans_id);
                     edd_update_payment_status($payment_id, 'refunded');
                     edd_insert_payment_note($payment_id, sprintf(__('Refund completed in Amazon. Refund ID: %s', 'edd'), $data['RefundDetails']['AmazonRefundId']));
                 }
                 break;
         }
     } catch (Exception $e) {
         wp_die($e->getErrorMessage(), __('IPN Error', 'edd'), array('response' => 401));
     }
 }
Esempio n. 22
0
/**
 * Update Edited Purchase
 *
 * Updates the purchase data for a payment.
 * Used primarily for adding new downloads to a purchase.
 *
 * @access      private
 * @since       1.0
 * @return      void
*/
function edd_update_edited_purchase($data)
{
    if (wp_verify_nonce($data['edd-payment-nonce'], 'edd_payment_nonce')) {
        $payment_id = $_POST['payment-id'];
        $payment_data = edd_get_payment_meta($payment_id);
        if (isset($_POST['edd-purchased-downloads'])) {
            $updated_downloads = array();
            foreach ($_POST['edd-purchased-downloads'] as $download) {
                if (isset($payment_data['cart_details'])) {
                    $updated_downloads[] = array('id' => $download);
                } else {
                    $updated_downloads[] = $download;
                }
            }
            $payment_data['downloads'] = serialize($updated_downloads);
        }
        $payment_data['email'] = strip_tags($_POST['edd-buyer-email']);
        update_post_meta($payment_id, '_edd_payment_meta', $payment_data);
        update_post_meta($payment_id, '_edd_payment_user_email', $payment_data['email']);
        if (isset($_POST['edd-payment-note'])) {
            $note = wp_kses($_POST['edd-payment-note'], array());
            $note_id = edd_insert_payment_note($payment_id, $note);
        }
        if ($_POST['edd-old-status'] != $_POST['edd-payment-status']) {
            edd_update_payment_status($payment_id, $_POST['edd-payment-status']);
        }
        if ($_POST['edd-payment-status'] == 'publish' && isset($_POST['edd-payment-send-email'])) {
            // send the purchase receipt
            edd_email_purchase_receipt($payment_id, false);
        }
    }
}
function sofort_ipn()
{
    global $edd_options;
    if (isset($_GET['sofort']) && $_GET['sofort'] == 'ipn') {
        require_once 'library/sofortLib.php';
        $notification = new SofortLib_Notification();
        $notification->getNotification();
        $transactionId = $notification->getTransactionId();
        if ($transactionId) {
            // fetch some information for the transaction id retrieved above
            $transactionData = new SofortLib_TransactionData(trim($edd_options['sofort_config_id']));
            $transactionData->setTransaction($transactionId);
            $transactionData->sendRequest();
            $reason = $transactionData->getReason();
            $payment_id = str_replace('CartId ', '', $reason[0]);
            edd_update_payment_status($payment_id, 'publish');
            edd_insert_payment_note($payment_id, 'Payment Successful. Transaction ID is ' . $transactionId);
        }
        exit;
    }
}
Esempio n. 24
0
/**
 * 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
    }
}
Esempio n. 25
0
/**
 * Updates week-old+ 'pending' orders to 'abandoned'
 *
 * @since 1.6
 * @return void
*/
function edd_mark_abandoned_orders()
{
    $args = array('status' => 'pending', 'number' => -1);
    add_filter('posts_where', 'edd_filter_where_older_than_week');
    $payments = edd_get_payments($args);
    remove_filter('posts_where', 'edd_filter_where_older_than_week');
    if ($payments) {
        foreach ($payments as $payment) {
            if ('pending' === $payment->post_status) {
                edd_update_payment_status($payment->ID, 'abandoned');
            }
        }
    }
}
Esempio n. 26
0
/**
 * Mark payments as Failed when returning to the Failed Transaction page
 *
 * @access      public
 * @since       1.9.9
 * @return      void
*/
function edd_listen_for_failed_payments()
{
    $failed_page = edd_get_option('failure_page', 0);
    if (!empty($failed_page) && is_page($failed_page) && !empty($_GET['payment-id'])) {
        $payment_id = absint($_GET['payment-id']);
        $payment = get_post($payment_id);
        $status = edd_get_payment_status($payment);
        if ($status && 'pending' === strtolower($status)) {
            edd_update_payment_status($payment_id, 'failed');
        }
    }
}
Esempio n. 27
0
 /**
  * process voguepay response and then redirect to purchase confirmation page.
  * @global $edd_options Array of all the EDD Options
  * @return void
  */
 public function process_voguepay_response()
 {
     global $edd_options;
     // Get all response data coming from voguepay.
     $post_data = $_POST;
     // Get payment id.
     $payment_id = $_GET['payment-id'];
     // Get Payment status code.
     $payment_status_code = intval($post_data['status']);
     if (empty($payment_id)) {
         return;
     }
     if ('voguepay' != edd_get_payment_gateway($payment_id)) {
         return;
         // this isn't a voguepay response.
     }
     // create payment note.
     $payment_note = sprintf(__('voguepay Reference ID: %s <br> Merchant Reference ID: %s', 'edd-voguepay'), $post_data['voguepay_refID'], $post_data['merchant_ref']);
     $payment_note .= '<br> Message: ' . $post_data['status_msg'];
     if (0 == $payment_status_code) {
         edd_insert_payment_note($payment_id, $payment_note);
         edd_set_payment_transaction_id($payment_id, $post_data['voguepay_refID']);
         edd_update_payment_status($payment_id, 'publish');
         $confirm_url = add_query_arg(array('payment-confirmation' => 'voguepay', 'payment-id' => $payment_id), get_permalink($edd_options['success_page']));
         wp_redirect($confirm_url);
     } else {
         edd_insert_payment_note($payment_id, $payment_note);
         edd_set_payment_transaction_id($payment_id, $post_data['voguepay_refID']);
         edd_update_payment_status($payment_id, 'failed');
         wp_redirect(edd_get_failed_transaction_uri('?payment-id=' . $payment_id));
     }
     die;
 }
/**
 * Update Edited Purchase
 *
 * Updates the purchase data for a payment.
 * Used primarily for adding new downloads to a purchase.
 *
 * @since 1.0
 * @param $data Arguments passed
 * @return void
 */
function edd_update_edited_purchase($data)
{
    if (wp_verify_nonce($data['edd-payment-nonce'], 'edd_payment_nonce')) {
        $payment_id = $_POST['payment-id'];
        $payment_data = edd_get_payment_meta($payment_id);
        if (isset($_POST['edd-purchased-downloads'])) {
            $download_list = array();
            foreach ($_POST['edd-purchased-downloads'] as $key => $download) {
                if (isset($download['options']['price_id'])) {
                    $download_list[] = array('id' => $key, 'options' => array('price_id' => $download['options']['price_id']));
                } else {
                    $download_list[] = array('id' => $download);
                }
            }
            $payment_data['downloads'] = serialize($download_list);
        }
        $user_info = maybe_unserialize($payment_data['user_info']);
        $user_info['email'] = strip_tags($_POST['edd-buyer-email']);
        $user_info['user_id'] = strip_tags(intval($_POST['edd-buyer-user-id']));
        $payment_data['user_info'] = serialize($user_info);
        update_post_meta($payment_id, '_edd_payment_meta', $payment_data);
        update_post_meta($payment_id, '_edd_payment_user_email', strip_tags($_POST['edd-buyer-email']));
        update_post_meta($payment_id, '_edd_payment_user_id', strip_tags(intval($_POST['edd-buyer-user-id'])));
        if (!empty($_POST['edd-payment-note'])) {
            $note = wp_kses($_POST['edd-payment-note'], array());
            $note_id = edd_insert_payment_note($payment_id, $note);
        }
        if (!empty($_POST['edd-payment-amount'])) {
            update_post_meta($payment_id, '_edd_payment_total', sanitize_text_field(edd_sanitize_amount($_POST['edd-payment-amount'])));
        }
        if (!empty($_POST['edd-unlimited-downloads'])) {
            add_post_meta($payment_id, '_unlimited_file_downloads', '1');
        } else {
            delete_post_meta($payment_id, '_unlimited_file_downloads');
        }
        if ($_POST['edd-old-status'] != $_POST['edd-payment-status']) {
            edd_update_payment_status($payment_id, $_POST['edd-payment-status']);
        }
        if ($_POST['edd-payment-status'] == 'publish' && isset($_POST['edd-payment-send-email'])) {
            // Send the purchase receipt
            edd_email_purchase_receipt($payment_id, false);
        }
        do_action('edd_update_edited_purchase', $payment_id);
    }
}
 /**
  * Process the bulk actions
  *
  * @access public
  * @since 1.4
  * @return void
  */
 public function process_bulk_action()
 {
     $ids = isset($_GET['payment']) ? $_GET['payment'] : false;
     $action = $this->current_action();
     if (!is_array($ids)) {
         $ids = array($ids);
     }
     if (empty($action)) {
         return;
     }
     foreach ($ids as $id) {
         // Detect when a bulk action is being triggered...
         if ('delete' === $this->current_action()) {
             edd_delete_purchase($id);
         }
         if ('set-status-publish' === $this->current_action()) {
             edd_update_payment_status($id, 'publish');
         }
         if ('set-status-pending' === $this->current_action()) {
             edd_update_payment_status($id, 'pending');
         }
         if ('set-status-refunded' === $this->current_action()) {
             edd_update_payment_status($id, 'refunded');
         }
         if ('set-status-revoked' === $this->current_action()) {
             edd_update_payment_status($id, 'revoked');
         }
         if ('set-status-failed' === $this->current_action()) {
             edd_update_payment_status($id, 'failed');
         }
         if ('set-status-abandoned' === $this->current_action()) {
             edd_update_payment_status($id, 'abandoned');
         }
         if ('set-status-preapproval' === $this->current_action()) {
             edd_update_payment_status($id, 'preapproval');
         }
         if ('set-status-cancelled' === $this->current_action()) {
             edd_update_payment_status($id, 'cancelled');
         }
         if ('resend-receipt' === $this->current_action()) {
             edd_email_purchase_receipt($id, false);
         }
         do_action('edd_payments_table_do_bulk_action', $id, $this->current_action());
     }
 }
Esempio n. 30
0
/**
 * Process the payment details edit
 *
 * @access      private
 * @since       1.9
 * @return      void
*/
function edd_update_payment_details($data)
{
    if (!current_user_can('edit_shop_payments', $data['edd_payment_id'])) {
        wp_die(__('You do not have permission to edit this payment record', 'easy-digital-downloads'), __('Error', 'easy-digital-downloads'), array('response' => 403));
    }
    check_admin_referer('edd_update_payment_details_nonce');
    // Retrieve the payment ID
    $payment_id = absint($data['edd_payment_id']);
    // Retrieve existing payment meta
    $meta = edd_get_payment_meta($payment_id);
    $user_info = edd_get_payment_meta_user_info($payment_id);
    $status = $data['edd-payment-status'];
    $unlimited = isset($data['edd-unlimited-downloads']) ? '1' : '';
    $date = sanitize_text_field($data['edd-payment-date']);
    $hour = sanitize_text_field($data['edd-payment-time-hour']);
    // Restrict to our high and low
    if ($hour > 23) {
        $hour = 23;
    } elseif ($hour < 0) {
        $hour = 00;
    }
    $minute = sanitize_text_field($data['edd-payment-time-min']);
    // Restrict to our high and low
    if ($minute > 59) {
        $minute = 59;
    } elseif ($minute < 0) {
        $minute = 00;
    }
    $address = array_map('trim', $data['edd-payment-address'][0]);
    $curr_total = edd_sanitize_amount(edd_get_payment_amount($payment_id));
    $new_total = edd_sanitize_amount($_POST['edd-payment-total']);
    $tax = isset($_POST['edd-payment-tax']) ? edd_sanitize_amount($_POST['edd-payment-tax']) : 0;
    $date = date('Y-m-d', strtotime($date)) . ' ' . $hour . ':' . $minute . ':00';
    $curr_customer_id = sanitize_text_field($data['edd-current-customer']);
    $new_customer_id = sanitize_text_field($data['customer-id']);
    // Setup purchased Downloads and price options
    $updated_downloads = isset($_POST['edd-payment-details-downloads']) ? $_POST['edd-payment-details-downloads'] : false;
    if ($updated_downloads && !empty($_POST['edd-payment-downloads-changed'])) {
        $downloads = array();
        $cart_details = array();
        $i = 0;
        foreach ($updated_downloads as $download) {
            if (empty($download['amount'])) {
                $download['amount'] = '0.00';
            }
            $item = array();
            $item['id'] = absint($download['id']);
            $item['quantity'] = absint($download['quantity']) > 0 ? absint($download['quantity']) : 1;
            $price_id = (int) $download['price_id'];
            $has_log = absint($download['has_log']);
            if ($price_id !== false && edd_has_variable_prices($item['id'])) {
                $item['options'] = array('price_id' => $price_id);
            }
            $downloads[] = $item;
            $cart_item = array();
            $cart_item['item_number'] = $item;
            $item_price = round($download['amount'] / $item['quantity'], edd_currency_decimal_filter());
            $cart_details[$i] = array('name' => get_the_title($download['id']), 'id' => $download['id'], 'item_number' => $item, 'price' => $download['amount'], 'item_price' => $item_price, 'subtotal' => $download['amount'], 'quantity' => $download['quantity'], 'discount' => 0, 'tax' => 0);
            // If this item doesn't have a log yet, add one for each quantity count
            if (empty($has_log)) {
                $log_date = date('Y-m-d G:i:s', current_time('timestamp', true));
                $price_id = $price_id !== false ? $price_id : 0;
                $y = 0;
                while ($y < $download['quantity']) {
                    edd_record_sale_in_log($download['id'], $payment_id, $price_id, $log_date);
                    $y++;
                }
                edd_increase_purchase_count($download['id'], $download['quantity']);
                edd_increase_earnings($download['id'], $download['amount']);
            }
            $i++;
        }
        $meta['downloads'] = $downloads;
        $meta['cart_details'] = $cart_details;
        $deleted_downloads = json_decode(stripcslashes($data['edd-payment-removed']), true);
        foreach ($deleted_downloads as $deleted_download) {
            $deleted_download = $deleted_download[0];
            if (empty($deleted_download['id'])) {
                continue;
            }
            $price_id = empty($deleted_download['price_id']) ? 0 : (int) $deleted_download['price_id'];
            $log_args = array('post_type' => 'edd_log', 'post_parent' => $deleted_download['id'], 'numberposts' => $deleted_download['quantity'], 'meta_query' => array(array('key' => '_edd_log_payment_id', 'value' => $payment_id, 'compare' => '='), array('key' => '_edd_log_price_id', 'value' => $price_id, 'compare' => '=')));
            $found_logs = get_posts($log_args);
            foreach ($found_logs as $log) {
                wp_delete_post($log->ID, true);
            }
            edd_decrease_purchase_count($deleted_download['id'], $deleted_download['quantity']);
            edd_decrease_earnings($deleted_download['id'], $deleted_download['amount']);
            do_action('edd_remove_download_from_payment', $payment_id, $deleted_download['id']);
        }
    }
    do_action('edd_update_edited_purchase', $payment_id);
    // Update main payment record
    $updated = wp_update_post(array('ID' => $payment_id, 'post_date' => $date));
    if (0 === $updated) {
        wp_die(__('Error Updating Payment', 'easy-digital-downloads'), __('Error', 'easy-digital-downloads'), array('response' => 400));
    }
    $customer_changed = false;
    if (isset($data['edd-new-customer']) && $data['edd-new-customer'] == '1') {
        $email = isset($data['edd-new-customer-email']) ? sanitize_text_field($data['edd-new-customer-email']) : '';
        $names = isset($data['edd-new-customer-name']) ? sanitize_text_field($data['edd-new-customer-name']) : '';
        if (empty($email) || empty($names)) {
            wp_die(__('New Customers require a name and email address', 'easy-digital-downloads'));
        }
        $customer = new EDD_Customer($email);
        if (empty($customer->id)) {
            $customer_data = array('name' => $names, 'email' => $email);
            $user_id = email_exists($email);
            if (false !== $user_id) {
                $customer_data['user_id'] = $user_id;
            }
            if (!$customer->create($customer_data)) {
                // Failed to crete the new customer, assume the previous customer
                $customer_changed = false;
                $customer = new EDD_Customer($curr_customer_id);
                edd_set_error('edd-payment-new-customer-fail', __('Error creating new customer', 'easy-digital-downloads'));
            }
        }
        $new_customer_id = $customer->id;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } elseif ($curr_customer_id !== $new_customer_id) {
        $customer = new EDD_Customer($new_customer_id);
        $email = $customer->email;
        $names = $customer->name;
        $previous_customer = new EDD_Customer($curr_customer_id);
        $customer_changed = true;
    } else {
        $customer = new EDD_Customer($curr_customer_id);
        $email = $customer->email;
        $names = $customer->name;
    }
    // Setup first and last name from input values
    $names = explode(' ', $names);
    $first_name = !empty($names[0]) ? $names[0] : '';
    $last_name = '';
    if (!empty($names[1])) {
        unset($names[0]);
        $last_name = implode(' ', $names);
    }
    if ($customer_changed) {
        // Remove the stats and payment from the previous customer and attach it to the new customer
        $previous_customer->remove_payment($payment_id, false);
        $customer->attach_payment($payment_id, false);
        // If purchase was completed and not ever refunded, adjust stats of customers
        if ('revoked' == $status || 'publish' == $status) {
            $previous_customer->decrease_purchase_count();
            $previous_customer->decrease_value($new_total);
            $customer->increase_purchase_count();
            $customer->increase_value($new_total);
        }
        update_post_meta($payment_id, '_edd_payment_customer_id', $customer->id);
    }
    // Set new meta values
    $user_info['id'] = $customer->user_id;
    $user_info['email'] = $customer->email;
    $user_info['first_name'] = $first_name;
    $user_info['last_name'] = $last_name;
    $user_info['address'] = $address;
    $meta['user_info'] = $user_info;
    $meta['tax'] = $tax;
    // Check for payment notes
    if (!empty($data['edd-payment-note'])) {
        $note = wp_kses($data['edd-payment-note'], array());
        edd_insert_payment_note($payment_id, $note);
    }
    // Set new status
    edd_update_payment_status($payment_id, $status);
    edd_update_payment_meta($payment_id, '_edd_payment_user_id', $customer->user_id);
    edd_update_payment_meta($payment_id, '_edd_payment_user_email', $customer->email);
    edd_update_payment_meta($payment_id, '_edd_payment_meta', $meta);
    edd_update_payment_meta($payment_id, '_edd_payment_total', $new_total);
    // Adjust total store earnings if the payment total has been changed
    if ($new_total !== $curr_total && ('publish' == $status || 'revoked' == $status)) {
        if ($new_total > $curr_total) {
            // Increase if our new total is higher
            $difference = $new_total - $curr_total;
            edd_increase_total_earnings($difference);
        } elseif ($curr_total > $new_total) {
            // Decrease if our new total is lower
            $difference = $curr_total - $new_total;
            edd_decrease_total_earnings($difference);
        }
    }
    edd_update_payment_meta($payment_id, '_edd_payment_downloads', $new_total);
    edd_update_payment_meta($payment_id, '_edd_payment_unlimited_downloads', $unlimited);
    do_action('edd_updated_edited_purchase', $payment_id);
    wp_safe_redirect(admin_url('edit.php?post_type=download&page=edd-payment-history&view=view-order-details&edd-message=payment-updated&id=' . $payment_id));
    exit;
}