/**
 * Get replacement elements for country and region fields on the checkout form
 *
 *  Note: extracted from the wpsc_change_tax function in ajax.php as of version 3.8.13.3
 *
 * @since 3.8.14
 * @access private
 * @return array  checkout information
 */
function _wpsc_get_checkout_info()
{
    global $wpsc_cart;
    // Checkout info is what we will return to the AJAX client
    $checkout_info = array();
    // start with items that have no dependencies
    $checkout_info['delivery_country'] = wpsc_get_customer_meta('shippingcountry');
    $checkout_info['billing_country'] = wpsc_get_customer_meta('billingcountry');
    $checkout_info['country_name'] = wpsc_get_country($checkout_info['delivery_country']);
    $checkout_info['lock_tax'] = get_option('lock_tax');
    // TODO: this is set anywhere, probably deprecated
    $checkout_info['needs_shipping_recalc'] = wpsc_cart_need_to_recompute_shipping_quotes();
    $checkout_info['shipping_keys'] = array();
    foreach ($wpsc_cart->cart_items as $key => $cart_item) {
        $checkout_info['shipping_keys'][$key] = wpsc_currency_display($cart_item->shipping);
    }
    if (!$checkout_info['needs_shipping_recalc']) {
        $wpsc_cart->update_location();
        $wpsc_cart->get_shipping_method();
        $wpsc_cart->get_shipping_option();
        if ($wpsc_cart->selected_shipping_method != '') {
            $wpsc_cart->update_shipping($wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option);
        }
        $tax = $wpsc_cart->calculate_total_tax();
        $total = wpsc_cart_total();
        $total_input = wpsc_cart_total(false);
        if ($wpsc_cart->coupons_amount >= $total_input && !empty($wpsc_cart->coupons_amount)) {
            $total = 0;
        }
        if ($wpsc_cart->total_price < 0) {
            $wpsc_cart->coupons_amount += $wpsc_cart->total_price;
            $wpsc_cart->total_price = null;
            $wpsc_cart->calculate_total_price();
        }
        $cart_widget = _wpsc_ajax_get_cart(false);
        if (isset($cart_widget['widget_output']) && !empty($cart_widget['widget_output'])) {
            $checkout_info['widget_output'] = $cart_widget['widget_output'];
        }
        $checkout_info['cart_shipping'] = wpsc_cart_shipping();
        $checkout_info['tax'] = $tax;
        $checkout_info['display_tax'] = wpsc_cart_tax();
        $checkout_info['total'] = $total;
        $checkout_info['total_input'] = $total_input;
    }
    return apply_filters('wpsc_ajax_checkout_info', $checkout_info);
}
Example #2
0
   	</tr>
	  <?php 
    }
    ?>

		
	
	<tr class='total_price'>
		<td colspan='3'>
		<?php 
    echo TXT_WPSC_TOTALPRICE;
    ?>
		</td>
		<td colspan='2'>
			<span id='checkout_total' class="pricedisplay checkout-total"><?php 
    echo wpsc_cart_total();
    ?>
</span>
		</td>
	</tr>
	
	
	</table>

		<?php 
    do_action('wpsc_before_form_of_shopping_cart');
    ?>
	
	<form class='wpsc_checkout_forms' action='' method='post' enctype="multipart/form-data">
	
	   <?php 
Example #3
0
/**
	* wpsc_change_tax function, used through ajax and in normal page loading.
	* No parameters, returns nothing
*/
function wpsc_change_tax()
{
    global $wpdb, $wpsc_cart, $wpsc_theme_path;
    $form_id = absint($_POST['form_id']);
    $wpsc_selected_country = $wpsc_cart->selected_country;
    $wpsc_selected_region = $wpsc_cart->selected_region;
    $wpsc_delivery_country = $wpsc_cart->delivery_country;
    $wpsc_delivery_region = $wpsc_cart->delivery_region;
    $previous_country = $_SESSION['wpsc_selected_country'];
    if (isset($_POST['billing_country'])) {
        $wpsc_selected_country = $wpdb->escape($_POST['billing_country']);
        $_SESSION['wpsc_selected_country'] = $wpsc_selected_country;
    }
    if (isset($_POST['billing_region'])) {
        $wpsc_selected_region = absint($_POST['billing_region']);
        $_SESSION['wpsc_selected_region'] = $wpsc_selected_region;
    }
    //if(!wpsc_has_shipping_form()) {
    //	$_POST['shipping_country'] = $wpsc_selected_country;
    //	$_POST['shipping_region'] = $wpsc_selected_region;
    //}
    $check_country_code = $wpdb->get_var(" SELECT `country`.`isocode` FROM `" . WPSC_TABLE_REGION_TAX . "` AS `region` INNER JOIN `" . WPSC_TABLE_CURRENCY_LIST . "` AS `country` ON `region`.`country_id` = `country`.`id` WHERE `region`.`id` = '" . $_SESSION['wpsc_selected_region'] . "' LIMIT 1");
    if ($_SESSION['wpsc_selected_country'] != $check_country_code) {
        $wpsc_selected_region = null;
    }
    if (isset($_POST['shipping_country'])) {
        $wpsc_delivery_country = $wpdb->escape($_POST['shipping_country']);
        $_SESSION['wpsc_delivery_country'] = $wpsc_delivery_country;
    }
    if (isset($_POST['shipping_region'])) {
        $wpsc_delivery_region = absint($_POST['shipping_region']);
        $_SESSION['wpsc_delivery_region'] = $wpsc_delivery_region;
    }
    $check_country_code = $wpdb->get_var(" SELECT `country`.`isocode` FROM `" . WPSC_TABLE_REGION_TAX . "` AS `region` INNER JOIN `" . WPSC_TABLE_CURRENCY_LIST . "` AS `country` ON `region`.`country_id` = `country`.`id` WHERE `region`.`id` = '" . $wpsc_delivery_region . "' LIMIT 1");
    if ($wpsc_delivery_country != $check_country_code) {
        $wpsc_delivery_region = null;
    }
    $wpsc_cart->update_location();
    $wpsc_cart->get_shipping_method();
    $wpsc_cart->get_shipping_option();
    if ($wpsc_cart->selected_shipping_method != '') {
        $wpsc_cart->update_shipping($wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option);
    }
    $tax = $wpsc_cart->calculate_total_tax();
    $total = wpsc_cart_total();
    ob_start();
    $cur_wpsc_theme_folder = apply_filters('wpsc_theme_folder', $wpsc_theme_path . WPSC_THEME_DIR);
    include_once $cur_wpsc_theme_folder . "/cart_widget.php";
    $output = ob_get_contents();
    ob_end_clean();
    //exit("/*<pre>".print_r($wpsc_cart,true)."</pre>*/");
    $output = str_replace(array("\n", "\r"), array("\\n", "\\r"), addslashes($output));
    if (get_option('lock_tax') == 1) {
        //echo "jQuery('#region').val(".$_SESSION['wpsc_delivery_region']."); \n";
        echo "jQuery('#current_country').val('" . $_SESSION['wpsc_delivery_country'] . "'); \n";
        if ($_SESSION['wpsc_delivery_country'] == 'US' && get_option('lock_tax') == 1) {
            //exit('<pre>'.print_r($_SESSION, true).'</pre>');
            $output = wpsc_shipping_region_list($_SESSION['wpsc_delivery_country'], $_SESSION['wpsc_delivery_region']);
            //	echo 'jQuery("#change_country").append(\''.$output.'\');\n\r';
            $output = str_replace(array("\n", "\r"), array("\\n", "\\r"), addslashes($output));
            echo "jQuery('#region').remove();\n\r";
            echo "jQuery('#change_country').append(\"" . $output . "\");\n\r";
        }
    }
    foreach ($wpsc_cart->cart_items as $key => $cart_item) {
        echo "jQuery('#shipping_{$key}').html(\"" . $wpsc_cart->process_as_currency($cart_item->shipping) . "\");\n\r";
    }
    echo "jQuery('#checkout_shipping').html(\"" . wpsc_cart_shipping() . "\");\n\r";
    echo "jQuery('div.shopping-cart-wrapper').html('{$output}');\n";
    if (get_option('lock_tax') == 1) {
        echo "jQuery('.shipping_country').val('" . $_SESSION['wpsc_delivery_country'] . "') \n";
        $sql = "SELECT `country` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `isocode`='" . $_SESSION['wpsc_selected_country'] . "'";
        $country_name = $wpdb->get_var($sql);
        echo "jQuery('.shipping_country_name').html('" . $country_name . "') \n";
    }
    $form_selected_country = null;
    $form_selected_region = null;
    $onchange_function = null;
    if ($_POST['billing_country'] != 'undefined' && !isset($_POST['shipping_country'])) {
        $form_selected_country = $wpsc_selected_country;
        $form_selected_region = $wpsc_selected_region;
        $onchange_function = 'set_billing_country';
        $title = 'billingregion';
    } else {
        if ($_POST['shipping_country'] != 'undefined' && !isset($_POST['billing_country'])) {
            $form_selected_country = $wpsc_delivery_country;
            $form_selected_region = $wpsc_delivery_region;
            $onchange_function = 'set_shipping_country';
            $title = 'shippingregion';
        }
    }
    if ($form_selected_country != null && $onchange_function != null) {
        $region_list = $wpdb->get_results("SELECT `" . WPSC_TABLE_REGION_TAX . "`.* FROM `" . WPSC_TABLE_REGION_TAX . "`, `" . WPSC_TABLE_CURRENCY_LIST . "`  WHERE `" . WPSC_TABLE_CURRENCY_LIST . "`.`isocode` IN('" . $form_selected_country . "') AND `" . WPSC_TABLE_CURRENCY_LIST . "`.`id` = `" . WPSC_TABLE_REGION_TAX . "`.`country_id`", ARRAY_A);
        if ($region_list != null) {
            $output = "<select title='{$title}' name='collected_data[" . $form_id . "][1]' class='current_region' onchange='{$onchange_function}(\"region_country_form_{$form_id}\", \"{$form_id}\");'>\n\r";
            foreach ($region_list as $region) {
                if ($form_selected_region == $region['id']) {
                    $selected = "selected='selected'";
                } else {
                    $selected = "";
                }
                $output .= "  <option value='" . $region['id'] . "' {$selected}>" . htmlspecialchars($region['name']) . "</option>\n\r";
            }
            $output .= "</select>\n\r";
            $output = str_replace(array("\n", "\r"), array("\\n", "\\r"), addslashes($output));
            echo "jQuery('#region_select_{$form_id}').html(\"" . $output . "\");\n\r";
        } else {
            if (get_option('lock_tax') == 1) {
                echo "jQuery('#region').hide();";
            }
            echo "jQuery('#region_select_{$form_id}').html('');\n\r";
        }
    }
    if ($tax > 0) {
        echo "jQuery(\"tr.total_tax\").show();\n\r";
    } else {
        echo "jQuery(\"tr.total_tax\").hide();\n\r";
    }
    echo "jQuery('#checkout_tax').html(\"<span class='pricedisplay'>" . wpsc_cart_tax() . "</span>\");\n\r";
    echo "jQuery('#checkout_total').html(\"<span class='pricedisplay'>{$total}</span><input id='shopping_cart_total_price' type='hidden' value='{$total}' />\");\n\r";
    //echo "\n\r/*\n\r{$wpsc_cart->tax_percentage}\n\r*/\n\r";
    exit;
}
			<?php echo __('Discount', 'wpsc'); ?>
		</td>
		<td colspan="2">
			<span id="coupons_amount" class="pricedisplay"><?php echo wpsc_coupon_amount(); ?></span>
	    </td>
   	</tr>
	  <?php endif ?>

		
	
	<tr class='total_price'>
		<td colspan='3'>
		<?php echo __('Total Price', 'wpsc'); ?>
		</td>
		<td colspan='2'>
			<span id='checkout_total' class="pricedisplay checkout-total"><?php echo wpsc_cart_total(); ?></span>
		</td>
	</tr>
	
	
	</table>

		<?php do_action('wpsc_before_form_of_shopping_cart'); ?>
	
	<form class='wpsc_checkout_forms' action='' method='post' enctype="multipart/form-data">
	
	   <?php 
	   /**  
	    * Both the registration forms and the checkout details forms must be in the same form element as they are submitted together, you cannot have two form elements submit together without the use of JavaScript.
	   */
	   ?>
/**
 * prcessing functions, this is where the main logic of paypal express lives
 * @access public
 *
 * @since 3.8
 */
function paypal_processingfunctions()
{
    global $wpdb, $wpsc_cart;
    $sessionid = (string) wpsc_get_customer_meta('paypal_express_sessionid');
    if (isset($_REQUEST['act']) && 'error' == $_REQUEST['act']) {
        $resArray = wpsc_get_customer_meta('paypal_express_reshash');
        $paypal_express_message = '
		<center>
		<table width="700" align="left">
		<tr>
			<td colspan="2" class="header">' . __('The PayPal API has returned an error!', 'wpsc') . '</td>
		</tr>
		';
        //it will print if any URL errors
        if (wpsc_get_customer_meta('paypal_express_curl_error_msg')) {
            $errorMessage = wpsc_get_customer_meta('paypal_express_curl_error_msg');
            $response = wpsc_get_customer_meta('paypal_express_response');
            $paypal_express_message .= '
			<tr>
				<td>response:</td>
				<td>' . $response . '</td>
			</tr>

			<tr>
				<td>Error Message:</td>
				<td>' . $errorMessage . '</td>
			</tr>';
        } else {
            /* If there is no URL Errors, Construct the HTML page with
               Response Error parameters.   */
            $paypal_express_message .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Ack:</td>\n\t\t\t\t\t<td>" . $resArray['ACK'] . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Correlation ID:</td>\n\t\t\t\t\t<td>" . $resArray['CORRELATIONID'] . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Version:</td>\n\t\t\t\t\t<td>" . $resArray['VERSION'] . "</td>\n\t\t\t\t</tr>";
            $count = 0;
            while (isset($resArray["L_SHORTMESSAGE" . $count])) {
                $errorCode = $resArray["L_ERRORCODE" . $count];
                $shortMessage = $resArray["L_SHORTMESSAGE" . $count];
                $longMessage = $resArray["L_LONGMESSAGE" . $count];
                $count = $count + 1;
                $paypal_express_message .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Error Number:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$errorCode} </td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Short Message:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$shortMessage} </td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Long Message:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$longMessage} </td>\n\t\t\t\t\t</tr>";
            }
            //end while
        }
        // end else
        $paypal_express_message .= "\n\t\t\t</center>\n\t\t\t\t</table>";
        wpsc_update_customer_meta('paypal_express_message', $paypal_express_message);
    } else {
        if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'do') {
            /* Gather the information to make the final call to
               finalize the PayPal payment.  The variable nvpstr
               holds the name value pairs   */
            $token = urlencode($_REQUEST['token']);
            $paymentAmount = urlencode(wpsc_get_customer_meta('paypal_express_converted_amount'));
            $paymentType = urlencode(wpsc_get_customer_meta('paypal_express_payment_type'));
            $currCodeType = urlencode(wpsc_get_paypal_currency_code());
            $payerID = urlencode($_REQUEST['PayerID']);
            $serverName = urlencode($_SERVER['SERVER_NAME']);
            $BN = 'Instinct_e-commerce_wp-shopping-cart_NZ';
            $nvpstr = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=Sale&PAYMENTREQUEST_0_CURRENCYCODE=' . $currCodeType . '&IPADDRESS=' . $serverName . "&BUTTONSOURCE=" . $BN . "&PAYMENTREQUEST_0_INVNUM=" . urlencode($sessionid);
            // IPN data
            if (get_option('paypal_ipn') == 1) {
                $notify_url = add_query_arg('wpsc_action', 'gateway_notification', get_option('siteurl') . "/index.php");
                $notify_url = add_query_arg('gateway', 'wpsc_merchant_paypal_express', $notify_url);
                $notify_url = apply_filters('wpsc_paypal_express_notify_url', $notify_url);
                $nvpstr .= '&PAYMENTREQUEST_0_NOTIFYURL=' . urlencode($notify_url);
            }
            // Horrible code that I had to write to hot fix the issue with missing item detail in email receipts. arrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrgh!!!!! @#@$%@#%@##$#$
            $purchase_log = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` = %s", $sessionid), ARRAY_A);
            $cart_data = $original_cart_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid` = {$purchase_log['id']}", ARRAY_A);
            $i = 0;
            $item_total = 0;
            $shipping_total = 0;
            foreach ($cart_data as $cart_item) {
                $converted_price = wpsc_paypal_express_convert($cart_item['price']);
                $nvpstr .= "&L_PAYMENTREQUEST_0_NAME{$i}=" . urlencode(apply_filters('the_title', $cart_item['name']));
                $nvpstr .= "&L_PAYMENTREQUEST_0_AMT{$i}=" . $converted_price;
                $nvpstr .= "&L_PAYMENTREQUEST_0_NUMBER{$i}=" . $i;
                $nvpstr .= "&L_PAYMENTREQUEST_0_QTY{$i}=" . $cart_item['quantity'];
                $item_total += $converted_price * $cart_item['quantity'];
                $shipping_total += wpsc_paypal_express_convert($cart_item['pnp']);
                $i++;
            }
            //if we have a discount then include a negative amount with that discount
            if ($purchase_log['discount_value'] && 0.0 != $purchase_log['discount_value']) {
                $discount_value = wpsc_paypal_express_convert($purchase_log['discount_value']);
                // if item total < discount amount, leave at least 0.01 unit in item total, then subtract
                // 0.01 from shipping as well
                if ($discount_value >= $item_total) {
                    $discount_value = $item_total - 0.01;
                    $shipping_total -= 0.01;
                }
                $nvpstr .= "&L_PAYMENTREQUEST_0_NAME{$i}=" . urlencode("Discount / Coupon");
                $nvpstr .= "&L_PAYMENTREQUEST_0_AMT{$i}=-" . urlencode($discount_value);
                $nvpstr .= "&L_PAYMENTREQUEST_0_NUMBER{$i}={$i}";
                $nvpstr .= "&L_PAYMENTREQUEST_0_QTY{$i}=1";
                $item_total -= $discount_value;
            }
            $item_total = wpsc_paypal_express_format($item_total);
            $shipping_total = wpsc_paypal_express_convert($purchase_log['base_shipping']) + $shipping_total;
            $nvpstr .= '&PAYMENTREQUEST_0_ITEMAMT=' . $item_total;
            $nvpstr .= '&PAYMENTREQUEST_0_SHIPPINGAMT=' . $shipping_total;
            $total = $item_total + $shipping_total;
            if (!wpsc_tax_isincluded()) {
                $tax = wpsc_paypal_express_convert($purchase_log['wpec_taxes_total']);
                $nvpstr .= '&PAYMENTREQUEST_0_TAXAMT=' . $tax;
                $total += $tax;
            }
            // adjust total amount in case we had to round up after converting currency
            if ($total != $paymentAmount) {
                $paymentAmount = $total;
            }
            $nvpstr .= "&PAYMENTREQUEST_0_AMT={$paymentAmount}";
            $resArray = paypal_hash_call("DoExpressCheckoutPayment", $nvpstr);
            /* Display the API response back to the browser.
               If the response from PayPal was a success, display the response parameters'
               If the response was an error, display the errors received using APIError.php. */
            $ack = strtoupper($resArray["ACK"]);
            wpsc_update_customer_meta('paypal_express_reshash', $resArray);
            if ($ack != "SUCCESS") {
                $location = get_option('transact_url') . "&act=error";
            } else {
                $transaction_id = $resArray['PAYMENTINFO_0_TRANSACTIONID'];
                switch ($resArray['PAYMENTINFO_0_PAYMENTSTATUS']) {
                    case 'Processed':
                        // I think this is mostly equivalent to Completed
                    // I think this is mostly equivalent to Completed
                    case 'Completed':
                        wpsc_update_purchase_log_status($sessionid, 3, 'sessionid');
                        transaction_results($sessionid, false);
                        break;
                    case 'Pending':
                        // need to wait for "Completed" before processing
                        wpsc_update_purchase_log_details($sessionid, array('processed' => 2, 'date' => time(), 'transactid' => $transaction_id), 'sessionid');
                        break;
                }
                $location = add_query_arg('sessionid', $sessionid, get_option('transact_url'));
                wpsc_delete_customer_meta('paypal_express_message');
                wp_redirect($location);
                exit;
            }
            wpsc_delete_customer_meta('nzshpcrt_serialized_cart');
            wpsc_delete_customer_meta('nzshpcart');
            $wpsc_cart->empty_cart();
        } else {
            if (isset($_REQUEST['paymentType']) || isset($_REQUEST['token'])) {
                $token = $_REQUEST['token'];
                if (!isset($token)) {
                    $paymentAmount = wpsc_get_customer_meta('paypal_express_converted_amount');
                    $currencyCodeType = wpsc_get_paypal_currency_code();
                    $paymentType = 'Sale';
                    if (get_option('permalink_structure') != '') {
                        $separator = "?";
                    } else {
                        $separator = "&";
                    }
                    $returnURL = urlencode(get_option('transact_url') . $separator . 'currencyCodeType=' . $currencyCodeType . '&paymentType=' . $paymentType . '&paymentAmount=' . $paymentAmount);
                    $cancelURL = urlencode(get_option('transact_url') . $separator . 'paymentType=$paymentType');
                    /* Construct the parameter string that describes the PayPal payment
                    			the varialbes were set in the web form, and the resulting string
                    			is stored in $nvpstr */
                    $nvpstr = "&PAYMENTREQUEST_0_AMT=" . $paymentAmount . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType . "&ReturnUrl=" . $returnURL . "&CANCELURL=" . $cancelURL . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
                    /* Make the call to PayPal to set the Express Checkout token
                    			If the API call succeded, then redirect the buyer to PayPal
                    			to begin to authorize payment.  If an error occured, show the
                    			resulting errors
                    			*/
                    $resArray = paypal_hash_call("SetExpressCheckout", $nvpstr);
                    wpsc_update_customer_meta('paypal_express_reshash', $resArray);
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        // Redirect to paypal.com here
                        $token = urldecode($resArray["TOKEN"]);
                        $payPalURL = $PAYPAL_URL . $token;
                        wp_redirect($payPalURL);
                    } else {
                        // Redirecting to APIError.php to display errors.
                        $location = get_option('transact_url') . "&act=error";
                        wp_redirect($location);
                    }
                    exit;
                } else {
                    /* At this point, the buyer has completed in authorizing payment
                    			at PayPal.  The script will now call PayPal with the details
                    			of the authorization, incuding any shipping information of the
                    			buyer.  Remember, the authorization is not a completed transaction
                    			at this state - the buyer still needs an additional step to finalize
                    			the transaction
                    			*/
                    $token = urlencode($_REQUEST['token']);
                    /* Build a second API request to PayPal, using the token as the
                    			ID to get the details on the payment authorization
                    			*/
                    $nvpstr = "&TOKEN=" . $token;
                    /* Make the API call and store the results in an array.  If the
                    			call was a success, show the authorization details, and provide
                    			an action to complete the payment.  If failed, show the error
                    			*/
                    $resArray = paypal_hash_call("GetExpressCheckoutDetails", $nvpstr);
                    wpsc_update_customer_meta('paypal_express_reshash', $resArray);
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        /********************************************************
                        				GetExpressCheckoutDetails.php
                        
                        				This functionality is called after the buyer returns from
                        				PayPal and has authorized the payment.
                        
                        				Displays the payer details returned by the
                        				GetExpressCheckoutDetails response and calls
                        				DoExpressCheckoutPayment.php to complete the payment
                        				authorization.
                        
                        				Called by ReviewOrder.php.
                        
                        				Calls DoExpressCheckoutPayment.php and APIError.php.
                        
                        				********************************************************/
                        /* Collect the necessary information to complete the
                        			authorization for the PayPal payment
                        			*/
                        /* Display the API response back to the browser .
                        			If the response from PayPal was a success, display the response parameters
                        			*/
                        if (isset($_REQUEST['token']) && !isset($_REQUEST['PayerID'])) {
                            wpsc_update_customer_meta('paypal_express_message', _x('<h4>TRANSACTION CANCELED</h4>', 'paypal express cancel header', 'wpsc'));
                        } else {
                            wpsc_update_customer_meta('paypal_express_token', $_REQUEST['token']);
                            wpsc_update_customer_meta('paypal_express_payer_id', $_REQUEST['PayerID']);
                            $resArray = wpsc_get_customer_meta('paypal_express_reshash');
                            if (get_option('permalink_structure') != '') {
                                $separator = "?";
                            } else {
                                $separator = "&";
                            }
                            if (!isset($resArray['SHIPTOSTREET2'])) {
                                $resArray['SHIPTOSTREET2'] = '';
                            }
                            $output = "\n\t\t\t\t\t   <table width='400' class='paypal_express_form'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'><b>" . __('Order Total:', 'wpsc') . "</b></td>\n\t\t\t\t\t\t\t<td align='left'>" . wpsc_currency_display(wpsc_get_customer_meta('paypal_express_original_amount')) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' colspan='2'><b>" . __('Shipping Address:', 'wpsc') . " </b></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Street 1:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOSTREET'] . "</td>\n\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Street 2:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOSTREET2'] . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('City:', 'wpsc') . "</td>\n\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOCITY'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('State:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOSTATE'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Postal code:', 'wpsc') . "</td>\n\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOZIP'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Country:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOCOUNTRYNAME'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>";
                            $output .= "<form action=" . get_option('transact_url') . " method='post'>\n";
                            $output .= "\t<input type='hidden' name='totalAmount' value='" . wpsc_cart_total(false) . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingStreet' value='" . $resArray['SHIPTOSTREET'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingStreet2' value='" . $resArray['SHIPTOSTREET2'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingCity' value='" . $resArray['SHIPTOCITY'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingState' value='" . $resArray['SHIPTOSTATE'] . "' />\n";
                            $output .= "\t<input type='hidden' name='postalCode' value='" . $resArray['SHIPTOZIP'] . "' />\n";
                            $output .= "\t<input type='hidden' name='country' value='" . $resArray['SHIPTOCOUNTRYNAME'] . "' />\n";
                            $output .= "\t<input type='hidden' name='token' value='" . wpsc_get_customer_meta('paypal_express_token') . "' />\n";
                            $output .= "\t<input type='hidden' name='PayerID' value='" . wpsc_get_customer_meta('paypal_express_payer_id') . "' />\n";
                            $output .= "\t<input type='hidden' name='act' value='do' />\n";
                            $output .= "\t<p>  <input name='usePayPal' type='submit' value='" . __('Confirm Payment', 'wpsc') . "' /></p>\n";
                            $output .= "</form>";
                            $output .= " </td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</center>\n\t\t\t\t\t";
                            wpsc_update_customer_meta('paypal_express_message', $output);
                        }
                    }
                }
            }
        }
    }
}
Example #6
0
/**
 * wpsc_change_tax function, used through ajax and in normal page loading.
 * No parameters, returns nothing
 */
function wpsc_change_tax()
{
    global $wpdb, $wpsc_cart;
    $form_id = absint($_POST['form_id']);
    $wpsc_selected_country = $wpsc_cart->selected_country;
    $wpsc_selected_region = $wpsc_cart->selected_region;
    $wpsc_delivery_country = $wpsc_cart->delivery_country;
    $wpsc_delivery_region = $wpsc_cart->delivery_region;
    $previous_country = $_SESSION['wpsc_selected_country'];
    if (isset($_POST['billing_country'])) {
        $wpsc_selected_country = $wpdb->escape($_POST['billing_country']);
        $_SESSION['wpsc_selected_country'] = $wpsc_selected_country;
    }
    if (isset($_POST['billing_region'])) {
        $wpsc_selected_region = absint($_POST['billing_region']);
        $_SESSION['wpsc_selected_region'] = $wpsc_selected_region;
    }
    $check_country_code = $wpdb->get_var(" SELECT `country`.`isocode` FROM `" . WPSC_TABLE_REGION_TAX . "` AS `region` INNER JOIN `" . WPSC_TABLE_CURRENCY_LIST . "` AS `country` ON `region`.`country_id` = `country`.`id` WHERE `region`.`id` = '" . $_SESSION['wpsc_selected_region'] . "' LIMIT 1");
    if ($_SESSION['wpsc_selected_country'] != $check_country_code) {
        $wpsc_selected_region = null;
    }
    if (isset($_POST['shipping_country'])) {
        $wpsc_delivery_country = $wpdb->escape($_POST['shipping_country']);
        $_SESSION['wpsc_delivery_country'] = $wpsc_delivery_country;
    }
    if (isset($_POST['shipping_region'])) {
        $wpsc_delivery_region = absint($_POST['shipping_region']);
        $_SESSION['wpsc_delivery_region'] = $wpsc_delivery_region;
    }
    $check_country_code = $wpdb->get_var(" SELECT `country`.`isocode` FROM `" . WPSC_TABLE_REGION_TAX . "` AS `region` INNER JOIN `" . WPSC_TABLE_CURRENCY_LIST . "` AS `country` ON `region`.`country_id` = `country`.`id` WHERE `region`.`id` = '" . $wpsc_delivery_region . "' LIMIT 1");
    if ($wpsc_delivery_country != $check_country_code) {
        $wpsc_delivery_region = null;
    }
    $wpsc_cart->update_location();
    $wpsc_cart->get_shipping_method();
    $wpsc_cart->get_shipping_option();
    if ($wpsc_cart->selected_shipping_method != '') {
        $wpsc_cart->update_shipping($wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option);
    }
    $tax = $wpsc_cart->calculate_total_tax();
    $total = wpsc_cart_total();
    $total_input = wpsc_cart_total(false);
    if ($wpsc_cart->coupons_amount >= wpsc_cart_total() && !empty($wpsc_cart->coupons_amount)) {
        $total = 0;
    }
    if ($wpsc_cart->total_price < 0) {
        $wpsc_cart->coupons_amount += $wpsc_cart->total_price;
        $wpsc_cart->total_price = null;
        $wpsc_cart->calculate_total_price();
    }
    ob_start();
    include_once wpsc_get_template_file_path('wpsc-cart_widget.php');
    $output = ob_get_contents();
    ob_end_clean();
    $output = str_replace(array("\n", "\r"), array("\\n", "\\r"), addslashes($output));
    if (get_option('lock_tax') == 1) {
        echo "jQuery('#current_country').val('" . $_SESSION['wpsc_delivery_country'] . "'); \n";
        if ($_SESSION['wpsc_delivery_country'] == 'US' && get_option('lock_tax') == 1) {
            $output = wpsc_shipping_region_list($_SESSION['wpsc_delivery_country'], $_SESSION['wpsc_delivery_region']);
            $output = str_replace(array("\n", "\r"), array("\\n", "\\r"), addslashes($output));
            echo "jQuery('#region').remove();\n\r";
            echo "jQuery('#change_country').append(\"" . $output . "\");\n\r";
        }
    }
    foreach ($wpsc_cart->cart_items as $key => $cart_item) {
        echo "jQuery('#shipping_{$key}').html(\"" . wpsc_currency_display($cart_item->shipping) . "\");\n\r";
    }
    echo "jQuery('#checkout_shipping').html(\"" . wpsc_cart_shipping() . "\");\n\r";
    echo "jQuery('div.shopping-cart-wrapper').html('{$output}');\n";
    if (get_option('lock_tax') == 1) {
        echo "jQuery('.shipping_country').val('" . $_SESSION['wpsc_delivery_country'] . "') \n";
        $sql = "SELECT `country` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `isocode`='" . $_SESSION['wpsc_selected_country'] . "'";
        $country_name = $wpdb->get_var($sql);
        echo "jQuery('.shipping_country_name').html('" . $country_name . "') \n";
    }
    $form_selected_country = null;
    $form_selected_region = null;
    $onchange_function = null;
    if ($_POST['billing_country'] != 'undefined' && !isset($_POST['shipping_country'])) {
        $form_selected_country = $wpsc_selected_country;
        $form_selected_region = $wpsc_selected_region;
        $onchange_function = 'set_billing_country';
    } else {
        if ($_POST['shipping_country'] != 'undefined' && !isset($_POST['billing_country'])) {
            $form_selected_country = $wpsc_delivery_country;
            $form_selected_region = $wpsc_delivery_region;
            $onchange_function = 'set_shipping_country';
        }
    }
    if ($form_selected_country != null && $onchange_function != null) {
        $region_list = $wpdb->get_results("SELECT `" . WPSC_TABLE_REGION_TAX . "`.* FROM `" . WPSC_TABLE_REGION_TAX . "`, `" . WPSC_TABLE_CURRENCY_LIST . "`  WHERE `" . WPSC_TABLE_CURRENCY_LIST . "`.`isocode` IN('" . $form_selected_country . "') AND `" . WPSC_TABLE_CURRENCY_LIST . "`.`id` = `" . WPSC_TABLE_REGION_TAX . "`.`country_id`", ARRAY_A);
        if ($region_list != null) {
            $title = empty($_POST['billing_country']) ? 'shippingstate' : 'billingstate';
            $output = "<select name='collected_data[" . $form_id . "][1]' class='current_region' onchange='{$onchange_function}(\"region_country_form_{$form_id}\", \"{$form_id}\");' title='" . $title . "'>\n\r";
            foreach ($region_list as $region) {
                if ($form_selected_region == $region['id']) {
                    $selected = "selected='selected'";
                } else {
                    $selected = "";
                }
                $output .= "   <option value='" . $region['id'] . "' {$selected}>" . htmlspecialchars($region['name']) . "</option>\n\r";
            }
            $output .= "</select>\n\r";
            $output = str_replace(array("\n", "\r"), array("\\n", "\\r"), addslashes($output));
            echo "jQuery('#region_select_{$form_id}').html(\"" . $output . "\");\n\r";
            echo "\n\t\t\t\tvar wpsc_checkout_table_selector = jQuery('#region_select_{$form_id}').parents('.wpsc_checkout_table').attr('class');\n\t\t\t\twpsc_checkout_table_selector = wpsc_checkout_table_selector.replace(' ','.');\n\t\t\t\twpsc_checkout_table_selector = '.'+wpsc_checkout_table_selector;\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' input.billing_region').attr('disabled', 'disabled');\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' input.shipping_region').attr('disabled', 'disabled');\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' .billing_region').parent().parent().hide();\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' .shipping_region').parent().parent().hide();\n\t\t\t";
        } else {
            if (get_option('lock_tax') == 1) {
                echo "jQuery('#region').hide();";
            }
            echo "jQuery('#region_select_{$form_id}').html('');\n\r";
            echo "\n\t\t\t\tvar wpsc_checkout_table_selector = jQuery('#region_select_{$form_id}').parents('.wpsc_checkout_table').attr('class');\n\t\t\t\twpsc_checkout_table_selector = wpsc_checkout_table_selector.replace(' ','.');\n\t\t\t\twpsc_checkout_table_selector = '.'+wpsc_checkout_table_selector;\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' input.billing_region').removeAttr('disabled');\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' input.shipping_region').removeAttr('disabled');\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' .billing_region').parent().parent().show();\n\t\t\t\tjQuery(wpsc_checkout_table_selector + ' .shipping_region').parent().parent().show();\n\t\t\t";
        }
    }
    if ($tax > 0) {
        echo "jQuery(\"tr.total_tax\").show();\n\r";
    } else {
        echo "jQuery(\"tr.total_tax\").hide();\n\r";
    }
    echo "jQuery('#checkout_tax').html(\"<span class='pricedisplay'>" . wpsc_cart_tax() . "</span>\");\n\r";
    echo "jQuery('#checkout_total').html(\"{$total}<input id='shopping_cart_total_price' type='hidden' value='{$total_input}' />\");\n\r";
    echo "if(jQuery(\"#shippingSameBilling\").is(\":checked\")) wpsc_shipping_same_as_billing();";
    exit;
}
/**
 * Checks if the current cart is a "Free Cart", which means one of the following:
 *
 *  - Either the all of the cart items are priced at 0.
 *  - Or a coupon has been applied that results in a free cart.
 *
 * This is a helpful function for doing things like allowing free carts to be purchased, bypassing payment gateways.
 *
 * @since  3.9.0
 * @return bool Whether or not the current cart's total cost is free or not.
 */
function wpsc_is_free_cart()
{
    return apply_filters('wpsc_is_free_cart', wpsc_cart_item_count() && !floatval(wpsc_cart_total(false)));
}
Example #8
0
/**
 * wpsc_change_tax function, used through ajax and in normal page loading.
 * No parameters, returns nothing
 */
function wpsc_change_tax()
{
    global $wpdb, $wpsc_cart;
    $form_id = absint($_POST['form_id']);
    $wpsc_selected_country = $wpsc_cart->selected_country;
    $wpsc_selected_region = $wpsc_cart->selected_region;
    $wpsc_delivery_country = $wpsc_cart->delivery_country;
    $wpsc_delivery_region = $wpsc_cart->delivery_region;
    $previous_country = wpsc_get_customer_meta('billingcountry');
    global $wpdb, $user_ID, $wpsc_customer_checkout_details;
    if (isset($_POST['billing_country'])) {
        $wpsc_selected_country = $_POST['billing_country'];
        wpsc_update_customer_meta('billingcountry', $wpsc_selected_country);
    }
    if (isset($_POST['billing_region'])) {
        $wpsc_selected_region = absint($_POST['billing_region']);
        wpsc_update_customer_meta('billingregion', $wpsc_selected_region);
    }
    $check_country_code = WPSC_Countries::country_id(wpsc_get_customer_meta('billing_region'));
    if (wpsc_get_customer_meta('billingcountry') != $check_country_code) {
        $wpsc_selected_region = null;
    }
    if (isset($_POST['shipping_country'])) {
        $wpsc_delivery_country = $_POST['shipping_country'];
        wpsc_update_customer_meta('shippingcountry', $wpsc_delivery_country);
    }
    if (isset($_POST['shipping_region'])) {
        $wpsc_delivery_region = absint($_POST['shipping_region']);
        wpsc_update_customer_meta('shippingregion', $wpsc_delivery_region);
    }
    $check_country_code = WPSC_Countries::country_id($wpsc_delivery_region);
    if ($wpsc_delivery_country != $check_country_code) {
        $wpsc_delivery_region = null;
    }
    $wpsc_cart->update_location();
    $wpsc_cart->get_shipping_method();
    $wpsc_cart->get_shipping_option();
    if ($wpsc_cart->selected_shipping_method != '') {
        $wpsc_cart->update_shipping($wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option);
    }
    $tax = $wpsc_cart->calculate_total_tax();
    $total = wpsc_cart_total();
    $total_input = wpsc_cart_total(false);
    if ($wpsc_cart->coupons_amount >= $total_input && !empty($wpsc_cart->coupons_amount)) {
        $total = 0;
    }
    if ($wpsc_cart->total_price < 0) {
        $wpsc_cart->coupons_amount += $wpsc_cart->total_price;
        $wpsc_cart->total_price = null;
        $wpsc_cart->calculate_total_price();
    }
    $delivery_country = wpsc_get_customer_meta('shipping_country');
    $output = _wpsc_ajax_get_cart(false);
    $output = $output['widget_output'];
    $json_response = array();
    global $wpsc_checkout;
    if (empty($wpsc_checkout)) {
        $wpsc_checkout = new wpsc_checkout();
    }
    $json_response['delivery_country'] = esc_js($delivery_country);
    $json_response['billing_country'] = esc_js($wpsc_selected_country);
    $json_response['widget_output'] = $output;
    $json_response['shipping_keys'] = array();
    $json_response['cart_shipping'] = wpsc_cart_shipping();
    $json_response['form_id'] = $form_id;
    $json_response['tax'] = $tax;
    $json_response['display_tax'] = wpsc_cart_tax();
    $json_response['total'] = $total;
    $json_response['total_input'] = $total_input;
    $json_response['lock_tax'] = get_option('lock_tax');
    $json_response['country_name'] = wpsc_get_country($delivery_country);
    if ('US' == $delivery_country || 'CA' == $delivery_country) {
        $output = wpsc_shipping_region_list($delivery_country, wpsc_get_customer_meta('shipping_region'));
        $output = str_replace(array("\n", "\r"), '', $output);
        $json_response['shipping_region_list'] = $output;
    }
    foreach ($wpsc_cart->cart_items as $key => $cart_item) {
        $json_response['shipping_keys'][$key] = wpsc_currency_display($cart_item->shipping);
    }
    $form_selected_country = null;
    $form_selected_region = null;
    $onchange_function = null;
    if (!empty($_POST['billing_country']) && $_POST['billing_country'] != 'undefined' && !isset($_POST['shipping_country'])) {
        $form_selected_country = $wpsc_selected_country;
        $form_selected_region = $wpsc_selected_region;
        $onchange_function = 'set_billing_country';
    } else {
        if (!empty($_POST['shipping_country']) && $_POST['shipping_country'] != 'undefined' && !isset($_POST['billing_country'])) {
            $form_selected_country = $wpsc_delivery_country;
            $form_selected_region = $wpsc_delivery_region;
            $onchange_function = 'set_shipping_country';
        }
    }
    if ($form_selected_country != null && $onchange_function != null) {
        $checkoutfields = 'set_shipping_country' == $onchange_function;
        $region_list = wpsc_country_region_list($form_id, false, $form_selected_country, $form_selected_region, $form_id, $checkoutfields);
        if ($region_list != null) {
            $json_response['region_list'] = str_replace(array("\n", "\r"), '', $region_list);
        }
    }
    echo json_encode($json_response);
    exit;
}
 /**
  * validate_forms method, validates the input from the checkout page
  * @access public
  */
 function validate_forms()
 {
     global $wpdb, $current_user, $user_ID;
     $any_bad_inputs = false;
     // Credit Card Number Validation for Paypal Pro and maybe others soon
     if (wpsc_cart_total(false) != 0) {
         if (isset($_POST['card_number'])) {
             if ($_POST['card_number'] != '') {
                 /*
                 
                    			$ccregex='/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/';
                    			if(!preg_match($ccregex, $_POST['card_number'])){
                    				$any_bad_inputs = true;
                 				$bad_input = true;
                 				$_SESSION['wpsc_gateway_error_messages']['card_number'] = __('Please enter a valid', 'wpsc') . " " . strtolower('card number') . ".";
                 				$_SESSION['wpsc_checkout_saved_values']['card_number'] = '';
                    			}else{
                    				$_SESSION['wpsc_gateway_error_messages']['card_number'] = '';
                    			}   		
                 */
             } else {
                 $any_bad_inputs = true;
                 $bad_input = true;
                 $_SESSION['wpsc_gateway_error_messages']['card_number'] = __('Please enter a valid', 'wpsc') . " " . strtolower('card number') . ".";
                 $_SESSION['wpsc_checkout_saved_values']['card_number'] = '';
             }
         } else {
             $_SESSION['wpsc_gateway_error_messages']['card_number'] = '';
         }
         if (isset($_POST['card_number1']) && isset($_POST['card_number2']) && isset($_POST['card_number3']) && isset($_POST['card_number4'])) {
             if ($_POST['card_number1'] != '' && $_POST['card_number2'] != '' && $_POST['card_number3'] != '' && $_POST['card_number4'] != '' && is_numeric($_POST['card_number1']) && is_numeric($_POST['card_number2']) && is_numeric($_POST['card_number3']) && is_numeric($_POST['card_number4'])) {
                 $_SESSION['wpsc_gateway_error_messages']['card_number'] = '';
             } else {
                 $any_bad_inputs = true;
                 $bad_input = true;
                 $_SESSION['wpsc_gateway_error_messages']['card_number'] = __('Please enter a valid', 'wpsc') . " " . strtolower('card number') . ".";
                 $_SESSION['wpsc_checkout_saved_values']['card_number'] = '';
             }
         }
         if (isset($_POST['expiry'])) {
             if ($_POST['expiry']['month'] != '' && $_POST['expiry']['month'] != '' && is_numeric($_POST['expiry']['month']) && is_numeric($_POST['expiry']['year'])) {
                 $_SESSION['wpsc_gateway_error_messages']['expdate'] = '';
             } else {
                 $any_bad_inputs = true;
                 $bad_input = true;
                 $_SESSION['wpsc_gateway_error_messages']['expdate'] = __('Please enter a valid', 'wpsc') . " " . strtolower('Expiry Date') . ".";
                 $_SESSION['wpsc_checkout_saved_values']['expdate'] = '';
             }
         }
         if (isset($_POST['card_code'])) {
             if ($_POST['card_code'] == '' || !is_numeric($_POST['card_code'])) {
                 $any_bad_inputs = true;
                 $bad_input = true;
                 $_SESSION['wpsc_gateway_error_messages']['card_code'] = __('Please enter a valid', 'wpsc') . " " . strtolower('CVV') . ".";
                 $_SESSION['wpsc_checkout_saved_values']['card_code'] = '';
             } else {
                 $_SESSION['wpsc_gateway_error_messages']['card_code'] = '';
             }
         }
         if (isset($_POST['cctype'])) {
             if ($_POST['cctype'] == '') {
                 $any_bad_inputs = true;
                 $bad_input = true;
                 $_SESSION['wpsc_gateway_error_messages']['cctype'] = __('Please enter a valid', 'wpsc') . " " . strtolower('CVV') . ".";
                 $_SESSION['wpsc_checkout_saved_values']['cctype'] = '';
             } else {
                 $_SESSION['wpsc_gateway_error_messages']['cctype'] = '';
             }
         }
     }
     //closes main bracket
     if (isset($_POST['log']) || isset($_POST['pwd']) || isset($_POST['user_email'])) {
         $results = wpsc_add_new_user($_POST['log'], $_POST['pwd'], $_POST['user_email']);
         $_SESSION['wpsc_checkout_user_error_messages'] = array();
         if (is_callable(array($results, "get_error_code")) && $results->get_error_code()) {
             foreach ($results->get_error_codes() as $code) {
                 foreach ($results->get_error_messages($code) as $error) {
                     $_SESSION['wpsc_checkout_user_error_messages'][] = $error;
                 }
                 $any_bad_inputs = true;
             }
         }
         //exit('<pre>'.print_r($results, true).'</pre>');
         if ($results->ID > 0) {
             $our_user_id = $results->ID;
         } else {
             $any_bad_inputs = true;
         }
     }
     if ($our_user_id < 1) {
         $our_user_id = $user_ID;
     }
     // check we have a user id
     if ($our_user_id > 0) {
         $user_ID = $our_user_id;
     }
     //exit('<pre>'.print_r($_POST['collected_data'],true).'</pre>');
     //Basic Form field validation for billing and shipping details
     foreach ($this->checkout_items as $form_data) {
         $value = $_POST['collected_data'][$form_data->id];
         $value_id = (int) $value_id;
         $_SESSION['wpsc_checkout_saved_values'][$form_data->id] = $value;
         $bad_input = false;
         if ($form_data->mandatory == 1 || $form_data->type == "coupon") {
             switch ($form_data->type) {
                 case "email":
                     if (!preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-.]+\\.[a-zA-Z]{2,5}\$/", $value)) {
                         $any_bad_inputs = true;
                         $bad_input = true;
                     }
                     break;
                 case "delivery_country":
                 case "country":
                 case "heading":
                     break;
                 case "select":
                 case 'checkbox':
                     if (is_array($value)) {
                         $select_bad_input = 0;
                         foreach ($value as $v) {
                             if ($v == '-1') {
                                 $select_bad_input++;
                             } else {
                                 $valid_select_input++;
                             }
                         }
                         if (count($value) == $select_bad_input) {
                             $any_bad_inputs = true;
                             $bad_input = true;
                         }
                     } else {
                         if ($value == '-1') {
                             $any_bad_inputs = true;
                             $bad_input = true;
                         }
                     }
                     break;
                 default:
                     if (is_array($value)) {
                         $select_bad_input = 0;
                         foreach ($value as $v) {
                             if ($v == '') {
                                 $select_bad_input++;
                             } else {
                                 $valid_select_input++;
                             }
                         }
                         if (count($value) == $select_bad_input) {
                             $any_bad_inputs = true;
                             $bad_input = true;
                         }
                     } else {
                         if ($value == '') {
                             $any_bad_inputs = true;
                             $bad_input = true;
                         }
                     }
                     break;
             }
             if ($bad_input === true) {
                 $_SESSION['wpsc_checkout_error_messages'][$form_data->id] = __('Please enter a valid', 'wpsc') . " " . strtolower($form_data->name) . ".";
                 $_SESSION['wpsc_checkout_saved_values'][$form_data->id] = '';
             }
         }
     }
     //exit('UserID >><pre>'.print_r($user_ID, true).'</pre>');
     if ($any_bad_inputs == false && $user_ID > 0) {
         $saved_data_sql = "SELECT * FROM `" . $wpdb->usermeta . "` WHERE `user_id` = '" . $user_ID . "' AND `meta_key` = 'wpshpcrt_usr_profile';";
         $saved_data = $wpdb->get_row($saved_data_sql, ARRAY_A);
         //echo "<pre>".print_r($meta_data,true)."</pre>";
         $new_meta_data = serialize($_POST['collected_data']);
         if ($saved_data != null) {
             $sql = "UPDATE `" . $wpdb->usermeta . "` SET `meta_value` =  '{$new_meta_data}' WHERE `user_id` IN ('{$user_ID}') AND `meta_key` IN ('wpshpcrt_usr_profile');";
             $wpdb->query($sql);
             $changes_saved = true;
             //exit($sql);
         } else {
             $sql = "INSERT INTO `" . $wpdb->usermeta . "` ( `user_id` , `meta_key` , `meta_value` ) VALUES ( " . $user_ID . ", 'wpshpcrt_usr_profile', '{$new_meta_data}');";
             $wpdb->query($sql);
             $changes_saved = true;
             //exit($sql);
         }
     }
     return array('is_valid' => !$any_bad_inputs, 'error_messages' => $bad_input_message);
 }
Example #10
0
 /**
  * Comparing logic with the product information
  *
  * Checks if the product matchs the logic
  *
  * @return bool True if all conditions are matched, False otherwise.
  */
 function compare_logic($c, $product_obj)
 {
     global $wpdb;
     if ($c['property'] == 'item_name') {
         $product_data = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_PRODUCT_LIST . " WHERE id='{$product_obj->product_id}'");
         $product_data = $product_data[0];
         switch ($c['logic']) {
             case 'equal':
                 //Checks if the product name is exactly the same as the condition value
                 if ($product_data->name == $c['value']) {
                     return true;
                 }
                 break;
             case 'greater':
                 //Checks if the product name is not the same as the condition value
                 if ($product_data->name > $c['value']) {
                     return true;
                 }
                 break;
             case 'less':
                 //Checks if the product name is not the same as the condition value
                 if ($product_data->name < $c['value']) {
                     return true;
                 }
                 break;
             case 'contains':
                 //Checks if the product name contains the condition value
                 preg_match("/(.*)" . $c['value'] . "(.*)/", $product_data->name, $match);
                 if (!empty($match)) {
                     return true;
                 }
                 break;
             case 'not_contain':
                 //Checks if the product name contains the condition value
                 preg_match("/(.*)" . $c['value'] . "(.*)/", $product_data->name, $match);
                 if (empty($match)) {
                     return true;
                 }
                 break;
             case 'begins':
                 //Checks if the product name begins with condition value
                 preg_match("/^" . $c['value'] . "/", $product_data->name, $match);
                 if (!empty($match)) {
                     return true;
                 }
                 break;
             case 'ends':
                 //Checks if the product name ends with condition value
                 preg_match("/" . $c['value'] . "\$/", $product_data->name, $match);
                 if (!empty($match)) {
                     return true;
                 }
                 break;
             default:
                 return false;
         }
     } else {
         if ($c['property'] == 'item_quantity') {
             switch ($c['logic']) {
                 case 'equal':
                     //Checks if the quantity of a product in the cart equals condition value
                     exit($product_obj->quantity . 'and' . $c['value']);
                     if ($product_obj->quantity == (int) $c['value']) {
                         return true;
                     }
                     break;
                 case 'greater':
                     //Checks if the quantity of a product is greater than the condition value
                     if ($product_obj->quantity > $c['value']) {
                         return true;
                     }
                     break;
                 case 'less':
                     //Checks if the quantity of a product is less than the condition value
                     if ($product_obj->quantity < $c['value']) {
                         return true;
                     }
                     break;
                 case 'contains':
                     //Checks if the product name contains the condition value
                     preg_match("/(.*)" . $c['value'] . "(.*)/", $product_obj->quantity, $match);
                     if (!empty($match)) {
                         return true;
                     }
                     break;
                 case 'not_contain':
                     //Checks if the product name contains the condition value
                     preg_match("/(.*)" . $c['value'] . "(.*)/", $product_obj->quantity, $match);
                     if (empty($match)) {
                         return true;
                     }
                     break;
                 case 'begins':
                     //Checks if the product name begins with condition value
                     preg_match("/^" . $c['value'] . "/", $product_obj->quantity, $match);
                     if (!empty($match)) {
                         return true;
                     }
                     break;
                 case 'ends':
                     //Checks if the product name ends with condition value
                     preg_match("/" . $c['value'] . "\$/", $product_obj->quantity, $match);
                     if (!empty($match)) {
                         return true;
                     }
                     break;
                 default:
                     return false;
             }
         } else {
             if ($c['property'] == 'total_quantity') {
                 //			exit('<pre>'.print_r($product_obj, true).'</pre>');
                 $total_quantity = $product_obj->quantity;
                 switch ($c['logic']) {
                     case 'equal':
                         //Checks if the quantity of products in the cart equals condition value
                         if ($total_quantity == $c['value']) {
                             return true;
                         }
                         break;
                     case 'greater':
                         //Checks if the quantity in the cart is greater than the condition value
                         if ($total_quantity > $c['value']) {
                             return true;
                         }
                         break;
                     case 'less':
                         //Checks if the quantity in the cart is less than the condition value
                         if ($total_quantity < $c['value']) {
                             return true;
                         }
                         break;
                     default:
                         return false;
                 }
             } else {
                 if ($c['property'] == 'subtotal_amount') {
                     $subtotal = wpsc_cart_total(false);
                     //exit('<pre>'.print_r($subtotal,true).'</pre>');
                     switch ($c['logic']) {
                         case 'equal':
                             //Checks if the subtotal of products in the cart equals condition value
                             if ($subtotal == $c['value']) {
                                 return true;
                             }
                             break;
                         case 'greater':
                             //Checks if the subtotal of the cart is greater than the condition value
                             //	exit('triggered here'.$subtotal.'>'.$c['value']);
                             if ($subtotal > $c['value']) {
                                 return true;
                             }
                             break;
                         case 'less':
                             //Checks if the subtotal of the cart is less than the condition value
                             if ($subtotal < $c['value']) {
                                 //exit('<pre>'.print_r($product_obj->cart->subtotal, true).'</pre>cValue'.$c['value']);
                                 return true;
                             } else {
                                 return false;
                             }
                             break;
                         default:
                             return false;
                     }
                 }
             }
         }
     }
 }
Example #11
0
function gateway_paypal_payflow($seperator, $sessionid)
{
    global $wpdb, $wpsc_cart;
    $purchase_log_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1";
    $purchase_log = $wpdb->get_results($purchase_log_sql, ARRAY_A);
    $fraud = 'NO';
    $env = get_option('paypal_payflow_test') ? 'Test' : 'Live';
    $user = get_option('paypal_payflow_user');
    $password = get_option('paypal_payflow_pass');
    $partner = get_option('paypal_payflow_partner');
    $vendor = get_option('paypal_payflow_vendor');
    $currency = get_option('paypal_payflow_curcode');
    if ($env == 'Live') {
        $submiturl = 'https://payflowpro.paypal.com';
        $PayPalURL = 'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=';
    } else {
        $submiturl = 'https://pilot-payflowpro.paypal.com';
        $PayPalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=';
    }
    $cart_sql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`='" . $purchase_log[0]['id'] . "'";
    $cart = $wpdb->get_results($cart_sql, ARRAY_A);
    $member_subtype = get_product_meta($cart[0]['prodid'], 'is_permenant', true);
    $member_shiptype = get_product_meta($cart[0]['prodid'], 'membership_length', true);
    $member_shiptype = $member_shiptype[0];
    $status = get_product_meta($cart[0]['prodid'], 'is_membership', true);
    $is_member = $status;
    $is_perm = $member_subtype;
    $length = $member_shiptype['length'];
    $custom = $purchase_log[0]['id'];
    if ($_POST['collected_data'][get_option('paypal_form_first_name')] != '') {
        $data['first_name'] = urlencode($_POST['collected_data'][get_option('paypal_form_first_name')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_last_name')] != '') {
        $data['last_name'] = urlencode($_POST['collected_data'][get_option('paypal_form_last_name')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_address')] != '') {
        $address_rows = explode("\n\r", $_POST['collected_data'][get_option('paypal_form_address')]);
        $data['address1'] = urlencode(str_replace(array("\n", "\r"), '', $address_rows[0]));
        unset($address_rows[0]);
        if ($address_rows != null) {
            $data['address2'] = implode(", ", $address_rows);
        } else {
            $data['address2'] = '';
        }
    }
    if ($_POST['collected_data'][get_option('paypal_form_city')] != '') {
        $data['city'] = urlencode($_POST['collected_data'][get_option('paypal_form_city')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_state')] != '') {
        $data['state'] = $wpdb->get_var("SELECT code FROM `" . WPSC_TABLE_REGION_TAX . "` WHERE id='" . wpsc_get_customer_meta('billing_region') . "'");
    }
    $customer_billing_country = wpsc_get_customer_meta('billing_country');
    if (preg_match("/^[a-zA-Z]{2}\$/", $customer_billing_country)) {
        $data['country'] = $customer_billing_country;
    }
    if (is_numeric($_POST['collected_data'][get_option('paypal_form_post_code')])) {
        $data['zip'] = urlencode($_POST['collected_data'][get_option('paypal_form_post_code')]);
    }
    $email_data = $wpdb->get_results("SELECT `id`,`type` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `type` IN ('email') AND `active` = '1'", ARRAY_A);
    foreach ((array) $email_data as $email) {
        $data['email'] = $_POST['collected_data'][$email['id']];
    }
    if ($_POST['collected_data'][get_option('email_form_field')] != null && $data['email'] == null) {
        $data['email'] = $_POST['collected_data'][get_option('email_form_field')];
    }
    $card_num = $_POST['card_number'];
    $cvv2 = $_POST['card_cvv'];
    $expiry = $_POST['expiry']['month'] . $_POST['expiry']['year'];
    $unique_id = generateGUID();
    $fname = $data['first_name'];
    $lname = $data['last_name'];
    $addr1 = $data['address1'] . $data['address2'];
    $addr2 = $data['city'];
    $addr3 = $data['state'];
    $addr4 = $data['zip'];
    $country = $data['country'];
    $email = $data['email'];
    $amount = wpsc_cart_total(false);
    $amount = number_format($amount, 2, '.', '');
    if ($is_member[0]) {
        switch ($member_shiptype['unit']) {
            case 'w':
                $member_ship_unit = 'WEEK';
                break;
            case 'm':
                $member_ship_unit = 'MONT';
                break;
            case 'y':
                $member_ship_unit = 'YEAR';
                break;
        }
        $paypal_query_array = array('USER' => $user, 'PROFILENAME' => $fname . $lname . $purchase_log[0]['id'], 'VENDOR' => $vendor, 'PARTNER' => $partner, 'PWD' => $password, 'TENDER' => 'C', 'TRXTYPE' => 'R', 'ACTION' => 'A', 'START' => date('m') . (date('d') + 1) . date('Y'), 'ACCT' => $card_num, 'CVV2' => $cvv2, 'EXPDATE' => $expiry, 'ACCTTYPE' => $card, 'AMT' => $amount, 'CURRENCY' => $currency, 'FIRSTNAME' => $fname, 'LASTNAME' => $lname, 'STREET' => $addr1, 'CITY' => $addr2, 'STATE' => $addr3, 'ZIP' => $addr4, 'COUNTRY' => $country, 'EMAIL' => $email, 'OPTIONALTRX' => 'A', 'OPTIONALTRXAMT' => '0.00', 'CLIENTIP' => $cust_ip, 'COMMENT1' => $custom, 'ORDERDESC' => $fname . $lname . $purchase_log[0]['id'], 'PAYPERIOD' => $member_ship_unit);
        foreach ($paypal_query_array as $key => $value) {
            if ($key == 'USER') {
                $paypal_query .= $key . '[' . strlen($value) . ']=' . $value;
            } else {
                $paypal_query .= '&' . $key . '[' . strlen($value) . ']=' . $value;
            }
        }
        $response = fetch_data($unique_id, $submiturl, $paypal_query);
        response_handler($response, 'NO', $sessionid, $colected_data, 1);
    }
    if (get_option('paypal_payflow_method') == '0') {
        $tender = 'P';
    } else {
        $tender = 'C';
    }
    $fname = $data['first_name'];
    $lname = $data['last_name'];
    $addr1 = $data['address1'] . $data['address2'];
    $addr2 = $data['city'];
    $addr3 = $data['state'];
    $addr4 = $data['zip'];
    $country = $data['country'];
    $email = $data['email'];
    $paypal_query_array = array('USER' => $user, 'VENDOR' => $vendor, 'PARTNER' => $partner, 'PWD' => $password, 'TENDER' => $tender, 'TRXTYPE' => 'S', 'ACCT' => $card_num, 'CVV2' => $cvv2, 'EXPDATE' => $expiry, 'ACCTTYPE' => $card, 'AMT' => $amount, 'CURRENCY' => $currency, 'FIRSTNAME' => $fname, 'LASTNAME' => $lname, 'STREET' => $addr1, 'CITY' => $addr2, 'STATE' => $addr3, 'ZIP' => $addr4, 'COUNTRY' => $country, 'EMAIL' => $email, 'CLIENTIP' => $cust_ip, 'COMMENT1' => $custom, 'COMMENT2' => '', 'INVNUM' => $order_num, 'ORDERDESC' => $desc, 'VERBOSITY' => 'MEDIUM', 'CARDSTART' => $card_start, 'CARDISSUE' => $card_issue);
    foreach ($paypal_query_array as $key => $value) {
        if ($key == 'USER') {
            $paypal_query .= $key . '[' . strlen($value) . ']=' . $value;
        } else {
            $paypal_query .= '&' . $key . '[' . strlen($value) . ']=' . $value;
        }
    }
    //exit("<pre>".print_r($paypal_query_array,true)."</pre>");
    $response = fetch_data($unique_id, $submiturl, $paypal_query);
    response_handler($response, 'NO', $sessionid, $colected_data);
    exit;
}
Example #12
0
function processingfunctions()
{
    global $wpdb, $wpsc_cart;
    $sessionid = $_SESSION['paypalexpresssessionid'];
    if ($_REQUEST['act'] == 'error') {
        session_start();
        $resArray = $_SESSION['reshash'];
        $_SESSION['paypalExpressMessage'] = '
	<center>
	
	<table width="700" align="left">
	<tr>
			<td colspan="2" class="header">The PayPal API has returned an error!</td>
		</tr>
	';
        //it will print if any URL errors
        if (isset($_SESSION['curl_error_no'])) {
            $errorCode = $_SESSION['curl_error_no'];
            $errorMessage = $_SESSION['curl_error_msg'];
            $response = $_SESSION['response'];
            session_unset();
            $_SESSION['paypalExpressMessage'] .= '
	<tr>
			<td>response:</td>
			<td><?php echo $response; ?></td>
		</tr>
	   
	<tr>
			<td>Error Number:</td>
			<td><?= $errorCode ?></td>
		</tr>
		<tr>
			<td>Error Message:</td>
			<td><?= $errorMessage ?></td>
		</tr>
		
		</center>
		</table>';
        } else {
            /* If there is no URL Errors, Construct the HTML page with 
               Response Error parameters.   
               */
            $_SESSION['paypalExpressMessage'] .= "\n\t\n\t\t\t<td>Ack:</td>\n\t\t\t<td>" . $resArray['ACK'] . "</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>Correlation ID:</td>\n\t\t\t<td>" . $resArray['CORRELATIONID'] . "</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>Version:</td>\n\t\t\t<td>" . $resArray['VERSION'] . "</td>\n\t\t</tr>";
            $count = 0;
            while (isset($resArray["L_SHORTMESSAGE" . $count])) {
                $errorCode = $resArray["L_ERRORCODE" . $count];
                $shortMessage = $resArray["L_SHORTMESSAGE" . $count];
                $longMessage = $resArray["L_LONGMESSAGE" . $count];
                $count = $count + 1;
                $_SESSION['paypalExpressMessage'] .= "\n\t\t<tr>\n\t\t\t<td>Error Number:</td>\n\t\t\t<td> {$errorCode} </td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>Short Message:</td>\n\t\t\t<td> {$shortMessage} </td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>Long Message:</td>\n\t\t\t<td> {$longMessage} </td>\n\t\t</tr>";
            }
            //end while
        }
        // end else
        $_SESSION['paypalExpressMessage'] .= "\n\t</center>\n\t\t</table>";
    } else {
        if ($_REQUEST['act'] == 'do') {
            session_start();
            /* Gather the information to make the final call to
               finalize the PayPal payment.  The variable nvpstr
               holds the name value pairs
               */
            //exit(wpsc_cart_total(false));
            $token = urlencode($_REQUEST['token']);
            $paymentAmount = urlencode($_SESSION['paypalAmount']);
            $paymentType = urlencode($_SESSION['paymentType']);
            $currCodeType = urlencode(get_option('paypal_curcode'));
            $payerID = urlencode($_REQUEST['PayerID']);
            $serverName = urlencode($_SERVER['SERVER_NAME']);
            $BN = 'Instinct_e-commerce_wp-shopping-cart_NZ';
            $nvpstr = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTACTION=Sale&AMT=' . $paymentAmount . '&CURRENCYCODE=' . $currCodeType . '&IPADDRESS=' . $serverName . "&BUTTONSOURCE=" . $BN;
            //	exit($nvpstr);
            /* Make the call to PayPal to finalize payment
            		If an error occured, show the resulting errors
            		*/
            $resArray = hash_call("DoExpressCheckoutPayment", $nvpstr);
            /* Display the API response back to the browser.
               If the response from PayPal was a success, display the response parameters'
               If the response was an error, display the errors received using APIError.php.
               */
            $ack = strtoupper($resArray["ACK"]);
            //exit('<pre>'.print_r($_POST, true).'</pre>');
            if ($ack != "SUCCESS") {
                $_SESSION['reshash'] = $resArray;
                $location = get_option('transact_url') . "&act=error";
                // header("Location: $location");
            } else {
                if (isset($_POST['usePayPal'])) {
                    $street = $_POST['shippingStreet'] . ' ' . $_POST['shippingStreet2'];
                    //form_id 12
                    $city = $_POST['shippingCity'];
                    //form_id 13
                    $state = $_POST['shippingState'];
                    // form_id 14
                    $country = $_POST['country'];
                    //form_id 15
                    $postalCode = $_POST['postalCode'];
                    //form_id 16
                    $log_id = $wpdb->get_var("SELECT `id` FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` IN('" . $sessionid . "') LIMIT 1");
                    $sql = "UPDATE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` LEFT JOIN `" . WPSC_TABLE_CHECKOUT_FORMS . "` ON `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` = `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`id` SET `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`value` ='" . $street . "' WHERE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id` = '" . $log_id . "' AND `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name`='shippingaddress'";
                    $wpdb->query($sql);
                    $sql = "UPDATE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` LEFT JOIN `" . WPSC_TABLE_CHECKOUT_FORMS . "` ON `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` = `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`id` SET `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`value` ='" . $city . "' WHERE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id` = '" . $log_id . "' AND `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name`='shippingcity'";
                    $wpdb->query($sql);
                    $sql = "UPDATE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` LEFT JOIN `" . WPSC_TABLE_CHECKOUT_FORMS . "` ON `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` = `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`id` SET `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`value` ='" . $state . "' WHERE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id` = '" . $log_id . "' AND `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name`='shippingstate'";
                    $wpdb->query($sql);
                    $sql = "UPDATE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` LEFT JOIN `" . WPSC_TABLE_CHECKOUT_FORMS . "` ON `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` = `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`id` SET `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`value` ='" . $country . "' WHERE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id` = '" . $log_id . "' AND `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name`='shippingcountry'";
                    $wpdb->query($sql);
                    $sql = "UPDATE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` LEFT JOIN `" . WPSC_TABLE_CHECKOUT_FORMS . "` ON `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` = `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`id` SET `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`value` ='" . $postalCode . "' WHERE `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id` = '" . $log_id . "' AND `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name`='shippingpostcode'";
                    $wpdb->query($sql);
                }
            }
            //exit('<pre>'.print_r($resArray, true).'</pre>');
            $_SESSION['paypalExpressMessage'] = "\n\t\t<h4>Transaction Accepted Please Keep these References Handy.</h4>\n\t\t<table width ='400'>\n\t\t\t\n\t\t\t<tr>\n\t\t\t\t<td >\n\t\t\t\t\tTransaction ID:</td>\n\t\t\t\t<td>" . $resArray['TRANSACTIONID'] . "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td >\n\t\t\t\t\tAmount:</td>\n\t\t\t\t<td>" . $currCodeType . " " . $resArray['AMT'] . "</td>\n\t\t\t</tr>\n\t\t</table>";
            //unset session shopping cart
            @($_SESSION['nzshpcrt_serialized_cart'] = '');
            $_SESSION['nzshpcrt_cart'] = '';
            $_SESSION['nzshpcrt_cart'] = array();
            //exit('HERE');
            $wpsc_cart->empty_cart();
        } else {
            if (isset($_REQUEST['paymentType']) || isset($_REQUEST['token'])) {
                $token = $_REQUEST['token'];
                if (!isset($token)) {
                    /* 
                    	The servername and serverport tells PayPal where the buyer
                       should be directed back to after authorizing payment.
                       In this case, its the local webserver that is running this script
                       Using the servername and serverport, the return URL is the first
                       portion of the URL that buyers will return to after authorizing payment
                    */
                    $paymentAmount = $_SESSION['paypalAmount'];
                    $currencyCodeType = get_option('paypal_curcode');
                    $paymentType = 'Sale';
                    /* The returnURL is the location where buyers return when a
                    			payment has been succesfully authorized.
                    			The cancelURL is the location buyers are sent to when they hit the
                    			cancel button during authorization of payment during the PayPal flow
                    			*/
                    if (get_option('permalink_structure') != '') {
                        $seperator = "?";
                    } else {
                        $seperator = "&";
                    }
                    $returnURL = urlencode(get_option('transact_url') . $seperator . 'currencyCodeType=' . $currencyCodeType . '&paymentType=' . $paymentType . '&paymentAmount=' . $paymentAmount);
                    $cancelURL = urlencode(get_option('transact_url') . $seperator . 'paymentType=$paymentType');
                    /* Construct the parameter string that describes the PayPal payment
                    			the varialbes were set in the web form, and the resulting string
                    			is stored in $nvpstr
                    			*/
                    $nvpstr = "&Amt=" . $paymentAmount . "&PAYMENTACTION=" . $paymentType . "&ReturnUrl=" . $returnURL . "&CANCELURL=" . $cancelURL . "&CURRENCYCODE=" . $currencyCodeType;
                    /* Make the call to PayPal to set the Express Checkout token
                    			If the API call succeded, then redirect the buyer to PayPal
                    			to begin to authorize payment.  If an error occured, show the
                    			resulting errors
                    			*/
                    $resArray = hash_call("SetExpressCheckout", $nvpstr);
                    $_SESSION['reshash'] = $resArray;
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        // Redirect to paypal.com here
                        $token = urldecode($resArray["TOKEN"]);
                        $payPalURL = PAYPAL_URL . $token;
                        header("Location: " . $payPalURL);
                    } else {
                        //Redirecting to APIError.php to display errors.
                        $location = get_option('transact_url') . "&act=error";
                        header("Location: {$location}");
                    }
                    exit;
                } else {
                    /* At this point, the buyer has completed in authorizing payment
                    		at PayPal.  The script will now call PayPal with the details
                    		of the authorization, incuding any shipping information of the
                    		buyer.  Remember, the authorization is not a completed transaction
                    		at this state - the buyer still needs an additional step to finalize
                    		the transaction
                    		*/
                    $token = urlencode($_REQUEST['token']);
                    /* Build a second API request to PayPal, using the token as the
                    		ID to get the details on the payment authorization
                    		*/
                    $nvpstr = "&TOKEN=" . $token;
                    /* Make the API call and store the results in an array.  If the
                    		call was a success, show the authorization details, and provide
                    		an action to complete the payment.  If failed, show the error
                    		*/
                    $resArray = hash_call("GetExpressCheckoutDetails", $nvpstr);
                    $_SESSION['reshash'] = $resArray;
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        /********************************************************
                        GetExpressCheckoutDetails.php
                        
                        This functionality is called after the buyer returns from
                        PayPal and has authorized the payment.
                        
                        Displays the payer details returned by the
                        GetExpressCheckoutDetails response and calls
                        DoExpressCheckoutPayment.php to complete the payment
                        authorization.
                        
                        Called by ReviewOrder.php.
                        
                        Calls DoExpressCheckoutPayment.php and APIError.php.
                        
                        ********************************************************/
                        session_start();
                        /* Collect the necessary information to complete the
                           authorization for the PayPal payment
                           */
                        $_SESSION['token'] = $_REQUEST['token'];
                        $_SESSION['payer_id'] = $_REQUEST['PayerID'];
                        /*
                        $_SESSION['paymentAmount']=$_REQUEST['paymentAmount'];
                        $_SESSION['currCodeType']=$_REQUEST['currencyCodeType'];
                        $_SESSION['paymentType']=$_REQUEST['paymentType'];
                        */
                        $resArray = $_SESSION['reshash'];
                        if (get_option('permalink_structure') != '') {
                            $seperator = "?";
                        } else {
                            $seperator = "&";
                        }
                        /* Display the  API response back to the browser .
                           If the response from PayPal was a success, display the response parameters
                           */
                        if (isset($_REQUEST['token']) && !isset($_REQUEST['PayerID'])) {
                            $_SESSION['paypalExpressMessage'] = '<h4>TRANSACTION CANCELED</h4>';
                        } else {
                            $_SESSION['paypalExpressMessage'] = "\n\t<form action=" . get_option('transact_url') . " method='post'>\n           <table width='400'>\n            <tr>\n                <td align='left'><b>Order Total:</b></td>\n                <td align='left'>\n                  " . wpsc_cart_total() . "</td>\n            </tr>\n\t\t\t<tr>\n\t\t\t    <td align='left'><b>Shipping Address: </b></td>\n\t\t\t</tr>\n            <tr>\n                <td align='left'>\n                    Street 1:</td>\n                <td align='left'>" . $resArray['SHIPTOSTREET'] . "</td>\n\n            </tr>\n            <tr>\n                <td align='left'>\n                    Street 2:</td>\n                <td align='left'>" . $resArray['SHIPTOSTREET2'] . "\n                </td>\n            </tr>\n            <tr>\n                <td align='left'>\n                    City:</td>\n\n                <td align='left'>" . $resArray['SHIPTOCITY'] . "</td>\n            </tr>\n            <tr>\n                <td align='left'>\n                    State:</td>\n                <td align='left'>" . $resArray['SHIPTOSTATE'] . "</td>\n            </tr>\n            <tr>\n                <td align='left'>\n                    Postal code:</td>\n\n                <td align='left'>" . $resArray['SHIPTOZIP'] . "</td>\n            </tr>\n            <tr>\n                <td align='left'>\n                    Country:</td>\n                <td align='left'>" . $resArray['SHIPTOCOUNTRYNAME'] . "</td>\n            </tr>\n            <tr>\n                <td>";
                            $_SESSION['paypalExpressMessage'] .= "               \n                <input type='hidden' name='totalAmount' value='" . wpsc_cart_total(false) . "' />\n                <input type='hidden' name='shippingStreet' value='" . $resArray['SHIPTOSTREET'] . "' />          \n                <input type='hidden' name='shippingStreet2' value='" . $resArray['SHIPTOSTREET2'] . "' />\n                <input type='hidden' name='shippingCity' value='" . $resArray['SHIPTOCITY'] . "' />\n                <input type='hidden' name='shippingState' value='" . $resArray['SHIPTOSTATE'] . "' />\n                <input type='hidden' name='postalCode' value='" . $resArray['SHIPTOZIP'] . "' />\n                 <input type='hidden' name='country' value='" . $resArray['SHIPTOCOUNTRYNAME'] . "' />\n                <input type='hidden' name='token' value='" . $_SESSION['token'] . "' />\n\t\t\t\t\t<input type='hidden' name='PayerID' value='" . $_SESSION['payer_id'] . "' />\n\t\t\t\t\t<input type='hidden' name='act' value='do' />\n\t\t\t\t\t\n                   <p>  <label for='usePayPal'>Use PayPal Shipping Address: </label><input name='usePayPal' type='submit' value='Pay' /></p>\n                   <p>  <label for='useOther'>Use Previous Shipping Information:</label> <input name='useOther' type='submit' value='Pay' /></p>\n                </td>\n            </tr>\n        </table>\n    </center>\n    </form>";
                        }
                    }
                }
            }
        }
    }
}
Example #13
0
    function submit()
    {
        if (@extension_loaded('soap')) {
            $pxf = new PxFusion();
            # handles most of the Px Fusion magic
            // Work out the probable location of return.php since this sample
            // code could be anywhere on a development server.
            $returnUrl = add_query_arg('sessionid', $this->cart_data['session_id'], get_option('transact_url'));
            // Set some transaction details
            $pxf->set_txn_detail('txnType', 'Purchase');
            # required
            $pxf->set_txn_detail('currency', 'NZD');
            # required
            $pxf->set_txn_detail('returnUrl', $returnUrl);
            # required
            $pxf->set_txn_detail('amount', number_format(wpsc_cart_total(false), $decimals = 2, $dec_point = '.', $thousands_sep = ''));
            # required
            $pxf->set_txn_detail('merchantReference', get_bloginfo('name'));
            // Some of the many optional settings that could be specified:
            $pxf->set_txn_detail('enableAddBillCard', 0);
            $pxf->set_txn_detail('txnRef', substr(uniqid() . rand(1000, 9999), 0, 16));
            # random 16 digit reference);
            // Make the request for a transaction id
            $response = $pxf->get_transaction_id();
            if (!$response->GetTransactionIdResult->success) {
                wp_die('Error! There was a problem getting a transaction id from DPS, please contact the server administrator.');
            } else {
                // You should store these values in a database
                // ... they are needed to query the transaction's outcome
                $result = $response->GetTransactionIdResult;
                $transaction_id = $result->transactionId;
                $session_id = $result->sessionId;
            }
            $curlPost = array('SessionId' => $session_id, 'Add' => 'Add', 'CardHolderName' => $_POST['CardHolderName'], 'CardNumber' => $_POST['CardNumber'], 'Cvc2' => $_POST['Cvc2'], 'ExpiryMonth' => $_POST['ExpiryMonth'], 'ExpiryYear' => $_POST['ExpiryYear']);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://sec2.paymentexpress.com/pxmi3/pxfusionauth');
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_CAINFO, WPSC_GOLD_FILE_PATH . "/merchants/paymentexpress/ThawteServerCA");
            $data = curl_exec($ch);
            curl_close($ch);
        } else {
            $data = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://paymentexpress.com">
						  <SOAP-ENV:Body>
						    <ns1:GetTransactionId>
						      <ns1:username>InstinctFusion</ns1:username>
						      <ns1:password>inst1234</ns1:password>
						      <ns1:tranDetail>
						        <ns1:amount>1.00</ns1:amount>
						        <ns1:currency>NZD</ns1:currency>
						        <ns1:enableAddBillCard>false</ns1:enableAddBillCard>
						        <ns1:merchantReference>Px Fusion -PHP</ns1:merchantReference>
						        <ns1:returnUrl>http://www.myReturnURL/return.php</ns1:returnUrl>
						        <ns1:txnRef>4cf703e6c79ff738</ns1:txnRef>
						        <ns1:txnType>Purchase</ns1:txnType>
						      </ns1:tranDetail>
						    </ns1:GetTransactionId>
						  </SOAP-ENV:Body>
						</SOAP-ENV:Envelope>';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://sec2.paymentexpress.com/pxf/pxf.svc?wsdl");
            curl_setopt($ch, CURLOPT_VERBOSE, 0);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            // SSL security
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_CAINFO, WPSC_GOLD_FILE_PATH . "/merchants/paymentexpress/ThawteServerCA");
            //
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: text/xml;charset=\"utf-8\"", "Accept: text/xml", "Cache-Control: no-cache", "Pragma: no-cache", "SOAPAction: \"http://paymentexpress.com/IPxFusion/GetTransactionId\"", "Content-length: " . strlen($data)));
            $response = curl_exec($ch);
            if (curl_errno($ch)) {
                wp_die('Curl error: ' . curl_error($ch) . '. Please contact server administrator.');
            }
            curl_close($ch);
            $xml_parser = xml_parser_create();
            if (!xml_parse_into_struct($xml_parser, $response, $vals, $index)) {
                wp_die("Error while parsing response from PX Fusion. Line " . xml_get_current_line_number($xml_parser) . '. Please contact server administrator.');
            }
            xml_parser_free($xml_parser);
            $parsed_xml = array();
            foreach ($vals as $val) {
                $parsed_xml[$val['tag']] = $val['value'];
            }
            if (!$parsed_xml['A:SUCCESS']) {
                wp_die('Error! There was a problem getting a transaction id from DPS, please contact the server administrator.');
            } else {
                // You should store these values in a database
                // ... they are needed to query the transaction's outcome
                $transaction_id = $parsed_xml["A:TRANSACTIONID"];
                $session_id = $parsed_xml["A:SESSIONID"];
            }
            $curlPost = array('SessionId' => $session_id, 'Add' => 'Add', 'CardHolderName' => $_POST['CardHolderName'], 'CardNumber' => $_POST['CardNumber'], 'Cvc2' => $_POST['Cvc2'], 'ExpiryMonth' => $_POST['ExpiryMonth'], 'ExpiryYear' => $_POST['ExpiryYear']);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://sec2.paymentexpress.com/pxmi3/pxfusionauth');
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_CAINFO, WPSC_GOLD_FILE_PATH . "/merchants/paymentexpress/ThawteServerCA");
            $data = curl_exec($ch);
            curl_close($ch);
        }
        $this->px_process_transaction($transaction_id);
    }
 /**
  * Comparing logic with the product information
  *
  * Checks if the product matchs the logic
  *
  * @return bool True if all conditions are matched, False otherwise.
  */
 function compare_logic($c, $product_obj)
 {
     global $wpdb;
     if ($c['property'] == 'item_name') {
         $product_data = $wpdb->get_results("SELECT * FROM " . $wpdb->posts . " WHERE id='{$product_obj->product_id}'");
         $product_data = $product_data[0];
         switch ($c['logic']) {
             case 'equal':
                 //Checks if the product name is exactly the same as the condition value
                 if ($product_data->post_title == $c['value']) {
                     return true;
                 }
                 break;
             case 'greater':
                 //Checks if the product name is not the same as the condition value
                 if ($product_data->post_title > $c['value']) {
                     return true;
                 }
                 break;
             case 'less':
                 //Checks if the product name is not the same as the condition value
                 if ($product_data->post_title < $c['value']) {
                     return true;
                 }
                 break;
             case 'contains':
                 //Checks if the product name contains the condition value
                 preg_match("/(.*)" . $c['value'] . "(.*)/", $product_data->post_title, $match);
                 if (!empty($match)) {
                     return true;
                 }
                 break;
             case 'category':
                 //Checks if the product category is the condition value
                 if ($product_data->post_parent) {
                     $categories = wp_get_post_terms($product_data->post_parent, 'wpsc_product_category');
                 } else {
                     $categories = wp_get_post_terms($product_data->ID, 'wpsc_product_category');
                 }
                 foreach ($categories as $cat) {
                     if (strtolower($cat->name) == strtolower($c['value'])) {
                         return true;
                     }
                 }
                 break;
             case 'not_contain':
                 //Checks if the product name contains the condition value
                 preg_match("/(.*)" . $c['value'] . "(.*)/", $product_data->post_title, $match);
                 if (empty($match)) {
                     return true;
                 }
                 break;
             case 'begins':
                 //Checks if the product name begins with condition value
                 preg_match("/^" . $c['value'] . "/", $product_data->post_title, $match);
                 if (!empty($match)) {
                     return true;
                 }
                 break;
             case 'ends':
                 //Checks if the product name ends with condition value
                 preg_match("/" . $c['value'] . "\$/", $product_data->post_title, $match);
                 if (!empty($match)) {
                     return true;
                 }
                 break;
             case 'category':
                 //Checks if the product name is in the set category
                 $product_categories = wp_get_post_terms($product_data->ID, 'wpsc_product_category');
                 foreach ($product_categories as $product_cat) {
                     if ($product_cat->name == $c['value']) {
                         return true;
                     }
                 }
                 break;
             default:
                 return false;
         }
     } else {
         if ($c['property'] == 'item_quantity') {
             switch ($c['logic']) {
                 case 'equal':
                     //Checks if the quantity of a product in the cart equals condition value
                     if ($product_obj->quantity == (int) $c['value']) {
                         return true;
                     }
                     break;
                 case 'greater':
                     //Checks if the quantity of a product is greater than the condition value
                     if ($product_obj->quantity > $c['value']) {
                         return true;
                     }
                     break;
                 case 'less':
                     //Checks if the quantity of a product is less than the condition value
                     if ($product_obj->quantity < $c['value']) {
                         return true;
                     }
                     break;
                 case 'contains':
                     //Checks if the product name contains the condition value
                     preg_match("/(.*)" . $c['value'] . "(.*)/", $product_obj->quantity, $match);
                     if (!empty($match)) {
                         return true;
                     }
                     break;
                 case 'not_contain':
                     //Checks if the product name contains the condition value
                     preg_match("/(.*)" . $c['value'] . "(.*)/", $product_obj->quantity, $match);
                     if (empty($match)) {
                         return true;
                     }
                     break;
                 case 'begins':
                     //Checks if the product name begins with condition value
                     preg_match("/^" . $c['value'] . "/", $product_obj->quantity, $match);
                     if (!empty($match)) {
                         return true;
                     }
                     break;
                 case 'ends':
                     //Checks if the product name ends with condition value
                     preg_match("/" . $c['value'] . "\$/", $product_obj->quantity, $match);
                     if (!empty($match)) {
                         return true;
                     }
                     break;
                 default:
                     return false;
             }
         } else {
             if ($c['property'] == 'total_quantity') {
                 $total_quantity = wpsc_cart_item_count();
                 switch ($c['logic']) {
                     case 'equal':
                         //Checks if the quantity of products in the cart equals condition value
                         if ($total_quantity == $c['value']) {
                             return true;
                         }
                         break;
                     case 'greater':
                         //Checks if the quantity in the cart is greater than the condition value
                         if ($total_quantity > $c['value']) {
                             return true;
                         }
                         break;
                     case 'less':
                         //Checks if the quantity in the cart is less than the condition value
                         if ($total_quantity < $c['value']) {
                             return true;
                         }
                         break;
                     default:
                         return false;
                 }
             } else {
                 if ($c['property'] == 'subtotal_amount') {
                     $subtotal = wpsc_cart_total(false);
                     switch ($c['logic']) {
                         case 'equal':
                             //Checks if the subtotal of products in the cart equals condition value
                             if ($subtotal == $c['value']) {
                                 return true;
                             }
                             break;
                         case 'greater':
                             //Checks if the subtotal of the cart is greater than the condition value
                             if ($subtotal > $c['value']) {
                                 return true;
                             }
                             break;
                         case 'less':
                             //Checks if the subtotal of the cart is less than the condition value
                             if ($subtotal < $c['value']) {
                                 return true;
                             } else {
                                 return false;
                             }
                             break;
                         default:
                             return false;
                     }
                 } else {
                     return apply_filters('wpsc_coupon_compare_logic', false, $c, $product_obj);
                 }
             }
         }
     }
 }
/**
 * prcessing functions, this is where the main logic of paypal express lives
 * @access public
 *
 * @since 3.8
 */
function paypal_processingfunctions()
{
    global $wpdb, $wpsc_cart;
    $sessionid = '';
    if (isset($_SESSION['paypalexpresssessionid'])) {
        $sessionid = $_SESSION['paypalexpresssessionid'];
    }
    if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'error') {
        session_start();
        $resArray = $_SESSION['reshash'];
        $_SESSION['paypalExpressMessage'] = '
		<center>
		<table width="700" align="left">
		<tr>
			<td colspan="2" class="header">' . __('The PayPal API has returned an error!', 'wpsc') . '</td>
		</tr>
		';
        //it will print if any URL errors
        if (isset($_SESSION['curl_error_msg'])) {
            $errorMessage = $_SESSION['curl_error_msg'];
            $response = $_SESSION['response'];
            session_unset();
            $_SESSION['paypalExpressMessage'] .= '
			<tr>
				<td>response:</td>
				<td>' . $response . '</td>
			</tr>
			   
			<tr>
				<td>Error Message:</td>
				<td>' . $errorMessage . '</td>
			</tr>';
        } else {
            /* If there is no URL Errors, Construct the HTML page with 
               Response Error parameters.   */
            $_SESSION['paypalExpressMessage'] .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Ack:</td>\n\t\t\t\t\t<td>" . $resArray['ACK'] . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Correlation ID:</td>\n\t\t\t\t\t<td>" . $resArray['CORRELATIONID'] . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Version:</td>\n\t\t\t\t\t<td>" . $resArray['VERSION'] . "</td>\n\t\t\t\t</tr>";
            $count = 0;
            while (isset($resArray["L_SHORTMESSAGE" . $count])) {
                $errorCode = $resArray["L_ERRORCODE" . $count];
                $shortMessage = $resArray["L_SHORTMESSAGE" . $count];
                $longMessage = $resArray["L_LONGMESSAGE" . $count];
                $count = $count + 1;
                $_SESSION['paypalExpressMessage'] .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Error Number:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$errorCode} </td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Short Message:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$shortMessage} </td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Long Message:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$longMessage} </td>\n\t\t\t\t\t</tr>";
            }
            //end while
        }
        // end else
        $_SESSION['paypalExpressMessage'] .= "\n\t\t\t</center>\n\t\t\t\t</table>";
    } else {
        if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'do') {
            session_start();
            /* Gather the information to make the final call to
               finalize the PayPal payment.  The variable nvpstr
               holds the name value pairs   */
            $token = urlencode($_REQUEST['token']);
            $paymentAmount = urlencode($_SESSION['paypalAmount']);
            $paymentType = urlencode($_SESSION['paymentType']);
            $currCodeType = urlencode(get_option('paypal_curcode'));
            $payerID = urlencode($_REQUEST['PayerID']);
            $serverName = urlencode($_SERVER['SERVER_NAME']);
            $BN = 'Instinct_e-commerce_wp-shopping-cart_NZ';
            $nvpstr = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTACTION=Sale&AMT=' . $paymentAmount . '&CURRENCYCODE=' . $currCodeType . '&IPADDRESS=' . $serverName . "&BUTTONSOURCE=" . $BN;
            $resArray = paypal_hash_call("DoExpressCheckoutPayment", $nvpstr);
            /* Display the API response back to the browser.
               If the response from PayPal was a success, display the response parameters'
               If the response was an error, display the errors received using APIError.php. */
            $ack = strtoupper($resArray["ACK"]);
            $_SESSION['reshash'] = $resArray;
            if ($ack != "SUCCESS") {
                $location = get_option('transact_url') . "&act=error";
            } else {
                $transaction_id = $wpdb->escape($resArray['TRANSACTIONID']);
                switch ($resArray['PAYMENTSTATUS']) {
                    case 'Processed':
                        // I think this is mostly equivalent to Completed
                    // I think this is mostly equivalent to Completed
                    case 'Completed':
                        $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '3' WHERE `sessionid` = " . $sessionid . " LIMIT 1");
                        transaction_results($_SESSION['wpsc_sessionid'], false, $transaction_id);
                        break;
                    case 'Pending':
                        // need to wait for "Completed" before processing
                        $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `transactid` = '" . $transaction_id . "',`processed` = '2', `date` = '" . time() . "'  WHERE `sessionid` = " . $sessionid . " LIMIT 1");
                        break;
                }
                $location = add_query_arg('sessionid', $sessionid, get_option('transact_url'));
                $_SESSION['paypalExpressMessage'] = null;
                wp_redirect($location);
                exit;
            }
            @($_SESSION['nzshpcrt_serialized_cart'] = '');
            $_SESSION['nzshpcrt_cart'] = '';
            $_SESSION['nzshpcrt_cart'] = array();
            $wpsc_cart->empty_cart();
        } else {
            if (isset($_REQUEST['paymentType']) || isset($_REQUEST['token'])) {
                $token = $_REQUEST['token'];
                if (!isset($token)) {
                    $paymentAmount = $_SESSION['paypalAmount'];
                    $currencyCodeType = get_option('paypal_curcode');
                    $paymentType = 'Sale';
                    if (get_option('permalink_structure') != '') {
                        $separator = "?";
                    } else {
                        $separator = "&";
                    }
                    $returnURL = urlencode(get_option('transact_url') . $separator . 'currencyCodeType=' . $currencyCodeType . '&paymentType=' . $paymentType . '&paymentAmount=' . $paymentAmount);
                    $cancelURL = urlencode(get_option('transact_url') . $separator . 'paymentType=$paymentType');
                    /* Construct the parameter string that describes the PayPal payment
                    			the varialbes were set in the web form, and the resulting string
                    			is stored in $nvpstr */
                    $nvpstr = "&Amt=" . $paymentAmount . "&PAYMENTACTION=" . $paymentType . "&ReturnUrl=" . $returnURL . "&CANCELURL=" . $cancelURL . "&CURRENCYCODE=" . $currencyCodeType;
                    /* Make the call to PayPal to set the Express Checkout token
                    			If the API call succeded, then redirect the buyer to PayPal
                    			to begin to authorize payment.  If an error occured, show the
                    			resulting errors
                    			*/
                    $resArray = paypal_hash_call("SetExpressCheckout", $nvpstr);
                    $_SESSION['reshash'] = $resArray;
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        // Redirect to paypal.com here
                        $token = urldecode($resArray["TOKEN"]);
                        $payPalURL = $PAYPAL_URL . $token;
                        wp_redirect($payPalURL);
                    } else {
                        // Redirecting to APIError.php to display errors.
                        $location = get_option('transact_url') . "&act=error";
                        wp_redirect($location);
                    }
                    exit;
                } else {
                    /* At this point, the buyer has completed in authorizing payment
                    			at PayPal.  The script will now call PayPal with the details
                    			of the authorization, incuding any shipping information of the
                    			buyer.  Remember, the authorization is not a completed transaction
                    			at this state - the buyer still needs an additional step to finalize
                    			the transaction
                    			*/
                    $token = urlencode($_REQUEST['token']);
                    /* Build a second API request to PayPal, using the token as the
                    			ID to get the details on the payment authorization
                    			*/
                    $nvpstr = "&TOKEN=" . $token;
                    /* Make the API call and store the results in an array.  If the
                    			call was a success, show the authorization details, and provide
                    			an action to complete the payment.  If failed, show the error
                    			*/
                    $resArray = paypal_hash_call("GetExpressCheckoutDetails", $nvpstr);
                    $_SESSION['reshash'] = $resArray;
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        /********************************************************
                        			GetExpressCheckoutDetails.php
                        			
                        			This functionality is called after the buyer returns from
                        			PayPal and has authorized the payment.
                        			
                        			Displays the payer details returned by the
                        			GetExpressCheckoutDetails response and calls
                        			DoExpressCheckoutPayment.php to complete the payment
                        			authorization.
                        			
                        			Called by ReviewOrder.php.
                        			
                        			Calls DoExpressCheckoutPayment.php and APIError.php.
                        			
                        			********************************************************/
                        session_start();
                        /* Collect the necessary information to complete the
                        			authorization for the PayPal payment
                        			*/
                        $_SESSION['token'] = $_REQUEST['token'];
                        $_SESSION['payer_id'] = $_REQUEST['PayerID'];
                        $resArray = $_SESSION['reshash'];
                        if (get_option('permalink_structure') != '') {
                            $separator = "?";
                        } else {
                            $separator = "&";
                        }
                        /* Display the  API response back to the browser .
                        			If the response from PayPal was a success, display the response parameters
                        			*/
                        if (isset($_REQUEST['TOKEN']) && !isset($_REQUEST['PAYERID'])) {
                            $_SESSION['paypalExpressMessage'] = '<h4>TRANSACTION CANCELED</h4>';
                        } else {
                            $output = "\n\t\t\t\t       <table width='400' class='paypal_express_form'>\n\t\t\t\t        <tr>\n\t\t\t\t            <td align='left' class='firstcol'><b>" . __('Error Number:', 'wpsc') . "Order Total:</b></td>\n\t\t\t\t            <td align='left'>" . wpsc_currency_display($_SESSION['paypalAmount']) . "</td>\n\t\t\t\t        </tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t    <td align='left'><b>" . __('Shipping Address:', 'wpsc') . " </b></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t        <tr>\n\t\t\t\t            <td align='left' class='firstcol'>\n\t\t\t\t                " . __('Street 1:', 'wpsc') . "</td>\n\t\t\t\t            <td align='left'>" . $resArray['SHIPTOSTREET'] . "</td>\n\t\t\t\t\n\t\t\t\t        </tr>\n\t\t\t\t        <tr>\n\t\t\t\t            <td align='left' class='firstcol'>\n\t\t\t\t                " . __('Street 2:', 'wpsc') . "</td>\n\t\t\t\t            <td align='left'>" . $resArray['SHIPTOSTREET2'] . "\n\t\t\t\t            </td>\n\t\t\t\t        </tr>\n\t\t\t\t        <tr>\n\t\t\t\t            <td align='left' class='firstcol'>\n\t\t\t\t                " . __('City:', 'wpsc') . "</td>\n\t\t\t\t\n\t\t\t\t            <td align='left'>" . $resArray['SHIPTOCITY'] . "</td>\n\t\t\t\t        </tr>\n\t\t\t\t        <tr>\n\t\t\t\t            <td align='left' class='firstcol'>\n\t\t\t\t                " . __('State:', 'wpsc') . "</td>\n\t\t\t\t            <td align='left'>" . $resArray['SHIPTOSTATE'] . "</td>\n\t\t\t\t        </tr>\n\t\t\t\t        <tr>\n\t\t\t\t            <td align='left' class='firstcol'>\n\t\t\t\t                " . __('Postal code:', 'wpsc') . "</td>\n\t\t\t\t\n\t\t\t\t            <td align='left'>" . $resArray['SHIPTOZIP'] . "</td>\n\t\t\t\t        </tr>\n\t\t\t\t        <tr>\n\t\t\t\t            <td align='left' class='firstcol'>\n\t\t\t\t                " . __('Country:', 'wpsc') . "</td>\n\t\t\t\t            <td align='left'>" . $resArray['SHIPTOCOUNTRYNAME'] . "</td>\n\t\t\t\t        </tr>\n\t\t\t\t        <tr>\n\t\t\t\t            <td>";
                            $output .= "<form action=" . get_option('transact_url') . " method='post'>\n";
                            $output .= "\t<input type='hidden' name='totalAmount' value='" . wpsc_cart_total(false) . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingStreet' value='" . $resArray['SHIPTOSTREET'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingStreet2' value='" . $resArray['SHIPTOSTREET2'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingCity' value='" . $resArray['SHIPTOCITY'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingState' value='" . $resArray['SHIPTOSTATE'] . "' />\n";
                            $output .= "\t<input type='hidden' name='postalCode' value='" . $resArray['SHIPTOZIP'] . "' />\n";
                            $output .= "\t<input type='hidden' name='country' value='" . $resArray['SHIPTOCOUNTRYNAME'] . "' />\n";
                            $output .= "\t<input type='hidden' name='token' value='" . $_SESSION['token'] . "' />\n";
                            $output .= "\t<input type='hidden' name='PayerID' value='" . $_SESSION['payer_id'] . "' />\n";
                            $output .= "\t<input type='hidden' name='act' value='do' />\n";
                            $output .= "\t<p>  <input name='usePayPal' type='submit' value='" . __('Confirm Payment', 'wpsc') . "' /></p>\n";
                            $output .= "</form>";
                            $output .= " </td>\n\t\t\t\t\t        </tr>\n\t\t\t\t\t    </table>\n\t\t\t\t\t</center>\n\t\t\t\t\t";
                            $_SESSION['paypalExpressMessage'] = $output;
                        }
                    }
                }
            }
        }
    }
}