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;
}
 /**
  * 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');
         }
     }
 }
Ejemplo n.º 3
0
 /**
  * Mark payments as Failed when returning to the Failed Transaction page
  * @return      void
  */
 public function voguepay_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']);
         if (!empty($_POST)) {
             // create payment note for failed transaction.
             $payment_note = sprintf(__('voguepay Reference ID: %s <br> Merchant Reference ID: %s', 'edd-voguepay'), $_POST['voguepay_refID'], $_POST['merchant_ref']);
             $payment_note .= '<br> Message: ' . $_POST['status_msg'];
             edd_insert_payment_note($payment_id, $payment_note);
             edd_set_payment_transaction_id($payment_id, $post_data['voguepay_refID']);
         }
     }
 }
/**
 * 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 the purchase and create the charge in Amazon
  *
  * @access public
  * @since  2.4
  * @param  $purchase_data array Cart details
  * @return void
  */
 public function process_purchase($purchase_data)
 {
     if (empty($purchase_data['post_data']['edd_amazon_reference_id'])) {
         edd_set_error('missing_reference_id', __('Missing Reference ID, please try again', 'edd'));
     }
     $errors = edd_get_errors();
     if ($errors) {
         edd_send_back_to_checkout('?payment-mode=amazon');
     }
     $args = apply_filters('edd_amazon_charge_args', array('merchant_id' => edd_get_option('amazon_seller_id', ''), 'amazon_reference_id' => $purchase_data['post_data']['edd_amazon_reference_id'], 'authorization_reference_id' => $purchase_data['purchase_key'], 'charge_amount' => $purchase_data['price'], 'currency_code' => edd_get_currency(), 'charge_note' => html_entity_decode(edd_get_purchase_summary($purchase_data, false)), 'charge_order_id' => $purchase_data['purchase_key'], 'store_name' => remove_accents(wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES)), 'transaction_timeout' => 0), $purchase_data);
     $args['platform_id'] = 'A3JST9YM1SX7LB';
     $charge = $this->client->charge($args);
     if (200 == $charge->response['Status']) {
         $charge = new ResponseParser($charge->response);
         $charge = $charge->toArray();
         $status = $charge['AuthorizeResult']['AuthorizationDetails']['AuthorizationStatus']['State'];
         if ('Declined' === $status) {
             $reason = $charge['AuthorizeResult']['AuthorizationDetails']['AuthorizationStatus']['ReasonCode'];
             edd_set_error('payment_declined', sprintf(__('Your payment could not be authorized, please try a different payment method. Reason: %s', 'edd'), $reason));
             edd_send_back_to_checkout('?payment-mode=amazon&amazon_reference_id=' . $purchase_data['post_data']['edd_amazon_reference_id']);
         }
         // Setup payment data to be recorded
         $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->gateway_id, 'status' => 'pending');
         $payment_id = edd_insert_payment($payment_data);
         $authorization_id = $charge['AuthorizeResult']['AuthorizationDetails']['AmazonAuthorizationId'];
         $capture_id = str_replace('-A', '-C', $authorization_id);
         $reference_id = sanitize_text_field($_POST['edd_amazon_reference_id']);
         // Confirm the capture was completed
         $capture = $this->client->getCaptureDetails(array('merchant_id' => edd_get_option('amazon_seller_id', ''), 'amazon_capture_id' => $capture_id));
         $capture = new ResponseParser($capture->response);
         $capture = $capture->toArray();
         // Check capture status
         edd_update_payment_meta($payment_id, '_edd_amazon_authorization_id', $authorization_id);
         edd_update_payment_meta($payment_id, '_edd_amazon_capture_id', $capture_id);
         edd_set_payment_transaction_id($payment_id, $reference_id);
         edd_update_payment_status($payment_id, 'publish');
         // Empty the shopping cart
         edd_empty_cart();
         edd_send_to_success_page();
     } else {
         // Set an error
         edd_set_error('amazon_error', sprintf(__('There was an issue processing your payment. Amazon error: %s', 'edd'), print_r($charge, true)));
         edd_send_back_to_checkout('?payment-mode=amazon&amazon_reference_id=' . $purchase_data['post_data']['edd_amazon_reference_id']);
     }
 }
Ejemplo n.º 6
0
 /**
  * Record a subscription payment
  *
  * @since  1.0.1
  * @return void
  */
 public function record_subscription_payment($parent_id = 0, $amount = '', $txn_id = '', $unique_key = 0)
 {
     global $edd_options;
     if ($this->payment_exists($unique_key)) {
         return;
     }
     // increase the earnings for each product in the subscription
     $downloads = edd_get_payment_meta_downloads($parent_id);
     if ($downloads) {
         foreach ($downloads as $download) {
             edd_increase_earnings($download['id'], $amount);
         }
     }
     // setup the payment daya
     $payment_data = array('parent' => $parent_id, 'price' => $amount, 'user_email' => edd_get_payment_user_email($parent_id), 'purchase_key' => get_post_meta($parent_id, '_edd_payment_purchase_key', true), 'currency' => edd_get_option('currency', 'usd'), 'downloads' => $downloads, 'user_info' => edd_get_payment_meta_user_info($parent_id), 'cart_details' => edd_get_payment_meta_cart_details($parent_id), 'status' => 'edd_subscription', 'gateway' => edd_get_payment_gateway($parent_id));
     // record the subscription payment
     $payment = edd_insert_payment($payment_data);
     if (!empty($unique_key)) {
         update_post_meta($payment, '_edd_recurring_' . $unique_key, '1');
     }
     // Record transaction ID
     if (!empty($txn_id)) {
         if (function_exists('edd_set_payment_transaction_id')) {
             edd_set_payment_transaction_id($payment, $txn_id);
         }
     }
     // Update the expiration date of license keys, if EDD Software Licensing is active
     if (function_exists('edd_software_licensing')) {
         $licenses = edd_software_licensing()->get_licenses_of_purchase($parent_id);
         if (!empty($licenses)) {
             foreach ($licenses as $license) {
                 // Update the expiration dates of the license key
                 edd_software_licensing()->renew_license($license->ID, $parent_id);
             }
         }
     }
     do_action('edd_recurring_record_payment', $payment, $parent_id, $amount, $txn_id, $unique_key);
 }
Ejemplo n.º 7
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_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');
        }
    }
}
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;
 }
 /**
  * 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']);
         }
     }
 }