示例#1
0
 /**
  * AJAX update order review on checkout
  */
 public static function update_order_review()
 {
     ob_start();
     check_ajax_referer('update-order-review', 'security');
     if (!defined('WOOCOMMERCE_CHECKOUT')) {
         define('WOOCOMMERCE_CHECKOUT', true);
     }
     if (WC()->cart->is_empty()) {
         $data = array('fragments' => apply_filters('woocommerce_update_order_review_fragments', array('form.woocommerce-checkout' => '<div class="woocommerce-error">' . __('Sorry, your session has expired.', 'woocommerce') . ' <a href="' . home_url() . '" class="wc-backward">' . __('Return to homepage', 'woocommerce') . '</a></div>')));
         wp_send_json($data);
         die;
     }
     do_action('woocommerce_checkout_update_order_review', $_POST['post_data']);
     $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
     if (isset($_POST['shipping_method']) && is_array($_POST['shipping_method'])) {
         foreach ($_POST['shipping_method'] as $i => $value) {
             $chosen_shipping_methods[$i] = wc_clean($value);
         }
     }
     WC()->session->set('chosen_shipping_methods', $chosen_shipping_methods);
     WC()->session->set('chosen_payment_method', empty($_POST['payment_method']) ? '' : $_POST['payment_method']);
     if (isset($_POST['country'])) {
         WC()->customer->set_country($_POST['country']);
     }
     if (isset($_POST['state'])) {
         WC()->customer->set_state($_POST['state']);
     }
     if (isset($_POST['postcode'])) {
         WC()->customer->set_postcode($_POST['postcode']);
     }
     if (isset($_POST['city'])) {
         WC()->customer->set_city($_POST['city']);
     }
     if (isset($_POST['address'])) {
         WC()->customer->set_address($_POST['address']);
     }
     if (isset($_POST['address_2'])) {
         WC()->customer->set_address_2($_POST['address_2']);
     }
     if (wc_ship_to_billing_address_only()) {
         if (isset($_POST['country'])) {
             WC()->customer->set_shipping_country($_POST['country']);
         }
         if (isset($_POST['state'])) {
             WC()->customer->set_shipping_state($_POST['state']);
         }
         if (isset($_POST['postcode'])) {
             WC()->customer->set_shipping_postcode($_POST['postcode']);
         }
         if (isset($_POST['city'])) {
             WC()->customer->set_shipping_city($_POST['city']);
         }
         if (isset($_POST['address'])) {
             WC()->customer->set_shipping_address($_POST['address']);
         }
         if (isset($_POST['address_2'])) {
             WC()->customer->set_shipping_address_2($_POST['address_2']);
         }
     } else {
         if (isset($_POST['s_country'])) {
             WC()->customer->set_shipping_country($_POST['s_country']);
         }
         if (isset($_POST['s_state'])) {
             WC()->customer->set_shipping_state($_POST['s_state']);
         }
         if (isset($_POST['s_postcode'])) {
             WC()->customer->set_shipping_postcode($_POST['s_postcode']);
         }
         if (isset($_POST['s_city'])) {
             WC()->customer->set_shipping_city($_POST['s_city']);
         }
         if (isset($_POST['s_address'])) {
             WC()->customer->set_shipping_address($_POST['s_address']);
         }
         if (isset($_POST['s_address_2'])) {
             WC()->customer->set_shipping_address_2($_POST['s_address_2']);
         }
     }
     WC()->cart->calculate_totals();
     // Get order review fragment
     ob_start();
     woocommerce_order_review();
     $woocommerce_order_review = ob_get_clean();
     // Get checkout payment fragment
     ob_start();
     woocommerce_checkout_payment();
     $woocommerce_checkout_payment = ob_get_clean();
     // Get messages if reload checkout is not true
     $messages = '';
     if (!isset(WC()->session->reload_checkout)) {
         ob_start();
         wc_print_notices();
         $messages = ob_get_clean();
     }
     $data = array('result' => empty($messages) ? 'success' : 'failure', 'messages' => $messages, 'reload' => isset(WC()->session->reload_checkout) ? 'true' : 'false', 'fragments' => apply_filters('woocommerce_update_order_review_fragments', array('.woocommerce-checkout-review-order-table' => $woocommerce_order_review, '.woocommerce-checkout-payment' => $woocommerce_checkout_payment)));
     wp_send_json($data);
     die;
 }
示例#2
0
 /**
  * AJAX update order review on checkout.
  */
 public static function update_order_review()
 {
     check_ajax_referer('update-order-review', 'security');
     wc_maybe_define_constant('WOOCOMMERCE_CHECKOUT', true);
     if (WC()->cart->is_empty()) {
         self::update_order_review_expired();
     }
     do_action('woocommerce_checkout_update_order_review', $_POST['post_data']);
     $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
     if (isset($_POST['shipping_method']) && is_array($_POST['shipping_method'])) {
         foreach ($_POST['shipping_method'] as $i => $value) {
             $chosen_shipping_methods[$i] = wc_clean($value);
         }
     }
     WC()->session->set('chosen_shipping_methods', $chosen_shipping_methods);
     WC()->session->set('chosen_payment_method', empty($_POST['payment_method']) ? '' : $_POST['payment_method']);
     WC()->customer->set_props(array('billing_country' => isset($_POST['country']) ? $_POST['country'] : null, 'billing_state' => isset($_POST['state']) ? $_POST['state'] : null, 'billing_postcode' => isset($_POST['postcode']) ? $_POST['postcode'] : null, 'billing_city' => isset($_POST['city']) ? $_POST['city'] : null, 'billing_address_1' => isset($_POST['address']) ? $_POST['address'] : null, 'billing_address_2' => isset($_POST['address_2']) ? $_POST['address_2'] : null));
     if (wc_ship_to_billing_address_only()) {
         WC()->customer->set_props(array('shipping_country' => isset($_POST['country']) ? $_POST['country'] : null, 'shipping_state' => isset($_POST['state']) ? $_POST['state'] : null, 'shipping_postcode' => isset($_POST['postcode']) ? $_POST['postcode'] : null, 'shipping_city' => isset($_POST['city']) ? $_POST['city'] : null, 'shipping_address_1' => isset($_POST['address']) ? $_POST['address'] : null, 'shipping_address_2' => isset($_POST['address_2']) ? $_POST['address_2'] : null));
         if (!empty($_POST['country'])) {
             WC()->customer->set_calculated_shipping(true);
         }
     } else {
         WC()->customer->set_props(array('shipping_country' => isset($_POST['s_country']) ? $_POST['s_country'] : null, 'shipping_state' => isset($_POST['s_state']) ? $_POST['s_state'] : null, 'shipping_postcode' => isset($_POST['s_postcode']) ? $_POST['s_postcode'] : null, 'shipping_city' => isset($_POST['s_city']) ? $_POST['s_city'] : null, 'shipping_address_1' => isset($_POST['s_address']) ? $_POST['s_address'] : null, 'shipping_address_2' => isset($_POST['s_address_2']) ? $_POST['s_address_2'] : null));
         if (!empty($_POST['s_country'])) {
             WC()->customer->set_calculated_shipping(true);
         }
     }
     WC()->customer->save();
     WC()->cart->calculate_totals();
     // Get order review fragment
     ob_start();
     woocommerce_order_review();
     $woocommerce_order_review = ob_get_clean();
     // Get checkout payment fragment
     ob_start();
     woocommerce_checkout_payment();
     $woocommerce_checkout_payment = ob_get_clean();
     // Get messages if reload checkout is not true
     $messages = '';
     if (!isset(WC()->session->reload_checkout)) {
         ob_start();
         wc_print_notices();
         $messages = ob_get_clean();
     }
     unset(WC()->session->refresh_totals, WC()->session->reload_checkout);
     wp_send_json(array('result' => empty($messages) ? 'success' : 'failure', 'messages' => $messages, 'reload' => isset(WC()->session->reload_checkout) ? 'true' : 'false', 'fragments' => apply_filters('woocommerce_update_order_review_fragments', array('.woocommerce-checkout-review-order-table' => $woocommerce_order_review, '.woocommerce-checkout-payment' => $woocommerce_checkout_payment))));
 }
                        <?php 
    }
}
?>
                    </div>
                </div>
            </div>
        </div>

    


        <div id="paypalexpress_order_review" style="display: none;">
                <?php 
woocommerce_order_review();
?>
        </div>

<?php 
if (WC()->cart->needs_shipping()) {
    ?>


  

    <div class="col2-set addresses">

        <div class="col-1">

            <div class="title">
    /**
     * Render checkout page
     */
    function get_hygglig_checkout_page()
    {
        //Add action for order review
        add_action('renderOrderReview', 'printOrderReview');
        // Debug
        if ($this->debug == 'yes') {
            $this->log->add('hygglig', 'HCO page about to render...');
        }
        global $woocommerce;
        global $current_user;
        //Checkout country should always be Sweden
        WC()->customer->set_shipping_country('SE');
        // Merchant ID
        $merchantid = $this->hygglig_merchantid;
        if (isset($_GET['token'])) {
            // Debug
            if ($this->debug == 'yes') {
                $this->log->add('hygglig', 'Rendering Thank you page...');
            }
            // Store the response as a TOKEN
            $token = $_GET['token'];
            // Display Order response/thank you page via iframe from Hygglig
            // Shared secret
            $sharedSecret = $this->hygglig_secret;
            //Next part is to ask for the iFrame
            $getiframeCheckSum = SHA1(strtoupper($token . $sharedSecret));
            $getiframeAPI = $this->hygglig_server . 'GetIFrame';
            //Destroy previous $create
            $create = array();
            //GetIFrame
            $create['MerchantKey'] = $merchantid;
            $create['Checksum'] = $getiframeCheckSum;
            $create['Token'] = $token;
            //Store Token for Future use
            $_SESSION['storedToken'] = $token;
            // Setup cURL
            $ch = curl_init($getiframeAPI);
            curl_setopt_array($ch, array(CURLOPT_POST => TRUE, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPHEADER => array('Content-Type: application/json; encoding=utf-8'), CURLOPT_POSTFIELDS => json_encode($create)));
            // Send the request
            $response = curl_exec($ch);
            // Check for errors
            if ($response === FALSE) {
                die(curl_error($ch));
            } else {
                //Close Curl
                curl_close($ch);
                //Clear old result
                $responseData = null;
                //Echo result
                $responseData = json_decode($response, true, 1024, JSON_BIGINT_AS_STRING);
            }
            $text = $responseData["HtmlText"];
            $storeSid = $_GET['sid'];
            ob_start();
            do_action('hygglig_before_hco_confirmation');
            //Was checkout/payment success or fail? If not successfull - don't clear session
            if (preg_match('/PaymentSuccess/', $text) || preg_match('/CheckoutSuccess/', $text)) {
                //Is success - clear session and cart
                do_action('woocommerce_thankyou', $storeSid);
                WC()->session->__unset('hygglig_checkout');
                // Remove cart
                $woocommerce->cart->empty_cart(true);
                ?>
					<script type="text/javascript">
					<!--
					//If Theme use "woo-menu-cart" hide it
					var x = document.getElementsByClassName("woo-menu-cart");
					x[0].style.display = 'none';
					//--></script>
					<?php 
            }
            echo '<link href="' . HYGGLIG_URL . '/css/hygglig.css" rel="stylesheet">';
            echo $text;
            do_action('hygglig_after_hco_confirmation', $storeSid);
            return ob_get_clean();
        } else {
            // Don't render the Hygglig Checkout form if the payment gateway isn't enabled.
            if ($this->enabled != 'yes') {
                return;
            }
            // If no Hygglig country is set - return.
            if (empty($this->hygglig_country)) {
                echo apply_filters('hygglig_checkout_wrong_country_message', sprintf(__('Sorry, you can not buy via Hygglig Checkout from your country or currency. Please <a href="%s">use another payment method</a>.', 'hygglig'), get_permalink(get_option('woocommerce_checkout_page_id'))));
                return;
            }
            // Recheck cart items so that they are in stock
            $result = $woocommerce->cart->check_cart_item_stock();
            if (is_wp_error($result)) {
                return $result->get_error_message();
            }
            // If checkout registration is disabled and not logged in, the user cannot checkout
            $checkout = $woocommerce->checkout();
            if (!$checkout->enable_guest_checkout && !is_user_logged_in()) {
                //do_action( 'woocommerce_login_form' );
                echo apply_filters('woocommerce_checkout_must_be_logged_in_message', __('You must be logged in to checkout.', 'woocommerce'));
                return;
            }
            // Process order via Hygglig Checkout page
            if (!defined('WOOCOMMERCE_CHECKOUT')) {
                define('WOOCOMMERCE_CHECKOUT', true);
            }
            if (!defined('WOOCOMMERCE_HYGGLIG_CHECKOUT')) {
                define('WOOCOMMERCE_HYGGLIG_CHECKOUT', true);
            }
            // Set Hygglig Checkout as the choosen payment method in the WC session
            WC()->session->set('chosen_payment_method', 'Hygglig');
            // Debug
            if ($this->debug == 'yes') {
                $this->log->add('hygglig', 'Rendering Checkout page...');
            }
            // Mobile or desktop browser
            if (wp_is_mobile()) {
                $hygglig_checkout_layout = 'mobile';
            } else {
                $hygglig_checkout_layout = 'desktop';
            }
            // If the WooCommerce terms page or the Hygglig Checkout settings field Terms Page isn't set, do nothing.
            if (empty($this->terms_url)) {
                return;
            }
            // Set $add_hygglig_window_size_script to true so that Window size detection script can load in the footer
            global $add_hygglig_window_size_script;
            $add_hygglig_window_size_script = true;
            //Add WooCommerce Div's
            echo '<div class="woocommerce"><form name="checkout" method="post" class="checkout woocommerce-checkout" action=' . $_SERVER['REQUEST_URI'] . ' enctype="multipart/form-data">';
            //Add button to Standard Checkout Page if this is enabled in the settings
            if ($this->add_std_checkout_button == 'yes') {
                echo '<br><a href="' . get_permalink(get_option('woocommerce_checkout_page_id')) . '" class="button std-checkout-button">' . $this->std_checkout_button_label . '</a><br>';
            }
            if (sizeof($woocommerce->cart->get_cart()) > 0) {
                // Create a new order
                $order_id = $this->create_order();
                // Check that the order doesnt contain an error message (from check_cart_item_stock() fired in create_order())
                if (!is_numeric($order_id)) {
                    //var_dump($order_id);
                    echo '<ul class="woocommerce-error"><li>' . __($order_id, 'woocommerce') . '</li></ul>';
                    exit;
                }
                do_action('woocommerce_checkout_order_processed', $order_id, false);
                // Store Order ID in session so it can be re-used if customer navigates away from the checkout and then return again
                $woocommerce->session->order_awaiting_payment = $order_id;
                // Get an instance of the created order
                $order = WC_Hygglig_Compatibility::wc_get_order($order_id);
                $cart = array();
                $totalAmount = 0;
                // Cart Contents
                if (sizeof($order->get_items()) > 0) {
                    foreach ($order->get_items() as $item) {
                        if ($item['qty']) {
                            $_product = $order->get_product_from_item($item);
                            // We manually calculate the tax percentage here
                            if ($_product->is_taxable() && $order->get_line_tax($item) > 0) {
                                // Calculate tax percentage
                                $item_tax_percentage = round($order->get_item_tax($item, false) / $order->get_item_total($item, false, false), 2) * 100;
                            } else {
                                $item_tax_percentage = 00;
                            }
                            $item_name = $item['name'];
                            $item_meta = new WC_Order_Item_Meta($item);
                            if ($meta = $item_meta->display(true, true)) {
                                $item_name .= ' ( ' . $meta . ' )';
                            }
                            // apply_filters to item price so we can filter this if needed
                            $hygglig_item_price_including_tax = $order->get_item_total($item, true);
                            $item_price = apply_filters('hygglig_item_price_including_tax', $hygglig_item_price_including_tax);
                            // Get SKU or product id [TEMP ONLY USE ID]
                            $reference = $_product->id;
                            //If variation of product - add ID
                            if ($item['variation_id']) {
                                $reference .= $item['variation_id'];
                            }
                            //Get product description
                            $product_description = trim(get_post($item['product_id'])->post_content);
                            //Fix desc
                            if (strlen($product_description) == 0) {
                                //Empty
                                $product_description = "Ingen beskrivning tillgänglig";
                            } else {
                                //Begränsa längd
                                $product_description = mb_substr($product_description, 0, 149);
                            }
                            $item_price = number_format($order->get_item_total($item, true) * 100, 0, '', '');
                            $cart[] = array('ArticleNumber' => $reference, 'ArticleName' => strip_tags($item_name), 'Description' => $product_description, 'Quantity' => intval($item['qty'] * 100), 'Price' => (int) $item_price, 'VAT' => intval($item_tax_percentage . '00'));
                            $totalAmount += $item_price * (int) $item['qty'];
                        }
                        // End if qty
                    }
                    // End foreach
                }
                // End if sizeof get_items()
                // Shipping
                if ($order->get_total_shipping() > 0) {
                    // We manually calculate the tax percentage here
                    if ($order->get_total_shipping() > 0) {
                        // Calculate tax percentage
                        $shipping_tax_percentage = round($order->get_shipping_tax() / $order->get_total_shipping(), 2) * 100;
                    } else {
                        $shipping_tax_percentage = 00;
                    }
                    $shipping_price = number_format(($order->get_total_shipping() + $order->get_shipping_tax()) * 100, 0, '', '');
                    $cart[] = array('ArticleNumber' => '999', 'ArticleName' => $order->get_shipping_method(), 'Description' => $order->get_shipping_method(), 'Quantity' => 100, 'Price' => intval($shipping_price), 'VAT' => intval($shipping_tax_percentage . '00'));
                    $totalAmount += $shipping_price;
                }
                // Shared secret
                $sharedSecret = strtoupper($this->hygglig_secret);
                //Checkout API
                $startCheckoutAPI = $this->hygglig_server . 'StartCheckout';
                //Get plugin dir
                $create['MerchantKey'] = $merchantid;
                $create['Checksum'] = $startCheckoutCheckSum = SHA1($totalAmount * 100 . $sharedSecret);
                $create['SuccessURL'] = $this->hygglig_checkout_thanks_url . '?sid=' . $order_id;
                $create['CheckoutURL'] = $this->hygglig_checkout_url;
                $create['PushNotificationURL'] = HYGGLIG_URL . 'woo-includes/callback.php';
                $create['TermsURL'] = $this->terms_url;
                $create['OrderReference'] = (string) $order_id;
                $create['Currency'] = $this->hygglig_currency;
                //IF logged in user with ness~data. Add to checkout
                if ($current_user->user_email && $woocommerce->customer->get_shipping_postcode()) {
                    $create['Email'] = $current_user->user_email;
                    $create['Postcode'] = $woocommerce->customer->get_shipping_postcode();
                }
                foreach ($cart as $item) {
                    $create['Articles'][] = $item;
                }
                /*
                echo "<pre>";
                print_r($create);
                echo "</pre>";
                */
                //exit;
                // Setup cURL
                $ch = curl_init($startCheckoutAPI);
                curl_setopt_array($ch, array(CURLOPT_POST => TRUE, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPHEADER => array('Content-Type: application/json'), CURLOPT_POSTFIELDS => json_encode($create)));
                // Send the request
                $response = curl_exec($ch);
                // Check for errors
                if ($response === FALSE) {
                    die(curl_error($ch));
                } else {
                    //Close Curl
                    curl_close($ch);
                    // Decode the response
                    $responseData = json_decode($response, true);
                    /*
                    echo "<pre>";
                    print_r($responseData);
                    echo "</pre>";						
                    */
                    //exit;
                    // Store the response as a TOKEN
                    $token = strtoupper($responseData['Token']);
                    //Next part is to ask for the iFrame
                    $getiframeCheckSum = SHA1(strtoupper($token . $sharedSecret));
                    $getiframeAPI = $this->hygglig_server . 'GetIFrame';
                    //Destroy previous $create
                    $create = array();
                    //GetIFrame
                    $create['MerchantKey'] = $merchantid;
                    $create['Checksum'] = $getiframeCheckSum;
                    $create['Token'] = $token;
                    // Setup cURL
                    $ch = curl_init($getiframeAPI);
                    curl_setopt_array($ch, array(CURLOPT_POST => TRUE, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPHEADER => array('Content-Type: application/json; encoding=utf-8'), CURLOPT_POSTFIELDS => json_encode($create)));
                    // Send the request
                    $response = curl_exec($ch);
                    // Check for errors
                    if ($response === FALSE) {
                        die(curl_error($ch));
                    } else {
                        //Close Curl
                        curl_close($ch);
                        //Clear old result
                        $responseData = null;
                        //Echo result
                        $responseData = json_decode($response, true, 1024, JSON_BIGINT_AS_STRING);
                    }
                }
                $text = $responseData["HtmlText"];
                // Display checkout
                ob_start();
                // Add CSS
                echo '<link href="' . HYGGLIG_URL . 'css/hygglig.css" rel="stylesheet">';
                if ($this->show_order_review == 'visatopp') {
                    echo '<div id="order_review" class="woocommerce-checkout-review-order">';
                    woocommerce_order_review();
                    echo '</div><br>';
                }
                //Hygglig iFrame render
                echo $text;
                if ($this->show_order_review == 'visaunder') {
                    echo '<br><div id="order_review" class="woocommerce-checkout-review-order">';
                    woocommerce_order_review();
                    echo '</div>';
                }
                //Close WooCommerce Div and Form
                echo "</form></div>";
                //Add update code
                ?>
<script>
//Script that do AJAX req and then based on answer updates checkout
window.onload = function() {
	if (window.jQuery) {  
		// jQuery is loaded 
		$j=jQuery.noConflict();
		//Do update to store current shipping
		$j.get( window.location.href);
		//Store val
		dataVal = $j('.order-total .amount').text();
		checker(dataVal);
	} 
	else {
		// jQuery is not loaded - implement solution using pure javascript
	}
}

function checker(oldVal){
	if(oldVal == $j('.order-total .amount').text()){
		//Wait and run check again
		setTimeout(function(){ checker(oldVal); }, 50);	
	}
	else{
		//Easiest way to get WC to update everything
		$j.get( window.location.href, function( ) {
			//Do update
			update($j('.order-total .amount').text());
		});
	}
	
}

//Update checkout
function update(oldVal){
	$j.ajax({url:'<?php 
                echo HYGGLIG_URL;
                ?>
woo-includes/hygglig-order-update.php?token=<?php 
                echo $token;
                ?>
&hid=<?php 
                echo $order_id;
                ?>
' , success: function(){	
		_hyggligCheckout.updateHygglig();	
		//And start update checker
		setTimeout(function(){ checker(oldVal); }, 50);	
	}});
}			
</script>
					<?php 
                return ob_get_clean();
            }
            // End if sizeof cart
        }
        // End if isset($_GET['token'])
    }