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;
}
Example #2
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 edd_process_paymentwall_purchase($purchase_data)
{
    global $edd_options;
    // 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' => 'paymentwall', 'status' => 'pending');
    // Record the pending payment
    $payment = edd_insert_payment($payment_data);
    // Check payment
    if (!$payment) {
        // Record the error
        edd_record_gateway_error(__('Payment Error', 'edd'), sprintf(__('Payment creation failed before sending buyer to Paymentwall. Payment data: %s', 'edd'), json_encode($payment_data)), $payment);
        // Problems? send back
        edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
    } else {
        edd_initialize_paymentwall_lib();
        $widget = new Paymentwall_Widget($purchase_data['user_email'], $edd_options['paymentwall_widget_code'], array(new Paymentwall_Product($payment, $purchase_data['price'], edd_get_currency(), stripslashes(html_entity_decode(wp_strip_all_tags(edd_get_purchase_summary($purchase_data, false)), ENT_COMPAT, 'UTF-8')))), array('success_url' => add_query_arg('payment-confirmation', 'paymentwall', get_permalink($edd_options['success_page'])), 'email' => $purchase_data['user_email'], 'sign_version' => Paymentwall_Signature_Abstract::VERSION_THREE, 'integration_module' => 'easy_digital_downloads'));
        // Get rid of cart contents
        edd_empty_cart();
        if (!empty($edd_options['paymentwall_widget_mode']) && $edd_options['paymentwall_widget_mode'] == 'iframe') {
            echo $htmlCode = $widget->getHtmlCode(array('width' => '100%', 'allowtransparency' => 'true'));
        } else {
            wp_redirect($widget->getUrl());
        }
        exit;
    }
}
 /**
  * Processes the recurring payments as they come in
  *
  * @since  1.0
  * @return void
  */
 public static function process_paypal_subscr_payment($ipn_data)
 {
     global $edd_options;
     $parent_payment_id = absint($ipn_data['custom']);
     if (false !== get_transient('_edd_recurring_payment_' . $parent_payment_id)) {
         die('2');
         // This is the initial payment
     }
     // If this is a test IPN, don't record it (or maybe do as a test transaction?).
     if (isset($ipn_data['test_ipn']) && (bool) $ipn_data['test_ipn']) {
         do_action('edd_recurring_paypal_test_ipn', $parent_payment_id, $ipn_data);
         die('3');
         // This is a test IPN - don't record it.
     }
     $payment_amount = $ipn_data['mc_gross'];
     $currency_code = strtolower($ipn_data['mc_currency']);
     $user_id = edd_get_payment_user_id($parent_payment_id);
     // verify details
     if ($currency_code != strtolower($edd_options['currency'])) {
         // the currency code is invalid
         edd_record_gateway_error(__('IPN Error', 'edd-recurring'), sprintf(__('Invalid currency in IPN response. IPN data: ', 'edd-recurring'), json_encode($ipn_data)));
         return;
     }
     $key = md5(serialize($ipn_data));
     // Store the payment
     EDD_Recurring()->record_subscription_payment($parent_payment_id, $payment_amount, $ipn_data['txn_id'], $key);
     // 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);
 }
/**
 * Process web accept (one time) payment IPNs
 *
 * @since 1.3.4
 * @param array   $data IPN Data
 * @return void
 */
function edd_process_paypal_web_accept_and_cart($data, $payment_id)
{
    if ($data['txn_type'] != 'web_accept' && $data['txn_type'] != 'cart' && $data['payment_status'] != 'Refunded') {
        return;
    }
    if (empty($payment_id)) {
        return;
    }
    // Collect payment details
    $purchase_key = isset($data['invoice']) ? $data['invoice'] : $data['item_number'];
    $paypal_amount = $data['mc_gross'];
    $payment_status = strtolower($data['payment_status']);
    $currency_code = strtolower($data['mc_currency']);
    $business_email = isset($data['business']) && is_email($data['business']) ? trim($data['business']) : trim($data['receiver_email']);
    $payment_meta = edd_get_payment_meta($payment_id);
    if (edd_get_payment_gateway($payment_id) != 'paypal') {
        return;
        // this isn't a PayPal standard IPN
    }
    // Verify payment recipient
    if (strcasecmp($business_email, trim(edd_get_option('paypal_email', false))) != 0) {
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid business email in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        edd_insert_payment_note($payment_id, __('Payment failed due to invalid PayPal business email.', 'edd'));
        return;
    }
    // Verify payment currency
    if ($currency_code != strtolower($payment_meta['currency'])) {
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid currency in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        edd_insert_payment_note($payment_id, __('Payment failed due to invalid currency in PayPal IPN.', 'edd'));
        return;
    }
    if (!edd_get_payment_user_email($payment_id)) {
        // This runs when a Buy Now purchase was made. It bypasses checkout so no personal info is collected until PayPal
        // No email associated with purchase, so store from PayPal
        edd_update_payment_meta($payment_id, '_edd_payment_user_email', $data['payer_email']);
        // Setup and store the customers's details
        $address = array();
        $address['line1'] = !empty($data['address_street']) ? sanitize_text_field($data['address_street']) : false;
        $address['city'] = !empty($data['address_city']) ? sanitize_text_field($data['address_city']) : false;
        $address['state'] = !empty($data['address_state']) ? sanitize_text_field($data['address_state']) : false;
        $address['country'] = !empty($data['address_country_code']) ? sanitize_text_field($data['address_country_code']) : false;
        $address['zip'] = !empty($data['address_zip']) ? sanitize_text_field($data['address_zip']) : false;
        $user_info = array('id' => '-1', 'email' => sanitize_text_field($data['payer_email']), 'first_name' => sanitize_text_field($data['first_name']), 'last_name' => sanitize_text_field($data['last_name']), 'discount' => '', 'address' => $address);
        $payment_meta['user_info'] = $user_info;
        edd_update_payment_meta($payment_id, '_edd_payment_meta', $payment_meta);
    }
    if ($payment_status == 'refunded' || $payment_status == 'reversed') {
        // Process a refund
        edd_process_paypal_refund($data, $payment_id);
    } else {
        if (get_post_status($payment_id) == 'publish') {
            return;
            // Only complete payments once
        }
        // Retrieve the total purchase amount (before PayPal)
        $payment_amount = edd_get_payment_amount($payment_id);
        if (number_format((double) $paypal_amount, 2) < number_format((double) $payment_amount, 2)) {
            // The prices don't match
            edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid payment amount in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            edd_insert_payment_note($payment_id, __('Payment failed due to invalid amount in PayPal IPN.', 'edd'));
            return;
        }
        if ($purchase_key != edd_get_payment_key($payment_id)) {
            // Purchase keys don't match
            edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid purchase key in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            edd_insert_payment_note($payment_id, __('Payment failed due to invalid purchase key in PayPal IPN.', 'edd'));
            return;
        }
        if ('completed' == $payment_status || edd_is_test_mode()) {
            edd_insert_payment_note($payment_id, sprintf(__('PayPal Transaction ID: %s', 'edd'), $data['txn_id']));
            edd_set_payment_transaction_id($payment_id, $data['txn_id']);
            edd_update_payment_status($payment_id, 'publish');
        } else {
            if ('pending' == $payment_status && isset($data['pending_reason'])) {
                // Look for possible pending reasons, such as an echeck
                $note = '';
                switch (strtolower($data['pending_reason'])) {
                    case 'echeck':
                        $note = __('Payment made via eCheck and will clear automatically in 5-8 days', 'edd');
                        break;
                    case 'address':
                        $note = __('Payment requires a confirmed customer address and must be accepted manually through PayPal', 'edd');
                        break;
                    case 'intl':
                        $note = __('Payment must be accepted manually through PayPal due to international account regulations', 'edd');
                        break;
                    case 'multi-currency':
                        $note = __('Payment received in non-shop currency and must be accepted manually through PayPal', 'edd');
                        break;
                    case 'paymentreview':
                    case 'regulatory_review':
                        $note = __('Payment is being reviewed by PayPal staff as high-risk or in possible violation of government regulations', 'edd');
                        break;
                    case 'unilateral':
                        $note = __('Payment was sent to non-confirmed or non-registered email address.', 'edd');
                        break;
                    case 'upgrade':
                        $note = __('PayPal account must be upgraded before this payment can be accepted', 'edd');
                        break;
                    case 'verify':
                        $note = __('PayPal account is not verified. Verify account in order to accept this payment', 'edd');
                        break;
                    case 'other':
                        $note = __('Payment is pending for unknown reasons. Contact PayPal support for assistance', 'edd');
                        break;
                }
                if (!empty($note)) {
                    edd_insert_payment_note($payment_id, $note);
                }
            }
        }
    }
}
 /**
  * Process Shmart Purchase
  * @global $edd_options Array of all the EDD Options
  * @param array   $purchase_data Purchase Data
  * @return void
  */
 function process_shmart_purchase($purchase_data)
 {
     global $edd_options;
     if (!wp_verify_nonce($purchase_data['gateway_nonce'], 'edd-gateway')) {
         wp_die(__('Nonce verification has failed', 'edd-shmart'), __('Error', 'edd-shmart'), array('response' => 403));
     }
     // 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' => 'shmart', 'status' => 'pending');
     // Add contact number if user is logged in.
     if (is_user_logged_in()) {
         $user_ID = get_current_user_id();
         // Add contact number in user meta.
         update_user_meta($user_ID, '_edd_user_contact_info', $purchase_data['post_data']['contact_number']);
     }
     // Record the pending payment
     $payment = edd_insert_payment($payment_data);
     // Check payment
     if (!$payment) {
         // Record the error
         edd_record_gateway_error(__('Payment Error', 'edd-shmart'), sprintf(__('Payment creation failed before sending buyer to Shmart. Payment data: %s', 'edd-shmart'), json_encode($payment_data)), $payment);
         // Problems? send back
         edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
     } else {
         // Only send to Shmart if the pending payment is created successfully
         //$listener_url = add_query_arg( 'edd-listener', 'SHMART_RESPONSE', home_url( 'index.php' ) );
         // Get the success url
         $listener_url = add_query_arg(array('edd-listener' => 'SHMART_RESPONSE', 'payment-id' => $payment), home_url('index.php'));
         // Get the Shmart redirect uri
         $shmart_redirect = trailingslashit($this->get_shmart_redirect());
         // Merchant ID.
         $merchant_id = $edd_options['shmart_merchant_id'];
         // Generate merchant ref ID.
         $merchant_refID = $this->generate_merchant_ref_ID();
         // Checksum Method.
         $checksum_method = 'MD5';
         /* Do currency conversion. */
         $amount = $this->do_currency_conversion($purchase_data['price']);
         // Round up final amount and convert amount into paisa.
         $amount = ceil($amount) * 100;
         //Get server IP address.
         $ip_address = gethostbyname($_SERVER['SERVER_NAME']);
         // String to generate checksum.
         $checksum_string = $edd_options['shmart_secret_key'] . $merchant_id . '|' . $edd_options['shmart_apikey'] . '|' . $ip_address . '|' . $merchant_refID . '|' . 'INR' . '|' . $amount . '|' . $checksum_method . '|' . 1;
         // Generate checksum.
         $checksum = md5($checksum_string);
         // Setup Shamrt arguments
         $shamrt_args = array('apikey' => $edd_options['shmart_apikey'], 'currency_code' => 'INR', 'amount' => $amount, 'merchant_refID' => $merchant_refID, 'merchant_id' => $merchant_id, 'checksum_method' => $checksum_method, 'checksum' => $checksum, 'ip_address' => $ip_address, 'email' => $purchase_data['user_email'], 'mobileNo' => $purchase_data['post_data']['contact_number'], 'f_name' => $purchase_data['user_info']['first_name'], 'addr' => $purchase_data['user_info']['address']['line1'] . ', ' . $purchase_data['user_info']['address']['line2'], 'city' => $purchase_data['user_info']['address']['city'], 'state' => $purchase_data['user_info']['address']['state'], 'zipcode' => $purchase_data['user_info']['address']['zip'], 'country' => $purchase_data['user_info']['address']['country'], 'show_shipping_addr' => 0, 'rurl' => get_permalink($edd_options['success_page']), 'furl' => edd_get_failed_transaction_uri('?payment-id=' . $payment), 'surl' => $listener_url, 'authorize_user' => 1);
         $shamrt_args = apply_filters('edd_shmart_redirect_args', $shamrt_args, $purchase_data);
         echo '<form action="' . $shmart_redirect . '" method="POST" name="shmartForm">';
         foreach ($shamrt_args as $arg => $arg_value) {
             echo '<input type="hidden" name="' . $arg . '" value="' . $arg_value . '">';
         }
         echo '</form>
               <script language="JavaScript">
                    document.shmartForm.submit();
               </script>';
         die;
     }
 }
 /**
  * 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']);
     }
 }
Example #8
0
/**
 * Process stripe checkout submission
 *
 * @access      public
 * @since       1.0
 * @return      void
 */
function edds_process_stripe_payment($purchase_data)
{
    global $edd_options;
    if (!class_exists('Stripe')) {
        require_once EDDS_PLUGIN_DIR . '/Stripe/Stripe.php';
    }
    if (edd_is_test_mode()) {
        $secret_key = trim($edd_options['test_secret_key']);
    } else {
        $secret_key = trim($edd_options['live_secret_key']);
    }
    $purchase_summary = edd_get_purchase_summary($purchase_data, false);
    // make sure we don't have any left over errors present
    edd_clear_errors();
    if (!isset($_POST['edd_stripe_token'])) {
        // check for fallback mode
        if (isset($edd_options['stripe_js_fallback'])) {
            if (!isset($_POST['card_name']) || strlen(trim($_POST['card_name'])) == 0) {
                edd_set_error('no_card_name', __('Please enter a name for the credit card.', 'edds'));
            }
            if (!isset($_POST['card_number']) || strlen(trim($_POST['card_number'])) == 0) {
                edd_set_error('no_card_number', __('Please enter a credit card number.', 'edds'));
            }
            if (!isset($_POST['card_cvc']) || strlen(trim($_POST['card_cvc'])) == 0) {
                edd_set_error('no_card_cvc', __('Please enter a CVC/CVV for the credit card.', 'edds'));
            }
            if (!isset($_POST['card_exp_month']) || strlen(trim($_POST['card_exp_month'])) == 0) {
                edd_set_error('no_card_exp_month', __('Please enter a expiration month.', 'edds'));
            }
            if (!isset($_POST['card_exp_year']) || strlen(trim($_POST['card_exp_year'])) == 0) {
                edd_set_error('no_card_exp_year', __('Please enter a expiration year.', 'edds'));
            }
            $card_data = array('number' => $purchase_data['card_info']['card_number'], 'name' => $purchase_data['card_info']['card_name'], 'exp_month' => $purchase_data['card_info']['card_exp_month'], 'exp_year' => $purchase_data['card_info']['card_exp_year'], 'cvc' => $purchase_data['card_info']['card_cvc'], 'address_line1' => $purchase_data['card_info']['card_address'], 'address_line2' => $purchase_data['card_info']['card_address_2'], 'address_city' => $purchase_data['card_info']['card_city'], 'address_zip' => $purchase_data['card_info']['card_zip'], 'address_state' => $purchase_data['card_info']['card_state'], 'address_country' => $purchase_data['card_info']['card_country']);
        } else {
            // no Stripe token
            edd_set_error('no_token', __('Missing Stripe token. Please contact support.', 'edds'));
            edd_record_gateway_error(__('Missing Stripe Token', 'edds'), __('A Stripe token failed to be generated. Please check Stripe logs for more information', ' edds'));
        }
    } else {
        $card_data = $_POST['edd_stripe_token'];
    }
    $errors = edd_get_errors();
    if (!$errors) {
        try {
            Stripe::setApiKey($secret_key);
            // setup the payment 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'], 'cart_details' => $purchase_data['cart_details'], 'user_info' => $purchase_data['user_info'], 'status' => 'pending', 'gateway' => 'stripe');
            $customer_exists = false;
            if (is_user_logged_in()) {
                $user = get_user_by('email', $purchase_data['user_email']);
                if ($user) {
                    $customer_id = get_user_meta($user->ID, edd_stripe_get_customer_key(), true);
                    if ($customer_id) {
                        $customer_exists = true;
                        try {
                            // Update the customer to ensure their card data is up to date
                            $cu = Stripe_Customer::retrieve($customer_id);
                            if (isset($cu->deleted) && $cu->deleted) {
                                // This customer was deleted
                                $customer_exists = false;
                            } else {
                                $cu->card = $card_data;
                                $cu->save();
                            }
                            // No customer found
                        } catch (Exception $e) {
                            $customer_exists = false;
                        }
                    }
                }
            }
            if (!$customer_exists) {
                // Create a customer first so we can retrieve them later for future payments
                $customer = Stripe_Customer::create(array('description' => $purchase_data['user_email'], 'email' => $purchase_data['user_email'], 'card' => $card_data));
                $customer_id = is_array($customer) ? $customer['id'] : $customer->id;
                if (is_user_logged_in()) {
                    update_user_meta($user->ID, edd_stripe_get_customer_key(), $customer_id);
                }
            }
            if (edds_is_recurring_purchase($purchase_data) && (!empty($customer) || $customer_exists)) {
                // Process a recurring subscription purchase
                $cu = Stripe_Customer::retrieve($customer_id);
                /**********************************************************
                 * Taxes, fees, and discounts have to be handled differently
                 * with recurring subscriptions, so each is added as an
                 * invoice item and then charged as one time items
                 **********************************************************/
                $invoice_items = array();
                $needs_invoiced = false;
                if ($purchase_data['tax'] > 0 && !edd_prices_include_tax()) {
                    if (edds_is_zero_decimal_currency()) {
                        $tax = $purchase_data['tax'];
                    } else {
                        $tax = $purchase_data['tax'] * 100;
                    }
                    $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $tax, 'currency' => edd_get_currency(), 'description' => sprintf(__('Sales tax for order %s', 'edds'), $purchase_data['purchase_key'])));
                    if (!empty($invoice->id)) {
                        $invoice_items[] = $invoice->id;
                    }
                    $needs_invoiced = true;
                }
                if (!empty($purchase_data['fees'])) {
                    foreach ($purchase_data['fees'] as $fee) {
                        if (edds_is_zero_decimal_currency()) {
                            $fee_amount = $fee['amount'];
                        } else {
                            $fee_amount = $fee['amount'] * 100;
                        }
                        $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $fee_amount, 'currency' => edd_get_currency(), 'description' => $fee['label']));
                        if (!empty($invoice->id)) {
                            $invoice_items[] = $invoice->id;
                        }
                    }
                    $needs_invoiced = true;
                }
                if ($purchase_data['discount'] > 0) {
                    if (edds_is_zero_decimal_currency()) {
                        $discount_amount = $purchase_data['discount'];
                    } else {
                        $discount_amount = $purchase_data['discount'] * 100;
                    }
                    $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $discount_amount * -1, 'currency' => edd_get_currency(), 'description' => $purchase_data['user_info']['discount']));
                    if (!empty($invoice->id)) {
                        $invoice_items[] = $invoice->id;
                    }
                    $needs_invoiced = true;
                }
                try {
                    $plan_id = edds_get_plan_id($purchase_data);
                    // record the pending payment
                    $payment = edd_insert_payment($payment_data);
                    set_transient('_edd_recurring_payment_' . $payment, '1', DAY_IN_SECONDS);
                    // Store the parent payment ID in the user meta
                    EDD_Recurring_Customer::set_customer_payment_id($user->ID, $payment);
                    // Update the customer's subscription in Stripe
                    $customer_response = $cu->updateSubscription(array('plan' => $plan_id));
                    // Set user as subscriber
                    EDD_Recurring_Customer::set_as_subscriber($user->ID);
                    // store the customer recurring ID
                    EDD_Recurring_Customer::set_customer_id($user->ID, $customer_id);
                    // Set the customer status
                    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, $payment);
                    // Set the customer's new expiration date
                    EDD_Recurring_Customer::set_customer_expiration($user->ID, $new_expiration);
                } catch (Stripe_CardError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    if (isset($err['message'])) {
                        edd_set_error('payment_error', $err['message']);
                    } else {
                        edd_set_error('payment_error', __('There was an error processing your payment, please ensure you have entered your card number correctly.', 'edds'));
                    }
                    edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error while processing a Stripe payment. Payment data: %s', ' edds'), json_encode($err)), 0);
                } catch (Stripe_ApiConnectionError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    edd_set_error('payment_error', __('There was an error processing your payment (Stripe\'s API is down), please try again', 'edds'));
                    edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error processing your payment (Stripe\'s API was down). Error: %s', 'edds'), json_encode($err['message'])), 0);
                } catch (Stripe_InvalidRequestError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    // Bad Request of some sort. Maybe Christoff was here ;)
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('request_error', sprintf(__('The Stripe API request was invalid, please try again. Error: %s', 'edds'), json_encode($err['message'])));
                    }
                } catch (Stripe_ApiError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds'));
                    }
                    edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error with Stripe\'s API: ', 'edds'), json_encode($err['message'])), 0);
                } catch (Stripe_AuthenticationError $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    // Authentication error. Stripe keys in settings are bad.
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('api_error', __('The API keys entered in settings are incorrect', 'edds'));
                    }
                } catch (Stripe_Error $e) {
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    // generic stripe error
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('api_error', __('Something went wrong.', 'edds'));
                    }
                } catch (Exception $e) {
                    // some sort of other error
                    $body = $e->getJsonBody();
                    $err = $body['error'];
                    if (isset($err['message'])) {
                        edd_set_error('request_error', $err['message']);
                    } else {
                        edd_set_error('api_error', __('Something went wrong.', 'edds'));
                    }
                }
                if (!empty($err)) {
                    // Delete any invoice items we created for fees, taxes, and other
                    foreach ($invoice_items as $invoice) {
                        $ii = Stripe_InvoiceItem::retrieve($invoice);
                        $ii->delete();
                    }
                    edd_send_back_to_checkout('?payment-mode=stripe');
                }
            } elseif (!empty($customer) || $customer_exists) {
                // Process a normal one-time charge purchase
                if (!isset($edd_options['stripe_preapprove_only'])) {
                    if (edds_is_zero_decimal_currency()) {
                        $amount = $purchase_data['price'];
                    } else {
                        $amount = $purchase_data['price'] * 100;
                    }
                    $charge = Stripe_Charge::create(array("amount" => $amount, "currency" => edd_get_currency(), "customer" => $customer_id, "description" => html_entity_decode($purchase_summary, ENT_COMPAT, 'UTF-8'), 'statement_description' => substr($purchase_summary, 0, 15), 'metadata' => array('email' => $purchase_data['user_info']['email'])));
                }
                // record the pending payment
                $payment = edd_insert_payment($payment_data);
            } else {
                edd_record_gateway_error(__('Customer Creation Failed', 'edds'), sprintf(__('Customer creation failed while processing a payment. Payment Data: %s', ' edds'), json_encode($payment_data)), $payment);
            }
            if ($payment && (!empty($customer_id) || !empty($charge))) {
                if (!empty($needs_invoiced)) {
                    try {
                        // Create the invoice containing taxes / discounts / fees
                        $invoice = Stripe_Invoice::create(array('customer' => $customer_id));
                        $invoice = $invoice->pay();
                    } catch (Exception $e) {
                        // If there is nothing to pay, it just means the invoice item was taken care of with the subscription payment
                    }
                }
                if (isset($edd_options['stripe_preapprove_only'])) {
                    edd_update_payment_status($payment, 'preapproval');
                    add_post_meta($payment, '_edds_stripe_customer_id', $customer_id);
                } else {
                    edd_update_payment_status($payment, 'publish');
                }
                // You should be using Stripe's API here to retrieve the invoice then confirming it's been paid
                if (!empty($charge)) {
                    edd_insert_payment_note($payment, 'Stripe Charge ID: ' . $charge->id);
                    if (function_exists('edd_set_payment_transaction_id')) {
                        edd_set_payment_transaction_id($payment, $charge->id);
                    }
                } elseif (!empty($customer_id)) {
                    edd_insert_payment_note($payment, 'Stripe Customer ID: ' . $customer_id);
                }
                edd_empty_cart();
                edd_send_to_success_page();
            } else {
                edd_set_error('payment_not_recorded', __('Your payment could not be recorded, please contact the site administrator.', 'edds'));
                // if errors are present, send the user back to the purchase page so they can be corrected
                edd_send_back_to_checkout('?payment-mode=stripe');
            }
        } catch (Stripe_CardError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            if (isset($err['message'])) {
                edd_set_error('payment_error', $err['message']);
            } else {
                edd_set_error('payment_error', __('There was an error processing your payment, please ensure you have entered your card number correctly.', 'edds'));
            }
            edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error while processing a Stripe payment. Payment data: %s', ' edds'), json_encode($err)), 0);
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_ApiConnectionError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            edd_set_error('payment_error', __('There was an error processing your payment (Stripe\'s API is down), please try again', 'edds'));
            edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error processing your payment (Stripe\'s API was down). Error: %s', 'edds'), json_encode($err['message'])), 0);
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_InvalidRequestError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            // Bad Request of some sort. Maybe Christoff was here ;)
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_ApiError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds'));
            }
            edd_set_error('request_error', sprintf(__('The Stripe API request was invalid, please try again. Error: %s', 'edds'), json_encode($err['message'])));
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_AuthenticationError $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            // Authentication error. Stripe keys in settings are bad.
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('api_error', __('The API keys entered in settings are incorrect', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Stripe_Error $e) {
            $body = $e->getJsonBody();
            $err = $body['error'];
            // generic stripe error
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('api_error', __('Something went wrong.', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        } catch (Exception $e) {
            // some sort of other error
            $body = $e->getJsonBody();
            $err = $body['error'];
            if (isset($err['message'])) {
                edd_set_error('request_error', $err['message']);
            } else {
                edd_set_error('api_error', __('Something went wrong.', 'edds'));
            }
            edd_send_back_to_checkout('?payment-mode=stripe');
        }
    } else {
        edd_send_back_to_checkout('?payment-mode=stripe');
    }
}
/**
 * Process web accept (one time) payment IPNs
 *
 * @since 1.3.4
 * @global $edd_options Array of all the EDD Options
 * @param array $data IPN Data
 * @return void
 */
function edd_process_paypal_web_accept($data)
{
    global $edd_options;
    if ($data['txn_type'] != 'web_accept') {
        return;
    }
    // Collect payment details
    $payment_id = $data['custom'];
    $purchase_key = $data['item_number'];
    $paypal_amount = $data['mc_gross'];
    $payment_status = strtolower($data['payment_status']);
    $currency_code = strtolower($data['mc_currency']);
    // Retrieve the meta info for this payment
    $payment_amount = edd_format_amount(edd_get_payment_amount($payment_id));
    if (get_post_status($payment_id) == 'complete') {
        return;
    }
    // Only complete payments once
    if (edd_get_payment_gateway($payment_id) != 'paypal') {
        return;
    }
    // this isn't a PayPal standard IPN
    // Verify details
    if ($currency_code != strtolower(edd_get_currency())) {
        // The currency code is invalid
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid currency in IPN response. IPN data: ', 'edd'), json_encode($data)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        return;
    }
    if ($payment_status == 'refunded') {
        // Process a refund
        edd_process_paypal_refund($data);
    } else {
        if (number_format((double) $paypal_amount, 2) != $payment_amount) {
            // The prices don't match
            edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid payment amount in IPN response. IPN data: ', 'edd'), json_encode($data)), $payment_id);
            //return;
        }
        if ($purchase_key != edd_get_payment_key($payment_id)) {
            // Purchase keys don't match
            edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid purchase key in IPN response. IPN data: ', 'edd'), json_encode($data)), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            return;
        }
        if ($payment_status == 'completed' || edd_is_test_mode()) {
            edd_insert_payment_note($payment_id, sprintf(__('PayPal Transaction ID: %s', 'edd'), $data['txn_id']));
            edd_update_payment_status($payment_id, 'publish');
        }
    }
}
/**
 * Process web accept (one time) payment IPNs
 *
 * @since 1.3.4
 * @global $edd_options Array of all the EDD Options
 * @param array   $data IPN Data
 * @return void
 */
function edd_process_paypal_web_accept_and_cart($data)
{
    global $edd_options;
    if ($data['txn_type'] != 'web_accept' && $data['txn_type'] != 'cart' && $data['payment_status'] != 'Refunded') {
        return;
    }
    // Collect payment details
    $payment_id = $data['custom'];
    $purchase_key = isset($data['invoice']) ? $data['invoice'] : $data['item_number'];
    $paypal_amount = $data['mc_gross'];
    $payment_status = strtolower($data['payment_status']);
    $currency_code = strtolower($data['mc_currency']);
    $business_email = isset($data['business']) && is_email($data['business']) ? trim($data['business']) : trim($data['receiver_email']);
    if (edd_get_payment_gateway($payment_id) != 'paypal') {
        return;
        // this isn't a PayPal standard IPN
    }
    // Verify payment recipient
    if (strcasecmp($business_email, trim($edd_options['paypal_email'])) != 0) {
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid business email in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        edd_insert_payment_note($payment_id, __('Payment failed due to invalid PayPal business email.', 'edd'));
        return;
    }
    // Verify payment currency
    if ($currency_code != strtolower(edd_get_currency())) {
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid currency in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        edd_insert_payment_note($payment_id, __('Payment failed due to invalid currency in PayPal IPN.', 'edd'));
        return;
    }
    if (!edd_get_payment_user_email($payment_id)) {
        // This runs when a Buy Now purchase was made. It bypasses checkout so no personal info is collected until PayPal
        // No email associated with purchase, so store from PayPal
        edd_update_payment_meta($payment_id, '_edd_payment_user_email', $data['payer_email']);
        // Setup and store the customers's details
        $address = array();
        $address['line1'] = !empty($data['address_street']) ? $data['address_street'] : false;
        $address['city'] = !empty($data['address_city']) ? $data['address_city'] : false;
        $address['state'] = !empty($data['address_state']) ? $data['address_state'] : false;
        $address['country'] = !empty($data['address_country_code']) ? $data['address_country_code'] : false;
        $address['zip'] = !empty($data['address_zip']) ? $data['address_zip'] : false;
        $user_info = array('id' => '-1', 'email' => $data['payer_email'], 'first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'discount' => '', 'address' => $address);
        $payment_meta = get_post_meta($payment_id, '_edd_payment_meta', true);
        $payment_meta['user_info'] = $user_info;
        edd_update_payment_meta($payment_id, '_edd_payment_meta', $payment_meta);
    }
    if ($payment_status == 'refunded' || $payment_status == 'reversed') {
        // Process a refund
        edd_process_paypal_refund($data);
    } else {
        if (get_post_status($payment_id) == 'publish') {
            return;
            // Only complete payments once
        }
        // Retrieve the total purchase amount (before PayPal)
        $payment_amount = edd_get_payment_amount($payment_id);
        if (number_format((double) $paypal_amount, 2) < number_format((double) $payment_amount, 2)) {
            // The prices don't match
            edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid payment amount in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            edd_insert_payment_note($payment_id, __('Payment failed due to invalid amount in PayPal IPN.', 'edd'));
            return;
        }
        if ($purchase_key != edd_get_payment_key($payment_id)) {
            // Purchase keys don't match
            edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid purchase key in IPN response. IPN data: %s', 'edd'), json_encode($data)), $payment_id);
            edd_update_payment_status($payment_id, 'failed');
            edd_insert_payment_note($payment_id, __('Payment failed due to invalid purchase key in PayPal IPN.', 'edd'));
            return;
        }
        if ($payment_status == 'completed' || edd_is_test_mode()) {
            edd_insert_payment_note($payment_id, sprintf(__('PayPal Transaction ID: %s', 'edd'), $data['txn_id']));
            edd_set_payment_transaction_id($payment_id, $data['txn_id']);
            edd_update_payment_status($payment_id, 'publish');
        }
    }
}
 /**
  * Execute an API call
  *
  * @access      public
  * @since       1.0.0
  * @param       int $customer_id The customer ID
  * @param       array $body The body of the API call
  * @param       string $method The type of call to make
  * @param       string $endpoint The endpoint to call
  * @return      mixed int $response If API call succeeded, false otherwise
  */
 public function call($customer_id = 0, $body = array(), $method = 'PUT', $endpoint = false)
 {
     // Bail if no ID or body passed
     if (!$customer_id || empty($body)) {
         return false;
     }
     $args = array('headers' => array('Authorization' => 'Basic ' . base64_encode($this->site_id . ':' . $this->api_key)), 'method' => $method, 'body' => $body);
     $url = $this->api_url . $customer_id;
     if ($endpoint) {
         $url .= '/' . $endpoint;
     }
     try {
         $response = wp_remote_request($url, $args);
     } catch (Exception $e) {
         edd_record_gateway_error(__('EDD Customer.io Connect Error', 'edd-customerio-connect'), print_r($e->getMessage(), true));
         return false;
     }
     $status = wp_remote_retrieve_header($response, 'status');
     if ($status != '200 OK') {
         $body = json_decode(wp_remote_retrieve_body($response));
         edd_record_gateway_error(__('EDD Customer.io Connect Error', 'edd-customerio-connect'), $status . ': ' . $body->meta->error);
         return false;
     }
     return $response;
 }
 public function process_payment($purchase_data)
 {
     if (!wp_verify_nonce($purchase_data['gateway_nonce'], 'edd-gateway')) {
         wp_die(__('Nonce verification has failed', GOURLEDD), __('Error', GOURLEDD), array('response' => 403));
     }
     $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_id = edd_insert_payment($payment_data);
     if ($payment_id) {
         // Save Log
         $userID = edd_get_payment_user_id($payment_id);
         $user = !$userID ? __('Guest', GOURLEDD) : "<a href='" . admin_url("user-edit.php?user_id=" . $userID) . "'>user" . $userID . "</a>";
         edd_insert_payment_note($payment_id, sprintf(__('Order Created by %s. <br/>Awaiting cryptocurrency payment ...', GOURLEDD), $user) . ' <br/>');
         // Forward to payment page
         edd_empty_cart();
         edd_send_to_success_page();
     } else {
         edd_record_gateway_error(__('Payment Error', GOURLEDD), sprintf(__('Payment creation failed while processing Bitcoin/Altcoin purchase. Payment data: %s', GOURLEDD), 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']);
     }
     return true;
 }
 /**
  * The $purchase_data array consists of the following data:
  *
  * $purchase_data = array(
  *   'downloads'    => array of download IDs,
  *   'tax'          => taxed amount on shopping cart
  *   'subtotal'     => total price before tax
  *   'price'        => total price of cart contents after taxes,
  *   '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,
  * );
  */
 public function process_purchase($purchase_data)
 {
     $config_id = edd_get_option($this->id . '_config_id');
     // 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' => $this->id, 'status' => 'pending');
     // Record the pending payment
     $payment_id = edd_insert_payment($payment_data);
     // Check payment
     if (!$payment_id) {
         // Log error
         edd_record_gateway_error(__('Payment Error', 'pronamic_ideal'), sprintf(__('Payment creation failed before sending buyer to the payment provider. Payment data: %s', 'pronamic_ideal'), json_encode($payment_data)), $payment_id);
         edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
     } else {
         $data = new Pronamic_WP_Pay_Extensions_EDD_PaymentData($payment_id, $payment_data);
         $gateway = Pronamic_WP_Pay_Plugin::get_gateway($config_id);
         if ($gateway) {
             // Start
             $payment = Pronamic_WP_Pay_Plugin::start($config_id, $gateway, $data, $this->payment_method);
             $error = $gateway->get_error();
             if (is_wp_error($error)) {
                 edd_record_gateway_error(__('Payment Error', 'pronamic_ideal'), sprintf(__('Payment creation failed before sending buyer to the payment provider. Payment data: %s', 'pronamic_ideal'), json_encode($payment_data)), $payment_id);
                 edd_set_error('pronamic_pay_error', Pronamic_WP_Pay_Plugin::get_default_error_message());
                 foreach ($error->get_error_messages() as $i => $message) {
                     edd_set_error('pronamic_pay_error_' . $i, $message);
                 }
                 edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
             } else {
                 // Transaction ID
                 // @see https://github.com/easydigitaldownloads/Easy-Digital-Downloads/blob/2.3/includes/payments/functions.php#L1400-L1416
                 edd_set_payment_transaction_id($payment_id, $payment->get_transaction_id());
                 // Payment note
                 $payment_link = add_query_arg(array('post' => $payment->get_id(), 'action' => 'edit'), admin_url('post.php'));
                 $note = sprintf(__('Payment %s pending.', 'pronamic_ideal'), sprintf('<a href="%s">#%s</a>', $payment_link, $payment->get_id()));
                 edd_insert_payment_note($payment_id, $note);
                 $gateway->redirect($payment);
                 exit;
             }
         } else {
             edd_set_error('pronamic_pay_error', Pronamic_WP_Pay_Plugin::get_default_error_message());
             edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
         }
     }
 }
Example #14
0
 /**
  * Process voguepay Purchase
  * @global $edd_options Array of all the EDD Options
  * @param array   $purchase_data Purchase Data
  * @return void
  */
 function process_voguepay_purchase($purchase_data)
 {
     global $edd_options;
     if (!wp_verify_nonce($purchase_data['gateway_nonce'], 'edd-gateway')) {
         wp_die(__('Nonce verification has failed', 'edd-voguepay'), __('Error', 'edd-voguepay'), array('response' => 403));
     }
     // 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' => 'voguepay', 'status' => 'pending');
     // Add contact number if user is logged in.
     // if( is_user_logged_in() ) {
     // $user_ID = get_current_user_id();
     // Add contact number in user meta.
     // update_user_meta( $user_ID, '_edd_user_contact_info', $purchase_data[ 'post_data' ][ 'contact_number' ] );
     // }
     // Record the pending payment
     $payment = edd_insert_payment($payment_data);
     // Check payment
     if (!$payment) {
         // Record the error
         edd_record_gateway_error(__('Payment Error', 'edd-voguepay'), sprintf(__('Payment creation failed before sending buyer to Voguepay. Payment data: %s', 'edd-voguepay'), json_encode($payment_data)), $payment);
         // Problems? send back
         edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
     } else {
         // Only send to voguepay if the pending payment is created successfully
         //$listener_url = add_query_arg( 'edd-listener', 'VOGUEPAY_RESPONSE', home_url( 'index.php' ) );
         // Get the success url
         $listener_url = add_query_arg(array('edd-listener' => 'VOGUEPAY_RESPONSE', 'payment-id' => $payment), home_url('index.php'));
         // Get the voguepay redirect uri
         $voguepay_redirect = trailingslashit($this->get_voguepay_redirect());
         // Merchant ID.
         $merchant_id = $edd_options['v_merchant_id'];
         // Merchant ID.
         $store_id = $edd_options['store_id'];
         // Generate merchant ref ID.
         $merchant_ref = $this->generate_merchant_refID();
         // Checksum Method.
         $checksum_method = 'MD5';
         /* Do currency conversion. */
         // $amount = $this->do_currency_conversion( $purchase_data[ 'price' ] );
         // Round up final amount and convert amount into paisa.
         $amount = $purchase_data['price'];
         //Get server IP address.
         $ip_address = gethostbyname($_SERVER['SERVER_NAME']);
         // String to generate checksum.
         $checksum_string = $edd_options['voguepay_secret_key'] . $merchant_id . '|' . $edd_options['voguepay_apikey'] . '|' . $ip_address . '|' . $merchant_ref . '|' . 'INR' . '|' . $amount . '|' . $checksum_method . '|' . 1;
         // Generate checksum.
         $checksum = md5($checksum_string);
         // Setup voguepay arguments
         $voguepay_args = array('cur' => 'NGN', 'memo' => 'Secure Payment with VoguePay', 'total' => $amount, 'merchant_ref' => $merchant_ref, 'v_merchant_id' => $merchant_id, 'store_id' => $store_id, 'success_url' => get_permalink($edd_options['success_page']), 'fail_url' => edd_get_failed_transaction_uri('?payment-id=' . $payment), 'notify_url' => $listener_url);
         $voguepay_args = apply_filters('edd_voguepay_redirect_args', $voguepay_args, $purchase_data);
         echo '<div align="center"><br /><br /><br />';
         echo "<h3>...Redirecting. Click the image below if not automatically redirected</h3><br /><br /><br />";
         echo '<form action="' . $voguepay_redirect . '" method="POST" name="voguepayForm">';
         foreach ($voguepay_args as $arg => $arg_value) {
             echo '<input type="hidden" name="' . $arg . '" value="' . $arg_value . '">';
         }
         $seyeurl = plugins_url('assets/pay-via-voguepay.png', __FILE__);
         echo '<input type="image" src="' . $seyeurl . '" />';
         echo '</form></div>
               <script language="JavaScript">
                  //  document.voguepayForm.submit();
               </script>';
         die;
     }
 }
 /**
  * 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']);
     }
 }
 /**
  * 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);
         }
     }
 }
/**
 * Process web accept (one time) payment IPNs
 *
 * @access      private
 * @since       1.3.4
 * @return      void
*/
function edd_process_paypal_web_accept($data)
{
    global $edd_options;
    // collect payment details
    $payment_id = $data['custom'];
    $purchase_key = $data['item_number'];
    $paypal_amount = $data['mc_gross'];
    $payment_status = $data['payment_status'];
    $currency_code = strtolower($data['mc_currency']);
    // retrieve the meta info for this payment
    $payment_meta = get_post_meta($payment_id, '_edd_payment_meta', true);
    $payment_amount = edd_format_amount($payment_meta['amount']);
    // verify details
    if ($currency_code != strtolower($edd_options['currency'])) {
        // the currency code is invalid
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid currency in IPN response. IPN data: ', 'edd'), json_encode($encoded_data_array)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        return;
    }
    if (number_format((double) $paypal_amount, 2) != $payment_amount) {
        // the prices don't match
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid payment amount in IPN response. IPN data: ', 'edd'), json_encode($encoded_data_array)), $payment_id);
        //return;
    }
    if ($purchase_key != $payment_meta['key']) {
        // purchase keys don't match
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid purchase key in IPN response. IPN data: ', 'edd'), json_encode($encoded_data_array)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        return;
    }
    if ($purchase_key != $payment_meta['key']) {
        // purchase keys don't match
        edd_record_gateway_error(__('IPN Error', 'edd'), sprintf(__('Invalid purchase key in IPN response. IPN data: ', 'edd'), json_encode($encoded_data_array)), $payment_id);
        edd_update_payment_status($payment_id, 'failed');
        return;
    }
    $status = strtolower($payment_status);
    if ($status == 'completed' || edd_is_test_mode()) {
        edd_insert_payment_note($payment_id, sprintf(__('PayPal Transaction ID: %s', 'edd'), $data['txn_id']));
        edd_update_payment_status($payment_id, 'publish');
    }
}