function receipt_page($order_id)
    {
        $order = new WC_Order($order_id);
        WC()->session->ppp_order_id = $order_id;
        $PaymentData = AngellEYE_Gateway_Paypal::calculate($order, true);
        $payment = new Payment();
        $payment->setId(WC()->session->paymentId);
        $patchReplace = new \PayPal\Api\Patch();
        $patchReplace->setOp('replace')->setPath('/transactions/0/amount')->setValue(json_decode('{
                    "total": "' . number_format($order->get_total(), 2, '.', '') . '",
                    "currency": "' . get_woocommerce_currency() . '",
                    "details": {
                        "subtotal": "' . $PaymentData['itemamt'] . '",
                        "shipping": "' . $PaymentData['shippingamt'] . '",
                        "tax":"' . $PaymentData['taxamt'] . '"
                    }
                }'));
        $patchRequest = new \PayPal\Api\PatchRequest();
        if ($order->needs_shipping_address() && !empty($order->shipping_country)) {
            //add shipping info
            $patchAdd = new \PayPal\Api\Patch();
            $patchAdd->setOp('add')->setPath('/transactions/0/item_list/shipping_address')->setValue(json_decode('{
                    "recipient_name": "' . $order->shipping_first_name . ' ' . $order->shipping_last_name . '",
                    "line1": "' . $order->shipping_address_1 . '",
                    "city": "' . $order->shipping_city . '",
                    "state": "' . $order->shipping_state . '",
                    "postal_code": "' . $order->shipping_postcode . '",
                    "country_code": "' . $order->shipping_country . '"
                }'));
            $patchRequest->setPatches(array($patchAdd, $patchReplace));
        } else {
            $patchRequest->setPatches(array($patchReplace));
        }
        try {
            $result = $payment->update($patchRequest, $this->getAuth());
            $this->add_log(print_r($payment, true));
            if ($result == true) {
            }
            ?>
        <script src="https://www.paypalobjects.com/webstatic/ppplus/ppplus.min.js"type="text/javascript"></script>
        <script>
            jQuery(document).ready(function(){
                jQuery.blockUI({
                    message: "<?php 
            echo esc_js(__('Thank you for your order. We are now redirecting you to PayPal to make payment.', 'paypal-for-woocommerce'));
            ?>
",
                    baseZ: 99999,
                    overlayCSS:
                    {
                        background: "#fff",
                        opacity: 0.6
                    },
                    css: {
                        padding:        "20px",
                        zindex:         "9999999",
                        textAlign:      "center",
                        color:          "#555",
                        border:         "3px solid #aaa",
                        backgroundColor:"#fff",
                        cursor:         "wait",
                        lineHeight:		"24px"
                    }
                });
                PAYPAL.apps.PPP.doCheckout();
            });
        </script>
    <?php 
        } catch (PayPal\Exception\PayPalConnectionException $ex) {
            wc_add_notice(__("Error processing checkout. Please try again. ", 'woocommerce'), 'error');
            $this->add_log($ex->getData());
        } catch (Exception $ex) {
            $this->add_log($ex->getMessage());
            // Prints the Error Code
            wc_add_notice(__("Error processing checkout. Please try again.", 'woocommerce'), 'error');
        }
    }
 /**
  * Process a refund if supported
  * @param  int $order_id
  * @param  float $amount
  * @param  string $reason
  * @return  bool|wp_error True or false based on success, or a WP_Error object
  */
 public function process_refund($order_id, $amount = null, $reason = '')
 {
     $order = wc_get_order($order_id);
     $this->add_log('Begin Refund');
     $this->add_log('Order: ' . print_r($order, true));
     $this->add_log('Transaction ID: ' . print_r($order->get_transaction_id(), true));
     $this->add_log('API Username: '******'API Password: '******'API Signature: ' . print_r($this->api_signature, true));
     if (!$order || !$order->get_transaction_id() || !$this->api_username || !$this->api_password || !$this->api_signature) {
         return false;
     }
     $this->add_log('Include Class Request');
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php';
     }
     /*
      * Create PayPal object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? TRUE : FALSE, 'APIUsername' => $this->api_username, 'APIPassword' => $this->api_password, 'APISignature' => $this->api_signature);
     $PayPal = new Angelleye_PayPal($PayPalConfig);
     if ($reason) {
         if (255 < strlen($reason)) {
             $reason = substr($reason, 0, 252) . '...';
         }
         $reason = html_entity_decode($reason, ENT_NOQUOTES, 'UTF-8');
     }
     // Prepare request arrays
     $RTFields = array('transactionid' => $order->get_transaction_id(), 'payerid' => '', 'invoiceid' => '', 'refundtype' => $order->get_total() == $amount ? 'Full' : 'Partial', 'amt' => number_format($amount, 2, '.', ''), 'currencycode' => $order->get_order_currency(), 'note' => $reason, 'retryuntil' => '', 'refundsource' => '', 'merchantstoredetail' => '', 'refundadvice' => '', 'refunditemdetails' => '', 'msgsubid' => '', 'storeid' => '', 'terminalid' => '');
     $PayPalRequestData = array('RTFields' => $RTFields);
     $this->add_log('Refund Request: ' . print_r($PayPalRequestData, true));
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->RefundTransaction($PayPalRequestData);
     /**
      *  cURL Error Handling #146 
      *  @since    1.1.8
      */
     AngellEYE_Gateway_Paypal::angelleye_paypal_for_woocommerce_curl_error_handler($PayPalResult, $methos_name = 'RefundTransaction', $gateway = 'PayPal Website Payments Pro (DoDirectPayment)', $this->error_email_notify);
     $this->add_log('Refund Information: ' . print_r($PayPalResult, true));
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         $order->add_order_note('Refund Transaction ID:' . $PayPalResult['REFUNDTRANSACTIONID']);
         $max_remaining_refund = wc_format_decimal($order->get_total() - $order->get_total_refunded());
         if (!$max_remaining_refund > 0) {
             $order->update_status('refunded');
         }
         if (ob_get_length()) {
             ob_end_clean();
         }
         return true;
     } else {
         $pc_message = apply_filters('ae_ppddp_refund_error_message', $PayPalResult['L_LONGMESSAGE0'], $PayPalResult['L_ERRORCODE'], $PayPalResult);
         return new WP_Error('ec_refund-error', $pc_message);
     }
 }
 /**
  * do_payment
  *
  * Makes the request to PayPal's DoDirectPayment API
  *
  * @access public
  * @param mixed $order
  * @param mixed $card_number
  * @param mixed $card_type
  * @param mixed $card_exp_month
  * @param mixed $card_exp_year
  * @param mixed $card_csc
  * @param string $centinelPAResStatus (default: '')
  * @param string $centinelEnrolled (default: '')
  * @param string $centinelCavv (default: '')
  * @param string $centinelEciFlag (default: '')
  * @param string $centinelXid (default: '')
  * @return void
  */
 function do_payment($order, $card_number, $card_type, $card_exp_month, $card_exp_year, $card_csc, $centinelPAResStatus = '', $centinelEnrolled = '', $centinelCavv = '', $centinelEciFlag = '', $centinelXid = '')
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         $pc_session_expired_error = apply_filters('angelleye_pc_session_expired_error', sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'));
         wc_add_notice($pc_session_expired_error, "error");
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php';
     }
     /*
      * Create PayPal object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? TRUE : FALSE, 'APIUsername' => $this->api_username, 'APIPassword' => $this->api_password, 'APISignature' => $this->api_signature);
     $PayPal = new Angelleye_PayPal($PayPalConfig);
     if (empty($GLOBALS['wp_rewrite'])) {
         $GLOBALS['wp_rewrite'] = new WP_Rewrite();
     }
     $card_exp = $card_exp_month . $card_exp_year;
     /**
      * Generate PayPal request
      */
     $DPFields = array('paymentaction' => $this->payment_action == 'Authorization' ? 'Authorization' : 'Sale', 'ipaddress' => $this->get_user_ip(), 'returnfmfdetails' => '');
     $CCDetails = array('creditcardtype' => $card_type, 'acct' => $card_number, 'expdate' => $card_exp, 'cvv2' => $card_csc, 'startdate' => '', 'issuenumber' => '');
     $PayerInfo = array('email' => $order->billing_email, 'firstname' => $order->billing_first_name, 'lastname' => $order->billing_last_name);
     $BillingAddress = array('street' => $order->billing_address_1, 'street2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'countrycode' => $order->billing_country, 'zip' => $order->billing_postcode, 'phonenum' => $order->billing_phone);
     $ShippingAddress = array('shiptoname' => $order->shipping_first_name . ' ' . $order->shipping_last_name, 'shiptostreet' => $order->shipping_address_1, 'shiptostreet2' => $order->shipping_address_2, 'shiptocity' => $order->shipping_city, 'shiptostate' => $order->shipping_state, 'shiptozip' => $order->shipping_postcode, 'shiptocountry' => $order->shipping_country, 'shiptophonenum' => $order->shipping_phone);
     $PaymentDetails = array('amt' => number_format($order->get_total(), 2, '.', ''), 'currencycode' => get_woocommerce_currency(), 'insuranceamt' => '', 'shipdiscamt' => '0.00', 'handlingamt' => '0.00', 'desc' => '', 'custom' => $order->customer_note ? substr(preg_replace("/[^A-Za-z0-9 ]/", "", $order->customer_note), 0, 256) : '', 'invnum' => $invoice_number = $this->invoice_id_prefix . preg_replace("/[^0-9,.]/", "", $order->id), 'notifyurl' => '', 'recurring' => '');
     $PaymentData = AngellEYE_Gateway_Paypal::calculate($order, $this->send_items);
     $OrderItems = array();
     if ($this->send_items) {
         foreach ($PaymentData['order_items'] as $item) {
             $Item = array('l_name' => $item['name'], 'l_desc' => '', 'l_amt' => $item['amt'], 'l_number' => $item['number'], 'l_qty' => $item['qty'], 'l_taxamt' => '', 'l_ebayitemnumber' => '', 'l_ebayitemauctiontxnid' => '', 'l_ebayitemorderid' => '');
             array_push($OrderItems, $Item);
         }
     }
     /**
      * Shipping/tax/item amount
      */
     $PaymentDetails['taxamt'] = $PaymentData['taxamt'];
     $PaymentDetails['shippingamt'] = $PaymentData['shippingamt'];
     $PaymentDetails['itemamt'] = $PaymentData['itemamt'];
     /**
      * 3D Secure Params
      */
     if ($this->enable_3dsecure) {
         $Secure3D = array('authstatus3d' => $centinelPAResStatus, 'mpivendor3ds' => $centinelEnrolled, 'cavv' => $centinelCavv, 'eci3ds' => $centinelEciFlag, 'xid' => $centinelXid);
     } else {
         $Secure3D = array();
     }
     $PayPalRequestData = array('DPFields' => $DPFields, 'CCDetails' => $CCDetails, 'PayerInfo' => $PayerInfo, 'BillingAddress' => $BillingAddress, 'ShippingAddress' => $ShippingAddress, 'PaymentDetails' => $PaymentDetails, 'OrderItems' => $OrderItems, 'Secure3D' => $Secure3D);
     if ($this->debug) {
         $log = $PayPalRequestData;
         $log['CCDetails']['acct'] = '****';
         $log['CCDetails']['cvv2'] = '****';
         $this->log->add('paypal-pro', 'Do payment request ' . print_r($log, true));
     }
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->DoDirectPayment($PayPalRequestData);
     if ($this->debug) {
         $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : '';
         $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : '';
         $this->log->add('paypal-pro', 'Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true));
         $this->log->add('paypal-pro', 'Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true));
     }
     if (empty($PayPalResult['RAWRESPONSE'])) {
         $pc_empty_response = apply_filters('angelleye_pc_empty_response', __('Empty PayPal response.', 'paypal-for-woocommerce'), $PayPalResult);
         throw new Exception($pc_empty_response);
     }
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         // Add order note
         $order->add_order_note(sprintf(__('PayPal Pro payment completed (Transaction ID: %s, Correlation ID: %s)', 'paypal-for-woocommerce'), $PayPalResult['TRANSACTIONID'], $PayPalResult['CORRELATIONID']));
         //$order->add_order_note("PayPal Results: ".print_r($PayPalResult,true));
         /* Checkout Note */
         if (isset($_POST) && !empty($_POST['order_comments'])) {
             // Update post 37
             $checkout_note = array('ID' => $order->id, 'post_excerpt' => $_POST['order_comments']);
             wp_update_post($checkout_note);
         }
         /**
          * Add order notes for AVS result
          */
         $avs_response_code = isset($PayPalResult['AVSCODE']) ? $PayPalResult['AVSCODE'] : '';
         $avs_response_message = $PayPal->GetAVSCodeMessage($avs_response_code);
         $avs_response_order_note = __('Address Verification Result', 'paypal-for-woocommerce');
         $avs_response_order_note .= "\n";
         $avs_response_order_note .= $avs_response_code;
         $avs_response_order_note .= $avs_response_message != '' ? ' - ' . $avs_response_message : '';
         $order->add_order_note($avs_response_order_note);
         /**
          * Add order notes for CVV2 result
          */
         $cvv2_response_code = isset($PayPalResult['CVV2MATCH']) ? $PayPalResult['CVV2MATCH'] : '';
         $cvv2_response_message = $PayPal->GetCVV2CodeMessage($cvv2_response_code);
         $cvv2_response_order_note = __('Card Security Code Result', 'paypal-for-woocommerce');
         $cvv2_response_order_note .= "\n";
         $cvv2_response_order_note .= $cvv2_response_code;
         $cvv2_response_order_note .= $cvv2_response_message != '' ? ' - ' . $cvv2_response_message : '';
         $order->add_order_note($cvv2_response_order_note);
         // Payment complete
         $order->payment_complete($PayPalResult['TRANSACTIONID']);
         // Remove cart
         WC()->cart->empty_cart();
         // Return thank you page redirect
         return array('result' => 'success', 'redirect' => $this->get_return_url($order));
     } else {
         // Get error message
         $error_code = isset($PayPalResult['ERRORS'][0]['L_ERRORCODE']) ? $PayPalResult['ERRORS'][0]['L_ERRORCODE'] : '';
         $long_message = isset($PayPalResult['ERRORS'][0]['L_LONGMESSAGE']) ? $PayPalResult['ERRORS'][0]['L_LONGMESSAGE'] : '';
         $error_message = $error_code . '-' . $long_message;
         // Notice admin if has any issue from PayPal
         if ($this->error_email_notify) {
             $admin_email = get_option("admin_email");
             $message = __("DoDirectPayment API call failed.", "paypal-for-woocommerce") . "\n\n";
             $message .= __('Error Code: ', 'paypal-for-woocommerce') . $error_code . "\n";
             $message .= __('Detailed Error Message: ', 'paypal-for-woocommerce') . $long_message . "\n";
             $message .= __('Order ID: ') . $order->id . "\n";
             $message .= __('Customer Name: ') . $order->billing_first_name . ' ' . $order->billing_last_name . "\n";
             $message .= __('Customer Email: ') . $order->billing_email . "\n";
             $pc_error_email_message = apply_filters('angelleye_pc_error_email_notify_message', $message, $error_code, $long_message);
             $pc_error_email_subject = apply_filters('angelleye_pc_error_email_notify_subject', "PayPal Pro Error Notification", $error_code, $long_message);
             wp_mail($admin_email, $pc_error_email_subject, $pc_error_email_message);
         }
         if ($this->debug) {
             $this->log->add('paypal-pro', 'Error ' . print_r($PayPalResult['ERRORS'], true));
         }
         $order->update_status('failed', sprintf(__('PayPal Pro payment failed (Correlation ID: %s). Payment was rejected due to an error: %s', 'paypal-for-woocommerce'), $PayPalResult['CORRELATIONID'], '(' . $PayPalResult['L_ERRORCODE0'] . ') ' . '"' . $error_message . '"'));
         // Generate error message based on Error Display Type setting
         if ($this->error_display_type == 'detailed') {
             $pc_display_type_error = __($error_message, 'paypal-for-woocommerce');
             $pc_display_type_notice = __('Payment error:', 'paypal-for-woocommerce') . ' ' . $error_message;
         } else {
             $pc_display_type_error = __('There was a problem connecting to the payment gateway.', 'paypal-for-woocommerce');
             $pc_display_type_notice = __('Payment error:', 'paypal-for-woocommerce') . ' ' . $error_message;
         }
         $pc_display_type_error = apply_filters('angelleye_pc_display_type_error', $pc_display_type_error, $error_code, $long_message);
         $pc_display_type_notice = apply_filters('angelleye_pc_display_type_notice', $pc_display_type_notice, $error_code, $long_message);
         wc_add_notice($pc_display_type_notice, "error");
         throw new Exception($pc_display_type_error);
         return;
     }
 }
 public static function is_wc_version_greater_2_3()
 {
     return AngellEYE_Gateway_Paypal::get_wc_version() && version_compare(AngellEYE_Gateway_Paypal::get_wc_version(), '2.3', '>=');
 }
 /**
  * Process a refund if supported
  * @param  int $order_id
  * @param  float $amount
  * @param  string $reason
  * @return  bool|wp_error True or false based on success, or a WP_Error object
  */
 public function process_refund($order_id, $amount = null, $reason = '')
 {
     do_action('angelleye_before_fc_refund', $order_id, $amount, $reason);
     $order = wc_get_order($order_id);
     $this->add_log('Begin Refund');
     $this->add_log('Order: ' . print_r($order, true));
     $this->add_log('Transaction ID: ' . print_r($order->get_transaction_id(), true));
     if (!$order || !$order->get_transaction_id() || !$this->paypal_user || !$this->paypal_password || !$this->paypal_vendor) {
         return false;
     }
     /*
      * Check if the PayPal_PayFlow class has already been established.
      */
     if (!class_exists('Angelleye_PayPal_PayFlow')) {
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php';
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.payflow.class.php';
     }
     /**
      * Create PayPal_PayFlow object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? true : false, 'APIUsername' => $this->paypal_user, 'APIPassword' => trim($this->paypal_password), 'APIVendor' => $this->paypal_vendor, 'APIPartner' => $this->paypal_partner);
     $PayPal = new Angelleye_PayPal_PayFlow($PayPalConfig);
     $PayPalRequestData = array('TENDER' => 'C', 'TRXTYPE' => 'C', 'ORIGID' => $order->get_transaction_id(), 'AMT' => $amount, 'CURRENCY' => $order->get_order_currency());
     $this->add_log('Refund Request: ' . print_r($PayPalRequestData, true));
     $PayPalResult = $PayPal->ProcessTransaction($PayPalRequestData);
     /**
      *  cURL Error Handling #146 
      *  @since    1.1.8
      */
     AngellEYE_Gateway_Paypal::angelleye_paypal_for_woocommerce_curl_error_handler($PayPalResult, $methos_name = 'Refund Request', $gateway = 'PayPal Payments Pro 2.0 (PayFlow)', $this->error_email_notify);
     $this->add_log('Refund Information: ' . print_r($PayPalResult, true));
     add_action('angelleye_after_refund', $PayPalResult, $order, $amount, $reason);
     if (isset($PayPalResult['RESULT']) && ($PayPalResult['RESULT'] == 0 || $PayPalResult['RESULT'] == 126)) {
         $order->add_order_note('Refund Transaction ID:' . $PayPalResult['PNREF']);
         $max_remaining_refund = wc_format_decimal($order->get_total() - $order->get_total_refunded());
         if (!$max_remaining_refund > 0) {
             $order->update_status('refunded');
         }
         if (ob_get_length()) {
             ob_end_clean();
         }
         return true;
     } else {
         $fc_refund_error = apply_filters('ae_pppf_refund_error_message', $PayPalResult['RESPMSG'], $PayPalResult);
         return new WP_Error('paypal-error', $fc_refund_error);
     }
     return false;
 }
        }
    </style>

    <?php 
    do_action('angelleye_review_order_before_login_create_account');
    ?>

    <div class="title">
        <h2><?php 
    _e('Login', 'woocommerce');
    ?>
</h2>
    </div>
    <form name="" action="" method="post">
        <?php 
    woocommerce_login_form(array('message' => 'Please login or create an account to complete your order.', 'redirect' => AngellEYE_Gateway_Paypal::curPageURL(), 'hidden' => true));
    ?>
    </form>
    <div class="title">
        <h2><?php 
    _e('Create A New Account', 'woocommerce');
    ?>
</h2>
    </div>
    <form action="<?php 
    echo add_query_arg(array('pp_action' => 'revieworder'));
    ?>
" method="post">
        <p class="form-row form-row-first">
            <label for="paypalexpress_order_review_username">Username:<span class="required">*</span></label>
            <input style="width: 100%;" type="text" name="username" id="paypalexpress_order_review_username" value="<?php 
 /**
  * do_payment
  *
  * Process the PayFlow transaction with PayPal.
  *
  * @access public
  * @param mixed $order
  * @param mixed $card_number
  * @param mixed $card_exp
  * @param mixed $card_csc
  * @param string $centinelPAResStatus (default: '')
  * @param string $centinelEnrolled (default: '')
  * @param string $centinelCavv (default: '')
  * @param string $centinelEciFlag (default: '')
  * @param string $centinelXid (default: '')
  * @return void
  */
 function do_payment($order, $card_number, $card_exp, $card_csc, $centinelPAResStatus = '', $centinelEnrolled = '', $centinelCavv = '', $centinelEciFlag = '', $centinelXid = '')
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         $fc_session_expired = apply_filters('angelleye_fc_session_expired', sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'), $this);
         wc_add_notice($fc_session_expired, "error");
     }
     /*
      * Check if the PayPal_PayFlow class has already been established.
      */
     if (!class_exists('Angelleye_PayPal_PayFlow')) {
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php';
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.payflow.class.php';
     }
     /**
      * Create PayPal_PayFlow object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? true : false, 'APIUsername' => $this->paypal_user, 'APIPassword' => trim($this->paypal_password), 'APIVendor' => $this->paypal_vendor, 'APIPartner' => $this->paypal_partner);
     $PayPal = new Angelleye_PayPal_PayFlow($PayPalConfig);
     /**
      * Pulled from original Woo extension.
      */
     if (empty($GLOBALS['wp_rewrite'])) {
         $GLOBALS['wp_rewrite'] = new WP_Rewrite();
     }
     if ($this->debug) {
         $this->add_log($order->get_checkout_order_received_url());
     }
     try {
         /**
          * Parameter set by original Woo.  I can probably ditch this, but leaving it for now.
          */
         $url = $this->testmode == 'yes' ? $this->testurl : $this->liveurl;
         /**
          * PayPal PayFlow Gateway Request Params
          */
         $PayPalRequestData = array('tender' => 'C', 'trxtype' => $this->payment_action == 'Authorization' ? 'A' : 'S', 'acct' => $card_number, 'expdate' => $card_exp, 'amt' => number_format($order->get_total(), 2, '.', ''), 'currency' => get_woocommerce_currency(), 'dutyamt' => '', 'freightamt' => '', 'taxamt' => '', 'taxexempt' => '', 'comment1' => $order->customer_note ? substr(preg_replace("/[^A-Za-z0-9 ]/", "", $order->customer_note), 0, 256) : '', 'comment2' => '', 'cvv2' => $card_csc, 'recurring' => '', 'swipe' => '', 'orderid' => preg_replace("/[^0-9,.]/", "", $order->get_order_number()), 'orderdesc' => 'Order ' . $order->get_order_number() . ' on ' . get_bloginfo('name'), 'billtoemail' => $order->billing_email, 'billtophonenum' => '', 'billtofirstname' => $order->billing_first_name, 'billtomiddlename' => '', 'billtolastname' => $order->billing_last_name, 'billtostreet' => $order->billing_address_1 . ' ' . $order->billing_address_2, 'billtocity' => $order->billing_city, 'billtostate' => $order->billing_state, 'billtozip' => $order->billing_postcode, 'billtocountry' => $order->billing_country, 'origid' => '', 'custref' => '', 'custcode' => '', 'custip' => $this->get_user_ip(), 'invnum' => $this->invoice_id_prefix . str_replace("#", "", $order->get_order_number()), 'ponum' => '', 'starttime' => '', 'endtime' => '', 'securetoken' => '', 'partialauth' => '', 'authcode' => '');
         /**
          * Shipping info
          */
         if ($order->shipping_address_1) {
             $PayPalRequestData['SHIPTOFIRSTNAME'] = $order->shipping_first_name;
             $PayPalRequestData['SHIPTOLASTNAME'] = $order->shipping_last_name;
             $PayPalRequestData['SHIPTOSTREET'] = $order->shipping_address_1 . ' ' . $order->shipping_address_2;
             $PayPalRequestData['SHIPTOCITY'] = $order->shipping_city;
             $PayPalRequestData['SHIPTOSTATE'] = $order->shipping_state;
             $PayPalRequestData['SHIPTOCOUNTRY'] = $order->shipping_country;
             $PayPalRequestData['SHIPTOZIP'] = $order->shipping_postcode;
         }
         $PaymentData = AngellEYE_Gateway_Paypal::calculate($order, $this->send_items);
         $OrderItems = array();
         if ($this->send_items) {
             $item_loop = 0;
             foreach ($PaymentData['order_items'] as $_item) {
                 $Item['L_NUMBER' . $item_loop] = $_item['number'];
                 $Item['L_NAME' . $item_loop] = $_item['name'];
                 $Item['L_COST' . $item_loop] = $_item['amt'];
                 $Item['L_QTY' . $item_loop] = $_item['qty'];
                 if ($_item['number']) {
                     $Item['L_SKU' . $item_loop] = $_item['number'];
                 }
                 array_push($OrderItems, $Item);
             }
         }
         /**
          * Shipping/tax/item amount
          */
         $PayPalRequestData['taxamt'] = $PaymentData['taxamt'];
         $PayPalRequestData['freightamt'] = $PaymentData['shippingamt'];
         $PayPalRequestData['ITEMAMT'] = $PaymentData['itemamt'];
         $PayPalRequestData = array_merge($PayPalRequestData, $OrderItems);
         $PayPalResult = $PayPal->ProcessTransaction($PayPalRequestData);
         /**
          * Log results
          */
         if ($this->debug) {
             $this->add_log('PayFlow Endpoint: ' . $PayPal->APIEndPoint);
             $this->add_log(print_r($PayPalResult, true));
         }
         /**
          * Error check
          */
         if (empty($PayPalResult['RAWRESPONSE'])) {
             $fc_empty_response = apply_filters('angelleye_fc_empty_response', __('Empty PayPal response.', 'paypal-for-woocommerce'), $PayPalResult);
             throw new Exception($fc_empty_response);
         }
         /** 
          * More logs
          */
         if ($this->debug) {
             $this->add_log(add_query_arg('key', $order->order_key, add_query_arg('order', $order->id)));
         }
         /**
          * Check for errors or fraud filter warnings and proceed accordingly.
          */
         if (isset($PayPalResult['RESULT']) && ($PayPalResult['RESULT'] == 0 || $PayPalResult['RESULT'] == 126)) {
             // Add order note
             if ($PayPalResult['RESULT'] == 126) {
                 $order->add_order_note($PayPalResult['RESPMSG']);
                 $order->add_order_note($PayPalResult['PREFPSMSG']);
                 $order->add_order_note("The payment was flagged by a fraud filter, please check your PayPal Manager account to review and accept or deny the payment.");
             } else {
                 $order->add_order_note(sprintf(__('PayPal Pro payment completed (PNREF: %s)', 'paypal-for-woocommerce'), $PayPalResult['PNREF']));
                 /* Checkout Note */
                 if (isset($_POST) && !empty($_POST['order_comments'])) {
                     // Update post 37
                     $checkout_note = array('ID' => $order->id, 'post_excerpt' => $_POST['order_comments']);
                     wp_update_post($checkout_note);
                 }
             }
             /**
              * Add order notes for AVS result
              */
             $avs_address_response_code = isset($PayPalResult['AVSADDR']) ? $PayPalResult['AVSADDR'] : '';
             $avs_zip_response_code = isset($PayPalResult['AVSZIP']) ? $PayPalResult['AVSZIP'] : '';
             $avs_response_order_note = __('Address Verification Result', 'paypal-for-woocommerce');
             $avs_response_order_note .= "\n";
             $avs_response_order_note .= sprintf(__('Address Match: %s', 'paypal-for-woocommerce'), $avs_address_response_code);
             $avs_response_order_note .= "\n";
             $avs_response_order_note .= sprintf(__('Postal Match: %s', 'paypal-for-woocommerce'), $avs_zip_response_code);
             $order->add_order_note($avs_response_order_note);
             /**
              * Add order notes for CVV2 result
              */
             $cvv2_response_code = isset($PayPalResult['CVV2MATCH']) ? $PayPalResult['CVV2MATCH'] : '';
             $cvv2_response_order_note = __('Card Security Code Result', 'paypal-for-woocommerce');
             $cvv2_response_order_note .= "\n";
             $cvv2_response_order_note .= sprintf(__('CVV2 Match: %s', 'paypal-for-woocommerce'), $cvv2_response_code);
             $order->add_order_note($cvv2_response_order_note);
             // Payment complete
             //$order->add_order_note("PayPal Result".print_r($PayPalResult,true));
             $order->payment_complete($PayPalResult['PNREF']);
             // Remove cart
             WC()->cart->empty_cart();
             // Return thank you page redirect
             return array('result' => 'success', 'redirect' => $this->get_return_url($order));
         } else {
             $order->update_status('failed', __('PayPal Pro payment failed. Payment was rejected due to an error: ', 'paypal-for-woocommerce') . '(' . $PayPalResult['RESULT'] . ') ' . '"' . $PayPalResult['RESPMSG'] . '"');
             // Generate error message based on Error Display Type setting
             if ($this->error_display_type == 'detailed') {
                 $fc_error_display_type = __('Payment error:', 'paypal-for-woocommerce') . ' ' . $PayPalResult['RESULT'] . '-' . $PayPalResult['RESPMSG'];
             } else {
                 $fc_error_display_type = __('Payment error:', 'paypal-for-woocommerce') . ' There was a problem processing your payment.  Please try another method.';
             }
             $fc_error_display_type = apply_filters('angelleye_fc_dp_error_display_type', $fc_error_display_type, $PayPalResult['RESULT'], $PayPalResult['RESPMSG'], $PayPalResult);
             wc_add_notice($fc_error_display_type, "error");
             // Notice admin if has any issue from PayPal
             if ($this->error_email_notify) {
                 $admin_email = get_option("admin_email");
                 $message = __("PayFlow API call failed.", "paypal-for-woocommerce") . "\n\n";
                 $message .= __('Error Code: ', 'paypal-for-woocommerce') . $PayPalResult['RESULT'] . "\n";
                 $message .= __('Detailed Error Message: ', 'paypal-for-woocommerce') . $PayPalResult['RESPMSG'];
                 $message .= isset($PayPalResult['PREFPSMSG']) && $PayPalResult['PREFPSMSG'] != '' ? ' - ' . $PayPalResult['PREFPSMSG'] . "\n" : "\n";
                 $message .= __('Order ID: ') . $order->id . "\n";
                 $message .= __('Customer Name: ') . $order->billing_first_name . ' ' . $order->billing_last_name . "\n";
                 $message .= __('Customer Email: ') . $order->billing_email . "\n";
                 $message = apply_filters('angelleye_fc_error_email_notify_msg', $message);
                 $subject = apply_filters('angelleye_fc_error_email_notify_subject', "PayPal Pro Error Notification");
                 wp_mail($admin_email, $subject, $message);
             }
             return;
         }
     } catch (Exception $e) {
         $fc_connect_error = apply_filters('angelleye_fc_connect_error', __('Connection error:', 'paypal-for-woocommerce') . ': "' . $e->getMessage() . '"', $e);
         wc_add_notice($fc_connect_error, "error");
         return;
     }
 }
 /**
  * ConfirmPayment
  *
  * Finalizes the checkout with PayPal's DoExpressCheckoutPayment API
  *
  * @FinalPaymentAmt (double) Final payment amount for the order.
  */
 function ConfirmPayment($FinalPaymentAmt)
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0 || empty(WC()->session->TOKEN)) {
         $ms = sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"');
         $ec_confirm_message = apply_filters('angelleye_ec_confirm_message', $ms);
         wc_add_notice($ec_confirm_message, "error");
         wp_redirect(get_permalink(wc_get_page_id('cart')));
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php';
     }
     /*
      * Create PayPal object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? TRUE : FALSE, 'APIUsername' => $this->api_username, 'APIPassword' => $this->api_password, 'APISignature' => $this->api_signature);
     $PayPal = new Angelleye_PayPal($PayPalConfig);
     /*
      * Get data from WooCommerce object
      */
     if (!empty($this->confirm_order_id)) {
         $order = new WC_Order($this->confirm_order_id);
         $invoice_number = preg_replace("/[^0-9,.]/", "", $order->get_order_number());
         if ($order->customer_note) {
             $customer_notes = wptexturize($order->customer_note);
         }
         $shipping_first_name = $order->shipping_first_name;
         $shipping_last_name = $order->shipping_last_name;
         $shipping_address_1 = $order->shipping_address_1;
         $shipping_address_2 = $order->shipping_address_2;
         $shipping_city = $order->shipping_city;
         $shipping_state = $order->shipping_state;
         $shipping_postcode = $order->shipping_postcode;
         $shipping_country = $order->shipping_country;
     }
     // Prepare request arrays
     $DECPFields = array('token' => urlencode($this->get_session('TOKEN')), 'payerid' => urlencode($this->get_session('payer_id')), 'returnfmfdetails' => '', 'giftmessage' => $this->get_session('giftmessage'), 'giftreceiptenable' => $this->get_session('giftreceiptenable'), 'giftwrapname' => $this->get_session('giftwrapname'), 'giftwrapamount' => $this->get_session('giftwrapamount'), 'buyermarketingemail' => '', 'surveyquestion' => '', 'surveychoiceselected' => '', 'allowedpaymentmethod' => '');
     $Payments = array();
     $Payment = array('amt' => number_format($FinalPaymentAmt, 2, '.', ''), 'currencycode' => get_woocommerce_currency(), 'shippingdiscamt' => '', 'insuranceoptionoffered' => '', 'handlingamt' => '', 'desc' => '', 'custom' => '', 'invnum' => $this->invoice_id_prefix . $invoice_number, 'notifyurl' => '', 'shiptoname' => $shipping_first_name . ' ' . $shipping_last_name, 'shiptostreet' => $shipping_address_1, 'shiptostreet2' => $shipping_address_2, 'shiptocity' => $shipping_city, 'shiptostate' => $shipping_state, 'shiptozip' => $shipping_postcode, 'shiptocountrycode' => $shipping_country, 'shiptophonenum' => '', 'notetext' => $this->get_session('customer_notes'), 'allowedpaymentmethod' => '', 'paymentaction' => $this->payment_action == 'Authorization' ? 'Authorization' : 'Sale', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '', 'sellerid' => '', 'sellerusername' => '', 'sellerregistrationdate' => '', 'softdescriptor' => '');
     $PaymentData = AngellEYE_Gateway_Paypal::calculate($order, $this->send_items);
     $PaymentOrderItems = array();
     if ($this->send_items) {
         foreach ($PaymentData['order_items'] as $item) {
             $Item = array('name' => $item['name'], 'desc' => '', 'amt' => $item['amt'], 'number' => $item['number'], 'qty' => $item['qty'], 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
             array_push($PaymentOrderItems, $Item);
         }
     }
     /*
      * Set tax, shipping, itemamt
      */
     $Payment['taxamt'] = $PaymentData['taxamt'];
     // Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
     $Payment['shippingamt'] = $PaymentData['shippingamt'];
     // Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
     $Payment['itemamt'] = $PaymentData['itemamt'];
     // Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
     $Payment['order_items'] = $PaymentOrderItems;
     array_push($Payments, $Payment);
     $UserSelectedOptions = array('shippingcalculationmode' => '', 'insuranceoptionselected' => '', 'shippingoptionisdefault' => '', 'shippingoptionamount' => '', 'shippingoptionname' => '');
     $PayPalRequestData = array('DECPFields' => $DECPFields, 'Payments' => $Payments);
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData);
     /*
      * Log API result
      */
     $this->add_log('Test Mode: ' . $this->testmode);
     $this->add_log('Endpoint: ' . $this->API_Endpoint);
     $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : '';
     $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : '';
     $this->add_log('Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true));
     $this->add_log('Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true));
     /*
      * Error handling
      */
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         $this->remove_session('TOKEN');
     }
     /*
      * Return the class library result array.
      */
     return $PayPalResult;
 }