function meta_box()
 {
     global $woocommerce, $post;
     $order = new WC_Order($post->ID);
     $order_discount = $order->get_total_discount();
     $order_tax = $order->get_total_tax();
     $order_subtotal = $order->get_subtotal_to_display();
     $order_total = $order->get_formatted_order_total();
     get_payment_gateway_fields('paypal');
     woocommerce_wp_select(array('id' => 'payment_type', 'label' => '', 'value' => 'default', 'options' => ins_get_payment_methods(), 'class' => 'chosen-select'));
     woocommerce_wp_select(array('id' => 'add_coupon', 'label' => '', 'value' => 'default', 'options' => ins_get_coupons(), 'class' => 'chosen-select'));
     woocommerce_wp_text_input(array('id' => 'sub_total', 'label' => __('Order Subtotal', 'instore'), 'placeholder' => 0.0, 'value' => $order_subtotal));
     woocommerce_wp_text_input(array('id' => 'order_tax', 'label' => __('Order Tax', 'instore'), 'placeholder' => 0.0, 'value' => $order_tax));
     woocommerce_wp_text_input(array('id' => 'applied_discount', 'label' => __('Applied Discount', 'instore'), 'placeholder' => 0.0, 'value' => $order_discount));
 }
 /**
  * Charge Payment
  * Method ini digunakan untuk mendapatkan link halaman pembayaran Veritrans
  * dengan mengirimkan JSON yang berisi data transaksi
  */
 function charge_payment($order_id)
 {
     global $woocommerce;
     $order_items = array();
     $cart = $woocommerce->cart;
     $order = new WC_Order($order_id);
     Veritrans_Config::$isProduction = $this->environment == 'production' ? true : false;
     Veritrans_Config::$serverKey = Veritrans_Config::$isProduction ? $this->server_key_v2_production : $this->server_key_v2_sandbox;
     Veritrans_Config::$is3ds = $this->enable_3d_secure == 'yes' ? true : false;
     Veritrans_Config::$isSanitized = $this->enable_sanitization == 'yes' ? true : false;
     $params = array('transaction_details' => array('order_id' => $order_id, 'gross_amount' => 0), 'vtweb' => array());
     $enabled_payments = array();
     if ($this->enable_credit_card == 'yes') {
         $enabled_payments[] = 'credit_card';
     }
     if ($this->enable_mandiri_clickpay == 'yes') {
         $enabled_payments[] = 'mandiri_clickpay';
     }
     if ($this->enable_cimb_clicks == 'yes') {
         $enabled_payments[] = 'cimb_clicks';
     }
     if ($this->enable_permata_va == 'yes') {
         $enabled_payments[] = 'bank_transfer';
     }
     if ($this->enable_bri_epay == 'yes') {
         $enabled_payments[] = 'bri_epay';
     }
     if ($this->enable_telkomsel_cash == 'yes') {
         $enabled_payments[] = 'telkomsel_cash';
     }
     if ($this->enable_xl_tunai == 'yes') {
         $enabled_payments[] = 'xl_tunai';
     }
     if ($this->enable_mandiri_bill == 'yes') {
         $enabled_payments[] = 'echannel';
     }
     if ($this->enable_bbmmoney == 'yes') {
         $enabled_payments[] = 'bbm_money';
     }
     if ($this->enable_indomaret == 'yes') {
         $enabled_payments[] = 'cstore';
     }
     if ($this->enable_indosat_dompetku == 'yes') {
         $enabled_payments[] = 'indosat_dompetku';
     }
     if ($this->enable_mandiri_ecash == 'yes') {
         $enabled_payments[] = 'mandiri_ecash';
     }
     $params['vtweb']['enabled_payments'] = $enabled_payments;
     $customer_details = array();
     $customer_details['first_name'] = $order->billing_first_name;
     $customer_details['last_name'] = $order->billing_last_name;
     $customer_details['email'] = $order->billing_email;
     $customer_details['phone'] = $order->billing_phone;
     $billing_address = array();
     $billing_address['first_name'] = $order->billing_first_name;
     $billing_address['last_name'] = $order->billing_last_name;
     $billing_address['address'] = $order->billing_address_1;
     $billing_address['city'] = $order->billing_city;
     $billing_address['postal_code'] = $order->billing_postcode;
     $billing_address['phone'] = $order->billing_phone;
     $billing_address['country_code'] = strlen($this->convert_country_code($order->billing_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
     $customer_details['billing_address'] = $billing_address;
     $customer_details['shipping_address'] = $billing_address;
     if (isset($_POST['ship_to_different_address'])) {
         $shipping_address = array();
         $shipping_address['first_name'] = $order->shipping_first_name;
         $shipping_address['last_name'] = $order->shipping_last_name;
         $shipping_address['address'] = $order->shipping_address_1;
         $shipping_address['city'] = $order->shipping_city;
         $shipping_address['postal_code'] = $order->shipping_postcode;
         $shipping_address['phone'] = $order->billing_phone;
         $shipping_address['country_code'] = strlen($this->convert_country_code($order->shipping_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
         $customer_details['shipping_address'] = $shipping_address;
     }
     $params['customer_details'] = $customer_details;
     //error_log(print_r($params,true));
     $items = array();
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if ($item['qty']) {
                 $product = $order->get_product_from_item($item);
                 $veritrans_item = array();
                 $veritrans_item['id'] = $item['product_id'];
                 $veritrans_item['price'] = $order->get_item_subtotal($item, false);
                 $veritrans_item['quantity'] = $item['qty'];
                 $veritrans_item['name'] = $item['name'];
                 $items[] = $veritrans_item;
             }
         }
     }
     // Shipping fee
     if ($order->get_total_shipping() > 0) {
         $items[] = array('id' => 'shippingfee', 'price' => $order->get_total_shipping(), 'quantity' => 1, 'name' => 'Shipping Fee');
     }
     // Tax
     if ($order->get_total_tax() > 0) {
         $items[] = array('id' => 'taxfee', 'price' => $order->get_total_tax(), 'quantity' => 1, 'name' => 'Tax');
     }
     // Discount
     if ($cart->get_cart_discount_total() > 0) {
         $items[] = array('id' => 'totaldiscount', 'price' => $cart->get_cart_discount_total() * -1, 'quantity' => 1, 'name' => 'Total Discount');
     }
     // Fees
     if (sizeof($order->get_fees()) > 0) {
         $fees = $order->get_fees();
         $i = 0;
         foreach ($fees as $item) {
             $items[] = array('id' => 'itemfee' . $i, 'price' => $item['line_total'], 'quantity' => 1, 'name' => $item['name']);
             $i++;
         }
     }
     $total_amount = 0;
     // error_log('print r items[]' . print_r($items,true)); //debugan
     foreach ($items as $item) {
         $total_amount += $item['price'] * $item['quantity'];
         // error_log('|||| Per item[]' . print_r($item,true)); //debugan
     }
     error_log('order get total = ' . $order->get_total());
     error_log('total amount = ' . $total_amount);
     $params['transaction_details']['gross_amount'] = $total_amount;
     // sift through the entire item to ensure that currency conversion is applied
     if (get_woocommerce_currency() != 'IDR') {
         foreach ($items as &$item) {
             $item['price'] = $item['price'] * $this->to_idr_rate;
         }
         unset($item);
         $params['transaction_details']['gross_amount'] *= $this->to_idr_rate;
     }
     $params['item_details'] = $items;
     $woocommerce->cart->empty_cart();
     return Veritrans_VtWeb::getRedirectionUrl($params);
 }
 /**
  * Get line items to send to paypal
  *
  * @param  WC_Order $order
  * @return array on success, or false when it is not possible to send line items
  */
 private function get_line_items($order)
 {
     // Do not send lines for tax inclusive prices
     if ('yes' === get_option('woocommerce_calc_taxes') && 'yes' === get_option('woocommerce_prices_include_tax')) {
         return false;
     }
     // Do not send lines when order discount is present, or too many line items in the order.
     if ($order->get_order_discount() > 0 || sizeof($order->get_items()) + sizeof($order->get_fees()) >= 9) {
         return false;
     }
     $item_loop = 0;
     $args = array();
     $args['tax_cart'] = $order->get_total_tax();
     // Products
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if (!$item['qty']) {
                 continue;
             }
             $item_loop++;
             $product = $order->get_product_from_item($item);
             $item_name = $item['name'];
             $item_meta = new WC_Order_Item_Meta($item['item_meta']);
             if ($meta = $item_meta->display(true, true)) {
                 $item_name .= ' ( ' . $meta . ' )';
             }
             $args['item_name_' . $item_loop] = $this->paypal_item_name($item_name);
             $args['quantity_' . $item_loop] = $item['qty'];
             $args['amount_' . $item_loop] = $order->get_item_subtotal($item, false);
             if ($args['amount_' . $item_loop] < 0) {
                 return false;
                 // Abort - negative line
             }
             if ($product->get_sku()) {
                 $args['item_number_' . $item_loop] = $product->get_sku();
             }
         }
     }
     // Discount
     if ($order->get_cart_discount() > 0) {
         $args['discount_amount_cart'] = round($order->get_cart_discount(), 2);
     }
     // Fees
     if (sizeof($order->get_fees()) > 0) {
         foreach ($order->get_fees() as $item) {
             $item_loop++;
             $args['item_name_' . $item_loop] = $this->paypal_item_name($item['name']);
             $args['quantity_' . $item_loop] = 1;
             $args['amount_' . $item_loop] = $item['line_total'];
             if ($args['amount_' . $item_loop] < 0) {
                 return false;
                 // Abort - negative line
             }
         }
     }
     // Shipping Cost item - paypal only allows shipping per item, we want to send shipping for the order
     if ($order->get_total_shipping() > 0) {
         $item_loop++;
         $args['item_name_' . $item_loop] = $this->paypal_item_name(sprintf(__('Shipping via %s', 'woocommerce'), $order->get_shipping_method()));
         $args['quantity_' . $item_loop] = '1';
         $args['amount_' . $item_loop] = number_format($order->get_total_shipping(), 2, '.', '');
     }
     return $args;
 }
/**
 * Insert a order in sync table once a order is created
 *
 * @global object $wpdb
 * @param int $order_id
 */
function dokan_sync_insert_order($order_id)
{
    global $wpdb;
    $order = new WC_Order($order_id);
    $seller_id = dokan_get_seller_id_by_order($order_id);
    $percentage = dokan_get_seller_percentage($seller_id);
    $order_total = $order->get_total();
    $order_shipping = $order->get_total_shipping();
    $order_tax = $order->get_total_tax();
    $extra_cost = $order_shipping + $order_tax;
    $order_cost = $order_total - $extra_cost;
    $order_status = $order->post_status;
    $net_amount = $order_cost * $percentage / 100 + $extra_cost;
    $net_amount = apply_filters('dokan_order_net_amount', $net_amount, $order);
    $wpdb->insert($wpdb->prefix . 'dokan_orders', array('order_id' => $order_id, 'seller_id' => $seller_id, 'order_total' => $order_total, 'net_amount' => $net_amount, 'order_status' => $order_status), array('%d', '%d', '%f', '%f', '%s'));
}
 /**
  * Perform a credit card transaction request
  *
  * @param Elavon_VM_API $elavon_client elavon api client
  * @param WC_Order $order the order
  *
  * @return SimpleXMLElement response, or false on error
  */
 private function transaction_request($elavon_client, $order)
 {
     $request = new stdClass();
     $request->ssl_test_mode = $this->is_test_mode() ? "true" : "false";
     $request->ssl_transaction_type = $this->auth_settle() ? "ccsale" : "ccauthonly";
     $request->ssl_invoice_number = ltrim($order->get_order_number(), _x('#', 'hash before order number', WC_Elavon_VM::TEXT_DOMAIN));
     $request->ssl_card_number = $this->get_post('elavon_vm_accountNumber');
     $request->ssl_exp_date = $this->get_post('elavon_vm_expirationMonth') . substr($this->get_post('elavon_vm_expirationYear'), -2);
     $request->ssl_amount = number_format($order->get_total(), 2, '.', '');
     $request->ssl_salestax = number_format($order->get_total_tax(), 2);
     // Note:  this is a fix suggested by Elavon that should work "90%" of the time.  We'll go with it for now, until someone really needs a POID field collected on the frontend
     $request->ssl_customer_code = substr($this->get_post('elavon_vm_accountNumber'), -4);
     $request->ssl_cvv2cvc2_indicator = $this->cvv_required() ? "1" : "0";
     if ($this->cvv_required()) {
         $request->ssl_cvv2cvc2 = $this->get_post('elavon_vm_cvNumber');
     }
     $request->ssl_first_name = $order->billing_first_name;
     $request->ssl_last_name = $order->billing_last_name;
     $request->ssl_company = $order->billing_company;
     $request->ssl_avs_address = $order->billing_address_1;
     $request->ssl_address2 = $order->billing_address_2;
     $request->ssl_city = $order->billing_city;
     $request->ssl_state = $order->billing_state;
     $request->ssl_avs_zip = $order->billing_postcode;
     $request->ssl_country = $order->billing_country;
     // country code
     $request->ssl_email = $order->billing_email;
     $request->ssl_phone = preg_replace('/[^0-9]/', '', $order->billing_phone);
     $request->ssl_cardholder_ip = $_SERVER['REMOTE_ADDR'];
     return $elavon_client->transaction_request($request);
 }
function orderpost($orderId)
{
    global $wpdb;
    $testMode = get_option('linksync_test');
    $LAIDKey = get_option('linksync_laid');
    $apicall = new linksync_class($LAIDKey, $testMode);
    //Checking for already sent Order
    $sentOrderIds = get_option('linksync_sent_order_id');
    if (isset($sentOrderIds)) {
        if (!empty($sentOrderIds)) {
            $order_id_array = unserialize($sentOrderIds);
        } else {
            $order_id_array = array();
        }
        if (!in_array($orderId, $order_id_array)) {
            $order = new WC_Order($orderId);
            if ($order->post_status == get_option('order_status_wc_to_vend')) {
                update_option('linksync_sent_order_id', serialize(array_merge($order_id_array, array($orderId))));
                $order_no = $order->get_order_number();
                if (strpos($order_no, '#') !== false) {
                    $order_no = str_replace('#', '', $order_no);
                }
                $get_total = $order->get_total();
                $get_user = $order->get_user();
                $comments = $order->post->post_excerpt;
                $primary_email_address = $get_user->data->user_email;
                $currency = $order->get_order_currency();
                $shipping_method = $order->get_shipping_method();
                $order_total = $order->get_order_item_totals();
                $transaction_id = $order->get_transaction_id();
                $taxes_included = false;
                $total_discount = $order->get_total_discount();
                $total_quantity = 0;
                $registerDb = get_option('wc_to_vend_register');
                $vend_uid = get_option('wc_to_vend_user');
                $total_tax = $order->get_total_tax();
                // Geting Payment object details
                if (isset($order_total['payment_method']['value']) && !empty($order_total['payment_method']['value'])) {
                    $wc_payment = get_option('wc_to_vend_payment');
                    if (isset($wc_payment) && !empty($wc_payment)) {
                        $total_payments = explode(",", $wc_payment);
                        foreach ($total_payments as $mapped_payment) {
                            $exploded_mapped_payment = explode("|", $mapped_payment);
                            if (isset($exploded_mapped_payment[1]) && !empty($exploded_mapped_payment[1]) && isset($exploded_mapped_payment[0]) && !empty($exploded_mapped_payment[0])) {
                                if ($exploded_mapped_payment[1] == $order_total['payment_method']['value']) {
                                    $vend_payment_data = explode("%%", $exploded_mapped_payment[0]);
                                    if (isset($vend_payment_data[0])) {
                                        $payment_method = $vend_payment_data[0];
                                    }
                                    if (isset($vend_payment_data[1])) {
                                        $payment_method_id = $vend_payment_data[1];
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    $payment = array("retailer_payment_type_id" => isset($payment_method_id) ? $payment_method_id : null, "amount" => isset($get_total) ? $get_total : 0, "method" => isset($payment_method) ? $payment_method : null, "transactionNumber" => isset($transaction_id) ? $transaction_id : null);
                }
                $export_user_details = get_option('wc_to_vend_export');
                if (isset($export_user_details) && !empty($export_user_details)) {
                    if ($export_user_details == 'customer') {
                        //woocommerce filter
                        $billingAddress_filter = apply_filters('woocommerce_order_formatted_billing_address', array('firstName' => $order->billing_first_name, 'lastName' => $order->billing_last_name, 'phone' => $order->billing_phone, 'street1' => $order->billing_address_1, 'street2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'postalCode' => $order->billing_postcode, 'country' => $order->billing_country, 'company' => $order->billing_company, 'email_address' => $order->billing_email), $order);
                        $billingAddress = array('firstName' => $billingAddress_filter['firstName'], 'lastName' => $billingAddress_filter['lastName'], 'phone' => $billingAddress_filter['phone'], 'street1' => $billingAddress_filter['street1'], 'street2' => $billingAddress_filter['street2'], 'city' => $billingAddress_filter['city'], 'state' => $billingAddress_filter['state'], 'postalCode' => $billingAddress_filter['postalCode'], 'country' => $billingAddress_filter['country'], 'company' => $billingAddress_filter['company'], 'email_address' => $billingAddress_filter['email_address']);
                        $deliveryAddress_filter = apply_filters('woocommerce_order_formatted_shipping_address', array('firstName' => $order->shipping_first_name, 'lastName' => $order->shipping_last_name, 'phone' => $order->shipping_phone, 'street1' => $order->shipping_address_1, 'street2' => $order->shipping_address_2, 'city' => $order->shipping_city, 'state' => $order->shipping_state, 'postalCode' => $order->shipping_postcode, 'country' => $order->shipping_country, 'company' => $order->shipping_company), $order);
                        $deliveryAddress = array('firstName' => $deliveryAddress_filter['firstName'], 'lastName' => $deliveryAddress_filter['lastName'], 'phone' => $deliveryAddress_filter['phone'], 'street1' => $deliveryAddress_filter['street1'], 'street2' => $deliveryAddress_filter['street2'], 'city' => $deliveryAddress_filter['city'], 'state' => $deliveryAddress_filter['state'], 'postalCode' => $deliveryAddress_filter['postalCode'], 'country' => $deliveryAddress_filter['country'], 'company' => $deliveryAddress_filter['company']);
                        $primary_email = isset($primary_email_address) ? $primary_email_address : $billingAddress['email_address'];
                        unset($billingAddress['email_address']);
                    }
                }
                $vend_user_detail = get_option('wc_to_vend_user');
                if (isset($vend_user_detail) && !empty($vend_user_detail)) {
                    $user = explode('|', $vend_user_detail);
                    $vend_uid = isset($user[0]) ? $user[0] : null;
                    $vend_username = isset($user[1]) ? $user[1] : null;
                }
                //Ordered product(s)
                $items = $order->get_items();
                $taxes = $order->get_taxes();
                foreach ($items as $item) {
                    foreach ($taxes as $tax_label) {
                        $sql = mysql_query("SELECT  tax_rate_id FROM  `" . $wpdb->prefix . "woocommerce_tax_rates` WHERE  tax_rate_name='" . $tax_label['label'] . "' AND tax_rate_class='" . $item['item_meta']['_tax_class'][0] . "'");
                        if (mysql_num_rows($sql) != 0) {
                            $tax_classes = linksync_tax_classes($tax_label['label'], $item['item_meta']['_tax_class'][0]);
                            if ($tax_classes['result'] == 'success') {
                                $vend_taxes = explode('/', $tax_classes['tax_classes']);
                            }
                        }
                    }
                    $taxId = isset($vend_taxes[0]) ? $vend_taxes[0] : null;
                    $taxName = isset($vend_taxes[1]) ? $vend_taxes[1] : null;
                    $taxRate = isset($vend_taxes[2]) ? $vend_taxes[2] : null;
                    if (isset($item['variation_id']) && !empty($item['variation_id'])) {
                        $product_id = $item['variation_id'];
                    } else {
                        $product_id = $item['product_id'];
                    }
                    $pro_object = new WC_Product($product_id);
                    $itemtotal = (double) $item['item_meta']['_line_subtotal'][0];
                    if (isset($item['line_subtotal']) && !empty($item['line_subtotal'])) {
                        $product_amount = (double) ($item['line_subtotal'] / $item['qty']);
                    }
                    $discount = (double) $item['item_meta']['_line_subtotal'][0] - (double) $item['item_meta']['_line_total'][0];
                    if (isset($discount) && !empty($discount)) {
                        $discount = (double) ($discount / $item['qty']);
                    }
                    #---------Changes--------#
                    //Product Amount = product org amount - discount amount
                    $product_total_amount = (double) $product_amount - (double) $discount;
                    $product_sku = $pro_object->get_sku();
                    if (isset($product_total_amount) && isset($taxRate) && !empty($product_total_amount) && !empty($taxRate)) {
                        $taxValue = $product_total_amount * $taxRate;
                    }
                    $products[] = array('sku' => $product_sku, 'title' => $item['name'], 'price' => $product_total_amount, 'quantity' => $item['qty'], 'discountAmount' => isset($discount) ? $discount : 0, 'taxName' => isset($taxName) ? $taxName : null, 'taxId' => isset($taxId) ? $taxId : null, 'taxRate' => isset($taxRate) ? $taxRate : null, 'taxValue' => isset($taxValue) ? $taxValue : null, 'discountTitle' => isset($discountTitle) ? $discountTitle : 'sale');
                    $total_quantity += $item['qty'];
                    unset($taxId);
                    unset($taxName);
                    unset($taxRate);
                    unset($taxValue);
                }
                #---------Discount-----#
                //              if (isset($total_discount) && !empty($total_discount)) {
                //                    $taxes_Discount = $apicall->linksync_getTaxes();
                //                    if (isset($taxes_Discount) && !empty($taxes_Discount)) {
                //                        if (!isset($taxes_Discount['errorCode'])) {
                //                            if (isset($taxes_Discount['taxes'])) {
                //                                foreach ($taxes_Discount['taxes'] as $select_tax) {
                //                                    if ($select_tax['name'] == 'GST') {
                //                                        $discountTaxName = $select_tax['name'];
                //                                        $discountTaxId = $select_tax['id'];
                //                                        $discountTaxRate = $select_tax['rate'];
                //                                    }
                //                                }
                //                            }
                //                        }
                //                    }
                //                    if (isset($total_discount)) {
                //                        if (isset($discountTaxRate) && !empty($discountTaxRate)) {
                //                            $taxValue_discount = $discountTaxRate * $total_discount;
                //                        }
                //                    }
                //                    $products[] = array(
                //                        "price" => isset($total_discount) ? $total_discount : null,
                //                        "quantity" => 1,
                //                        "sku" => "vend-discount",
                //                        'taxName' => isset($discountTaxName) ? $discountTaxName : null,
                //                        'taxId' => isset($discountTaxId) ? $discountTaxId : null,
                //                        'taxRate' => isset($discountTaxRate) ? $discountTaxRate : null,
                //                        'taxValue' => isset($taxValue_discount) ? $taxValue_discount : null
                //                    );
                //                    $products[] = array(
                //                        "price" => isset($total_discount) ? $total_discount : null,
                //                        "quantity" => 1,
                //                        "sku" => "vend-discount",
                //                        'taxName' => null,
                //                        'taxId' => null,
                //                        'taxRate' => null,
                //                        'taxValue' => null
                //                    );
                //            }
                #----------Shipping------------#
                foreach ($taxes as $tax_label) {
                    if (isset($tax_label['shipping_tax_amount']) && !empty($tax_label['shipping_tax_amount'])) {
                        $tax_classes = linksync_tax_classes($tax_label['label'], $item['item_meta']['_tax_class'][0]);
                        if ($tax_classes['result'] == 'success') {
                            $vend_taxes = explode('/', $tax_classes['tax_classes']);
                            $taxId_shipping = isset($vend_taxes[0]) ? $vend_taxes[0] : null;
                            $taxName_shipping = isset($vend_taxes[1]) ? $vend_taxes[1] : null;
                            $taxRate_shipping = isset($vend_taxes[2]) ? $vend_taxes[2] : null;
                        }
                    }
                }
                if (isset($shipping_method) && !empty($shipping_method)) {
                    $shipping_cost = $order->get_total_shipping();
                    $shipping_with_tax = $order->get_shipping_tax();
                    if ($shipping_with_tax > 0) {
                        if (isset($shipping_cost) && isset($taxRate_shipping) && !empty($shipping_cost) && !empty($taxRate_shipping)) {
                            $taxValue_shipping = $shipping_cost * $taxRate_shipping;
                        }
                    }
                    $products[] = array("price" => isset($shipping_cost) ? $shipping_cost : null, "quantity" => 1, "sku" => "shipping", 'taxName' => isset($taxName_shipping) ? $taxName_shipping : null, 'taxId' => isset($taxId_shipping) ? $taxId_shipping : null, 'taxRate' => isset($taxRate_shipping) ? $taxRate_shipping : null, 'taxValue' => isset($taxValue_shipping) ? $taxValue_shipping : null);
                }
                //UTC Time
                date_default_timezone_set("UTC");
                $order_created = date("Y-m-d H:i:s", time());
                $OrderArray = array('uid' => isset($vend_uid) ? $vend_uid : null, 'created' => isset($order_created) ? $order_created : null, "orderId" => isset($order_no) ? $order_no : null, "source" => "WooCommerce", 'register_id' => isset($registerDb) ? $registerDb : null, 'user_name' => isset($vend_username) ? $vend_username : null, 'primary_email' => isset($primary_email) && !empty($primary_email) ? $primary_email : null, 'total' => isset($get_total) ? $get_total : 0, 'total_tax' => isset($total_tax) ? $total_tax : 0, 'comments' => isset($comments) ? $comments : null, 'taxes_included' => $taxes_included, 'currency' => isset($currency) ? $currency : 'USD', 'shipping_method' => isset($shipping_method) ? $shipping_method : null, 'payment' => isset($payment) && !empty($payment) ? $payment : null, 'products' => isset($products) && !empty($products) ? $products : null, 'payment_type_id' => isset($payment_method_id) ? $payment_method_id : null, 'billingAddress' => isset($billingAddress) && !empty($billingAddress) ? $billingAddress : null, 'deliveryAddress' => isset($deliveryAddress) && !empty($deliveryAddress) ? $deliveryAddress : null);
                $json = json_encode($OrderArray);
                $apicall->linksync_postOrder($json);
                linksync_class::add('Order Sync Woo to Vend', 'success', 'Woo Order no:' . $order_no, $LAIDKey);
            }
        } else {
            linksync_class::add('Order Sync Woo to Vend', 'Error', 'Already Sent Order', $LAIDKey);
        }
    }
}
    /**
     * Google Analytics eCommerce tracking
     *
     * @access public
     * @param mixed $order_id
     * @return void
     */
    function ecommerce_tracking_code($order_id)
    {
        global $woocommerce;
        if ($this->disable_tracking($this->ga_eeT) || current_user_can("manage_options") || get_post_meta($order_id, "_tracked", true) == 1) {
            return;
        }
        $tracking_id = $this->ga_id;
        if (!$tracking_id) {
            return;
        }
        // Doing eCommerce tracking so unhook standard tracking from the footer
        remove_action("wp_footer", array($this, "ee_settings"));
        // Get the order and output tracking code
        $order = new WC_Order($order_id);
        //Get Applied Coupon Codes
        $coupons_list = '';
        if ($order->get_used_coupons()) {
            $coupons_count = count($order->get_used_coupons());
            $i = 1;
            foreach ($order->get_used_coupons() as $coupon) {
                $coupons_list .= $coupon;
                if ($i < $coupons_count) {
                    $coupons_list .= ', ';
                }
                $i++;
            }
        }
        //get domain name if value is set
        if (!empty($this->ga_Dname)) {
            $set_domain_name = esc_js($this->ga_Dname);
        } else {
            $set_domain_name = "auto";
        }
        //add display features
        if ($this->ga_DF) {
            $ga_display_feature_code = 'ga("require", "displayfeatures");';
        } else {
            $ga_display_feature_code = "";
        }
        //add Pageview on order page if user checked Add Standard UA code
        if ($this->ga_ST) {
            $ga_pageview = 'ga("send", "pageview");';
        } else {
            $ga_pageview = "";
        }
        $code = '(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
			(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
			m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
			})(window,document,"script","//www.google-analytics.com/analytics.js","ga");
                        
			ga("create", "' . esc_js($tracking_id) . '", "' . $set_domain_name . '");
                        ' . $ga_display_feature_code . '
			ga("require", "ec", "ec.js");
                        ' . $ga_pageview . '
                        ';
        // Order items
        if ($order->get_items()) {
            foreach ($order->get_items() as $item) {
                $_product = $order->get_product_from_item($item);
                if (isset($_product->variation_data)) {
                    $categories = esc_js(woocommerce_get_formatted_variation($_product->variation_data, true));
                } else {
                    $out = array();
                    $categories = get_the_terms($_product->id, "product_cat");
                    if ($categories) {
                        foreach ($categories as $category) {
                            $out[] = $category->name;
                        }
                    }
                    $categories = esc_js(join(",", $out));
                }
                //orderpage Prod json
                $orderpage_prod_Array[get_permalink($_product->id)] = array("tvc_id" => esc_html($_product->id), "tvc_i" => esc_js($_product->get_sku() ? $_product->get_sku() : $_product->id), "tvc_n" => esc_js($item["name"]), "tvc_p" => esc_js($order->get_item_total($item)), "tvc_c" => $categories, "tvc_q" => esc_js($item["qty"]));
            }
            //make json for prod meta data on order page
            $this->wc_version_compare("tvc_oc=" . json_encode($orderpage_prod_Array) . ";");
        }
        //get shipping cost based on version >2.1 get_total_shipping() < get_shipping
        if (version_compare($woocommerce->version, "2.1", ">=")) {
            $tvc_sc = $order->get_total_shipping();
        } else {
            $tvc_sc = $order->get_shipping();
        }
        //orderpage transcation data json
        $orderpage_trans_Array = array("id" => esc_js($order->get_order_number()), "affiliation" => esc_js(get_bloginfo('name')), "revenue" => esc_js($order->get_total()), "tax" => esc_js($order->get_total_tax()), "shipping" => esc_js($tvc_sc), "coupon" => $coupons_list);
        //make json for trans data on order page
        $this->wc_version_compare("tvc_td=" . json_encode($orderpage_trans_Array) . ";");
        $code .= '
                //set local currencies
            ga("set", "&cu", tvc_lc);  
            for(var t_item in tvc_oc){
                ga("ec:addProduct", { 
                    "id": tvc_oc[t_item].tvc_i,
                    "name": tvc_oc[t_item].tvc_n, 
                    "category": tvc_oc[t_item].tvc_c,
                    "price": tvc_oc[t_item].tvc_p,
                    "quantity": tvc_oc[t_item].tvc_q,
			});
            }
            ga("ec:setAction","purchase", {
				"id": tvc_td.id,
				"affiliation": tvc_td.affiliation,
				"revenue": tvc_td.revenue,
                                "tax": tvc_td.tax,
				"shipping": tvc_td.shipping,
                                "coupon": tvc_td.coupon
			});
                        
        ga("send", "event", "Enhanced-Ecommerce","load", "order_confirmation", {"nonInteraction": 1});      
    ';
        //check woocommerce version
        $this->wc_version_compare($code);
        update_post_meta($order_id, "_tracked", 1);
    }
 public function WooCommerceProcessTransaction($order_id)
 {
     //affiliates manager code
     WPAM_Logger::log_debug('WooCommerce Integration - Order processed. Order ID: ' . $order_id);
     if (wpam_has_purchase_record($order_id)) {
         WPAM_Logger::log_debug('WooCommerce Integration - Affiliate commission for this transaction was awarded once. No need to process anything.');
         return;
     }
     WPAM_Logger::log_debug('WooCommerce Integration - Checking if affiliate commission needs to be awarded.');
     $order = new WC_Order($order_id);
     $recurring_payment_method = get_post_meta($order_id, '_recurring_payment_method', true);
     if (!empty($recurring_payment_method)) {
         WPAM_Logger::log_debug("WooCommerce Integration - This is a recurring payment order. Subscription payment method: " . $recurring_payment_method);
         WPAM_Logger::log_debug("The commission will be calculated via the recurring payemnt api call.");
         return;
     }
     $order_status = $order->status;
     WPAM_Logger::log_debug("WooCommerce Integration - Order status: " . $order_status);
     if (strtolower($order_status) != "completed" && strtolower($order_status) != "processing") {
         WPAM_Logger::log_debug("WooCommerce Integration - Order status for this transaction is not in a 'completed' or 'processing' state. Commission will not be awarded at this stage.");
         WPAM_Logger::log_debug("WooCommerce Integration - Commission for this transaciton will be awarded when you set the order status to completed or processing.");
         return;
     }
     $total = $order->order_total;
     $shipping = $order->get_total_shipping();
     $tax = $order->get_total_tax();
     WPAM_Logger::log_debug('WooCommerce Integration - Total amount: ' . $total . ', Total shipping: ' . $shipping . ', Total tax: ' . $tax);
     $purchaseAmount = $total - $shipping - $tax;
     $wpam_refkey = get_post_meta($order_id, '_wpam_refkey', true);
     $wpam_id = get_post_meta($order_id, '_wpam_id', true);
     if (!empty($wpam_id)) {
         $wpam_refkey = $wpam_id;
     }
     $wpam_refkey = apply_filters('wpam_woo_override_refkey', $wpam_refkey, $order);
     if (empty($wpam_refkey)) {
         WPAM_Logger::log_debug("WooCommerce Integration - could not get wpam_id/wpam_refkey from cookie. This is not an affiliate sale");
         return;
     }
     $requestTracker = new WPAM_Tracking_RequestTracker();
     WPAM_Logger::log_debug('WooCommerce Integration - awarding commission for order ID: ' . $order_id . '. Purchase amount: ' . $purchaseAmount);
     $requestTracker->handleCheckoutWithRefKey($order_id, $purchaseAmount, $wpam_refkey);
 }
 /**
  * Process the payment and return the result
  *
  * @access public
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $this->init_mijireh();
     $mj_order = new Mijireh_Order();
     $wc_order = new WC_Order($order_id);
     // add items to order
     $items = $wc_order->get_items();
     foreach ($items as $item) {
         $product = $wc_order->get_product_from_item($item);
         if (get_option('woocommerce_prices_include_tax') == 'yes') {
             $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, true, false), $item['qty'], $product->get_sku());
         } else {
             $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, false, true), $item['qty'], $product->get_sku());
         }
     }
     // Handle fees
     $items = $wc_order->get_fees();
     foreach ($items as $item) {
         $mj_order->add_item($item['name'], number_format($item['line_total'], 2, '.', ','), 1, '');
     }
     // add billing address to order
     $billing = new Mijireh_Address();
     $billing->first_name = $wc_order->billing_first_name;
     $billing->last_name = $wc_order->billing_last_name;
     $billing->street = $wc_order->billing_address_1;
     $billing->apt_suite = $wc_order->billing_address_2;
     $billing->city = $wc_order->billing_city;
     $billing->state_province = $wc_order->billing_state;
     $billing->zip_code = $wc_order->billing_postcode;
     $billing->country = $wc_order->billing_country;
     $billing->company = $wc_order->billing_company;
     $billing->phone = $wc_order->billing_phone;
     if ($billing->validate()) {
         $mj_order->set_billing_address($billing);
     }
     // add shipping address to order
     $shipping = new Mijireh_Address();
     $shipping->first_name = $wc_order->shipping_first_name;
     $shipping->last_name = $wc_order->shipping_last_name;
     $shipping->street = $wc_order->shipping_address_1;
     $shipping->apt_suite = $wc_order->shipping_address_2;
     $shipping->city = $wc_order->shipping_city;
     $shipping->state_province = $wc_order->shipping_state;
     $shipping->zip_code = $wc_order->shipping_postcode;
     $shipping->country = $wc_order->shipping_country;
     $shipping->company = $wc_order->shipping_company;
     if ($shipping->validate()) {
         $mj_order->set_shipping_address($shipping);
     }
     // set order name
     $mj_order->first_name = $wc_order->billing_first_name;
     $mj_order->last_name = $wc_order->billing_last_name;
     $mj_order->email = $wc_order->billing_email;
     // set order totals
     $mj_order->total = $wc_order->get_total();
     $mj_order->discount = $wc_order->get_total_discount();
     if (get_option('woocommerce_prices_include_tax') == 'yes') {
         $mj_order->shipping = round($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2);
         $mj_order->show_tax = false;
     } else {
         $mj_order->shipping = round($wc_order->get_total_shipping(), 2);
         $mj_order->tax = $wc_order->get_total_tax();
     }
     // add meta data to identify woocommerce order
     $mj_order->add_meta_data('wc_order_id', $order_id);
     // Set URL for mijireh payment notificatoin - use WC API
     $mj_order->return_url = str_replace('https:', 'http:', add_query_arg('wc-api', 'WC_Gateway_Mijireh', home_url('/')));
     // Identify woocommerce
     $mj_order->partner_id = 'woo';
     try {
         $mj_order->create();
         $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url);
         return $result;
     } catch (Mijireh_Exception $e) {
         wc_add_notice(__('Mijireh error:', 'woocommerce') . $e->getMessage(), 'error');
     }
 }
 /**
  * ConfirmPayment
  *
  * Finalizes the checkout with PayPal's DoExpressCheckoutPayment API
  *
  * @FinalPaymentAmt (double) Final payment amount for the order.
  */
 function ConfirmPayment($FinalPaymentAmt)
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         wc_add_notice(sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'), "error");
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php';
     }
     /*
      * Create PayPal object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? TRUE : FALSE, 'APIUsername' => $this->api_username, 'APIPassword' => $this->api_password, 'APISignature' => $this->api_signature);
     $PayPal = new Angelleye_PayPal($PayPalConfig);
     /*
      * Get data from WooCommerce object
      */
     if (!empty($this->confirm_order_id)) {
         $order = new WC_Order($this->confirm_order_id);
         $invoice_number = preg_replace("/[^0-9,.]/", "", $order->get_order_number());
         if ($order->customer_note) {
             $customer_notes = wptexturize($order->customer_note);
         }
         $shipping_first_name = $order->shipping_first_name;
         $shipping_last_name = $order->shipping_last_name;
         $shipping_address_1 = $order->shipping_address_1;
         $shipping_address_2 = $order->shipping_address_2;
         $shipping_city = $order->shipping_city;
         $shipping_state = $order->shipping_state;
         $shipping_postcode = $order->shipping_postcode;
         $shipping_country = $order->shipping_country;
     }
     // Prepare request arrays
     $DECPFields = array('token' => urlencode($this->get_session('TOKEN')), 'payerid' => urlencode($this->get_session('payer_id')), 'returnfmfdetails' => '', 'giftmessage' => $this->get_session('giftmessage'), 'giftreceiptenable' => $this->get_session('giftreceiptenable'), 'giftwrapname' => $this->get_session('giftwrapname'), 'giftwrapamount' => $this->get_session('giftwrapamount'), 'buyermarketingemail' => '', 'surveyquestion' => '', 'surveychoiceselected' => '', 'allowedpaymentmethod' => '');
     $Payments = array();
     $Payment = array('amt' => number_format($FinalPaymentAmt, 2, '.', ''), 'currencycode' => get_woocommerce_currency(), 'shippingdiscamt' => '', 'insuranceoptionoffered' => '', 'handlingamt' => '', 'desc' => '', 'custom' => '', 'invnum' => $this->invoice_id_prefix . $invoice_number, 'notifyurl' => '', 'shiptoname' => $shipping_first_name . ' ' . $shipping_last_name, 'shiptostreet' => $shipping_address_1, 'shiptostreet2' => $shipping_address_2, 'shiptocity' => $shipping_city, 'shiptostate' => $shipping_state, 'shiptozip' => $shipping_postcode, 'shiptocountrycode' => $shipping_country, 'shiptophonenum' => '', 'notetext' => $this->get_session('customer_notes'), 'allowedpaymentmethod' => '', 'paymentaction' => 'Sale', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '', 'sellerid' => '', 'sellerusername' => '', 'sellerregistrationdate' => '', 'softdescriptor' => '');
     $PaymentOrderItems = array();
     $ctr = 0;
     $ITEMAMT = 0;
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $values) {
             $_product = $order->get_product_from_item($values);
             $qty = absint($values['qty']);
             $sku = $_product->get_sku();
             $values['name'] = html_entity_decode($values['name'], ENT_NOQUOTES, 'UTF-8');
             if ($_product->product_type == 'variation') {
                 if (empty($sku)) {
                     $sku = $_product->parent->get_sku();
                 }
                 $item_meta = new WC_Order_Item_Meta($values['item_meta']);
                 $meta = $item_meta->display(true, true);
                 if (!empty($meta)) {
                     $values['name'] .= " - " . str_replace(", \n", " - ", $meta);
                 }
             }
             /*
              * Set price based on tax option.
              */
             if (get_option('woocommerce_prices_include_tax') == 'yes') {
                 $product_price = $order->get_item_subtotal($values, true, false);
             } else {
                 $product_price = $order->get_item_subtotal($values, false, true);
             }
             $Item = array('name' => $values['name'], 'desc' => '', 'amt' => $product_price, 'number' => $sku, 'qty' => $qty, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
             array_push($PaymentOrderItems, $Item);
             $ITEMAMT += $product_price * $values['qty'];
         }
         /**
          * Add custom Woo cart fees as line items
          */
         foreach (WC()->cart->get_fees() as $fee) {
             $Item = array('name' => $fee->name, 'desc' => '', 'amt' => number_format($fee->amount, 2, '.', ''), 'number' => $fee->id, 'qty' => 1, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
             /**
              * The gift wrap amount actually has its own parameter in
              * DECP, so we don't want to include it as one of the line
              * items.
              */
             if ($Item['number'] != 'gift-wrap') {
                 array_push($PaymentOrderItems, $Item);
                 $ITEMAMT += $fee->amount * $Item['qty'];
             }
             $ctr++;
         }
         /*
          * Get discounts
          */
         if ($order->get_cart_discount() > 0) {
             foreach (WC()->cart->get_coupons('cart') as $code => $coupon) {
                 $Item = array('name' => 'Cart Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', ''));
                 array_push($PaymentOrderItems, $Item);
             }
             $ITEMAMT -= $order->get_cart_discount();
         }
         if ($order->get_order_discount() > 0) {
             foreach (WC()->cart->get_coupons('order') as $code => $coupon) {
                 $Item = array('name' => 'Order Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', ''));
                 array_push($PaymentOrderItems, $Item);
             }
             $ITEMAMT -= $order->get_order_discount();
         }
         /*
          * Set shipping and tax values.
          */
         if (get_option('woocommerce_prices_include_tax') == 'yes') {
             $shipping = $order->get_total_shipping() + $order->get_shipping_tax();
             $tax = 0;
         } else {
             $shipping = $order->get_total_shipping();
             $tax = $order->get_total_tax();
         }
         /*
          * Now that we have all items and subtotals
          * we can fill in necessary values.
          */
         $Payment['itemamt'] = number_format($ITEMAMT, 2, '.', '');
         // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.
         /*
          * Set tax
          */
         if ($tax > 0) {
             $Payment['taxamt'] = number_format($tax, 2, '.', '');
             // Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
         }
         /*
          * Set shipping
          */
         if ($shipping > 0) {
             $Payment['shippingamt'] = number_format($shipping, 2, '.', '');
             // Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
         }
     }
     $Payment['order_items'] = $PaymentOrderItems;
     array_push($Payments, $Payment);
     $UserSelectedOptions = array('shippingcalculationmode' => '', 'insuranceoptionselected' => '', 'shippingoptionisdefault' => '', 'shippingoptionamount' => '', 'shippingoptionname' => '');
     $PayPalRequestData = array('DECPFields' => $DECPFields, 'Payments' => $Payments);
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData);
     /*
      * Log API result
      */
     $this->add_log('Test Mode: ' . $this->testmode);
     $this->add_log('Endpoint: ' . $this->API_Endpoint);
     $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : '';
     $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : '';
     $this->add_log('Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true));
     $this->add_log('Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true));
     /*
      * Error handling
      */
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         $this->remove_session('TOKEN');
     }
     /*
      * Return the class library result array.
      */
     return $PayPalResult;
 }
 function get_payment_xml($order_id)
 {
     global $woocommerce;
     global $product;
     $order = new WC_Order($order_id);
     $Secuitems = '';
     foreach ($order->get_items() as $item) {
         $Options = array();
         foreach ($item as $Attribute => $Value) {
             if (!in_array($Attribute, $this->GetStandardProductFields())) {
                 $Options[$Attribute] = $Value;
             }
         }
         $product = new WC_Product($item['product_id']);
         $Secuitems .= '[' . $item['product_id'] . '|' . $product->get_sku() . '|' . $item['name'];
         if (!empty($Options)) {
             foreach ($Options as $Key => $Value) {
                 if ((string) $Key === 'pa_quantity') {
                     $Key = 'Quantity';
                 }
                 $Secuitems .= ', ' . $Key . ': ' . $Value;
             }
         }
         $Secuitems .= '|' . $this->currency_format($item['line_total'] / $item['qty']) . '|' . $item['qty'] . '|' . $this->currency_format($item['line_total']) . ']';
     }
     $TransactionSubTotal = $this->currency_format($order->get_subtotal());
     $TransactionAmount = $this->currency_format($order->get_total());
     $expirydate = str_replace(array('/', ' '), '', $_POST['UPG_api-card-expiry']);
     $cardnumber = str_replace(array(' ', '-'), '', $_POST['UPG_api-card-number']);
     $cardcv2 = str_replace(array(' ', '-'), '', $_POST['UPG_api-card-cvc']);
     $xmlContrsuct = '<?xml version ="1.0"?>';
     $xmlContrsuct .= '<request>';
     $xmlContrsuct .= '<type>transaction</type>';
     $xmlContrsuct .= '<authtype>authorise</authtype>';
     $xmlContrsuct .= '<authentication>';
     $xmlContrsuct .= '<shreference>' . $this->reference . '</shreference>';
     $xmlContrsuct .= '<checkcode>' . $this->checkcode . '</checkcode>';
     $xmlContrsuct .= '</authentication>';
     $xmlContrsuct .= '<transaction>';
     //Card details
     $xmlContrsuct .= '<cardnumber>' . $cardnumber . '</cardnumber>';
     $xmlContrsuct .= '<cv2>' . $cardcv2 . '</cv2>';
     $xmlContrsuct .= '<cardexpiremonth>' . substr($expirydate, 0, 2) . '</cardexpiremonth>';
     $xmlContrsuct .= '<cardexpireyear>' . substr($expirydate, -2) . '</cardexpireyear>';
     //Cardholder details
     $xmlContrsuct .= '<cardholdersname>' . $order->billing_first_name . ' ' . $order->billing_last_name . '</cardholdersname>';
     $xmlContrsuct .= '<cardholdersemail>' . $order->billing_email . '</cardholdersemail>';
     $xmlContrsuct .= '<cardholderaddr1>' . $order->billing_address_1 . '</cardholderaddr1>';
     $xmlContrsuct .= '<cardholderaddr2>' . $order->billing_address_2 . '</cardholderaddr2>';
     $xmlContrsuct .= '<cardholdercity>' . $order->billing_city . '</cardholdercity>';
     $xmlContrsuct .= '<cardholderstate>' . $order->billing_state . '</cardholderstate>';
     $xmlContrsuct .= '<cardholderpostcode>' . $order->billing_postcode . '</cardholderpostcode>';
     $xmlContrsuct .= '<cardholdercountry>' . $order->billing_country . '</cardholdercountry>';
     $xmlContrsuct .= '<cardholdertelephonenumber>' . $order->billing_phone . '</cardholdertelephonenumber>';
     // Order details
     $xmlContrsuct .= '<orderid>' . $order->id . '</orderid>';
     $xmlContrsuct .= '<subtotal>' . $TransactionSubTotal . '</subtotal>';
     $xmlContrsuct .= '<transactionamount>' . $TransactionAmount . '</transactionamount>';
     $xmlContrsuct .= '<transactioncurrency>' . get_woocommerce_currency() . '</transactioncurrency>';
     $xmlContrsuct .= '<transactiondiscount>' . $this->currency_format($order->get_total_discount()) . '</transactiondiscount>';
     $xmlContrsuct .= '<transactiontax>' . $this->currency_format($order->get_total_tax()) . '</transactiontax>';
     $xmlContrsuct .= '<shippingcharge>' . $this->currency_format($order->get_total_shipping()) . '</shippingcharge>';
     $xmlContrsuct .= '<secuitems><![CDATA[' . $Secuitems . ']]></secuitems>';
     $xmlContrsuct .= '</transaction>';
     $xmlContrsuct .= '</request>';
     return $xmlContrsuct;
 }
 protected function formOrderArray(\WC_Order $order)
 {
     $totalFees = 0;
     foreach ($order->get_fees() as $fee) {
         $totalFees += $fee['line_total'];
     }
     $this->order = array('order_id' => $order->id, 'revenue' => round($order->order_total - $totalFees, wc_get_price_decimals()), 'shipping' => $order->get_total_shipping(), 'tax' => $order->get_total_tax());
     return $this->order;
 }
Esempio n. 13
0
 /**
  * Construye un arreglo con todos los parametros que seran enviados al gateway de PayU Latam
  *
  * @access public
  * @return void
  */
 public function get_params_post($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $currency = get_woocommerce_currency();
     $amount = number_format($order->get_total(), 2, '.', '');
     $signature = md5($this->api_key . '~' . $this->merchant_id . '~' . $order->id . '~' . $amount . '~' . $currency);
     $description = "";
     $products = $order->get_items();
     foreach ($products as $product) {
         $description .= $product['name'] . ',';
     }
     $tax = number_format($order->get_total_tax(), 2, '.', '');
     $taxReturnBase = number_format($amount - $tax, 2, '.', '');
     if ($tax == 0) {
         $taxReturnBase = 0;
     }
     $test = 0;
     if ($this->test == 'yes') {
         $test = 1;
     }
     $parameters_args = array('merchantId' => $this->merchant_id, 'referenceCode' => $order->id, 'description' => trim($description, ','), 'amount' => $amount, 'tax' => $tax, 'taxReturnBase' => $taxReturnBase, 'signature' => $signature, 'accountId' => $this->account_id, 'currency' => $currency, 'buyerEmail' => $order->billing_email, 'test' => $test, 'confirmationUrl' => $this->confirmation_page, 'responseUrl' => $this->response_page, 'shippingAddress' => $order->shipping_address_1, 'shippingCountry' => $order->shipping_country, 'shippingCity' => $order->shipping_city, 'billingAddress' => $order->billing_address_1, 'billingCountry' => $order->billing_country, 'billingCity' => $order->billing_city, 'extra1' => 'WOOCOMMERCE');
     return $parameters_args;
 }
Esempio n. 14
0
/**
 * Insert a order in sync table once a order is created
 *
 * @global object $wpdb
 * @param int $order_id
 * @since 2.4
 */
function dokan_sync_order_table($order_id)
{
    global $wpdb;
    $order = new WC_Order($order_id);
    $seller_id = dokan_get_seller_id_by_order($order_id);
    $percentage = dokan_get_seller_percentage($seller_id);
    //Total calculation
    $order_total = $order->get_total();
    if ($total_refunded = $order->get_total_refunded()) {
        $order_total = $order_total - $total_refunded;
    }
    //Shipping calculation
    $order_shipping = $order->get_total_shipping();
    foreach ($order->get_items() as $item) {
        $total_shipping_refunded = 0;
        if ($shipping_refunded = $order->get_total_refunded_for_item($item['product_id'], 'shipping')) {
            $total_shipping_refunded += $shipping_refunded;
        }
    }
    $order_shipping = $order_shipping - $total_shipping_refunded;
    //Tax calculation
    $order_tax = $order->get_total_tax();
    if ($tax_refunded = $order->get_total_tax_refunded()) {
        $order_tax = $order_tax - $tax_refunded;
    }
    $extra_cost = $order_shipping + $order_tax;
    $order_cost = $order_total - $extra_cost;
    $order_status = $order->post_status;
    $net_amount = $order_cost * $percentage / 100 + $extra_cost;
    $net_amount = apply_filters('dokan_sync_order_net_amount', $net_amount, $order);
    $wpdb->insert($wpdb->prefix . 'dokan_orders', array('order_id' => $order_id, 'seller_id' => $seller_id, 'order_total' => $order_total, 'net_amount' => $net_amount, 'order_status' => $order_status), array('%d', '%d', '%f', '%f', '%s'));
}
/**
 * ecommerce tracking with piwik.
 *
 * @access public
 * @param int $order_id
 * @return void
 */
function woocommerce_ecommerce_tracking_piwik($order_id)
{
    global $woocommerce;
    // Don't track admin
    if (current_user_can('manage_options')) {
        return;
    }
    // Call the Piwik ecommerce function if WP-Piwik is configured to add tracking codes to the page
    $wp_piwik_global_settings = get_option('wp-piwik_global-settings');
    // Return if Piwik settings are not here, or if global is not set
    if (!isset($wp_piwik_global_settings['add_tracking_code']) || !$wp_piwik_global_settings['add_tracking_code']) {
        return;
    }
    if (!isset($GLOBALS['wp_piwik'])) {
        return;
    }
    // Get the order and get tracking code
    $order = new WC_Order($order_id);
    ob_start();
    ?>
	try {
		// Add order items
		<?php 
    if ($order->get_items()) {
        foreach ($order->get_items() as $item) {
            $_product = $order->get_product_from_item($item);
            ?>

			piwikTracker.addEcommerceItem(
				"<?php 
            echo esc_js($_product->get_sku());
            ?>
",			// (required) SKU: Product unique identifier
				"<?php 
            echo esc_js($item['name']);
            ?>
",					// (optional) Product name
				"<?php 
            if (isset($_product->variation_data)) {
                echo esc_js(woocommerce_get_formatted_variation($_product->variation_data, true));
            }
            ?>
",	// (optional) Product category. You can also specify an array of up to 5 categories eg. ["Books", "New releases", "Biography"]
				<?php 
            echo esc_js($order->get_item_total($item));
            ?>
,	// (recommended) Product price
				<?php 
            echo esc_js($item['qty']);
            ?>
 						// (optional, default to 1) Product quantity
			);

		<?php 
        }
    }
    ?>

		// Track order
		piwikTracker.trackEcommerceOrder(
			"<?php 
    echo esc_js($order->get_order_number());
    ?>
",	// (required) Unique Order ID
			<?php 
    echo esc_js($order->get_total());
    ?>
,			// (required) Order Revenue grand total (includes tax, shipping, and subtracted discount)
			false,													// (optional) Order sub total (excludes shipping)
			<?php 
    echo esc_js($order->get_total_tax());
    ?>
,		// (optional) Tax amount
			<?php 
    echo esc_js($order->get_shipping());
    ?>
,		// (optional) Shipping amount
			false 													// (optional) Discount offered (set to false for unspecified parameter)
		);
	} catch( err ) {}
	<?php 
    $code = ob_get_clean();
    $woocommerce->add_inline_js($code);
}
Esempio n. 16
0
 /**
  * Process the payment and return the result
  *
  * @access public
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     global $woocommerce;
     $this->init_mijireh();
     $mj_order = new Mijireh_Order();
     $wc_order = new WC_Order($order_id);
     // add items to order
     $items = $wc_order->get_items();
     foreach ($items as $item) {
         $product = $wc_order->get_product_from_item($item);
         $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item), $item['qty'], $product->get_sku());
     }
     // add billing address to order
     $billing = new Mijireh_Address();
     $billing->first_name = $wc_order->billing_first_name;
     $billing->last_name = $wc_order->billing_last_name;
     $billing->street = $wc_order->billing_address_1;
     $billing->apt_suite = $wc_order->billing_address_2;
     $billing->city = $wc_order->billing_city;
     $billing->state_province = $wc_order->billing_state;
     $billing->zip_code = $wc_order->billing_postcode;
     $billing->country = $wc_order->billing_country;
     $billing->company = $wc_order->billing_company;
     $billing->phone = $wc_order->billing_phone;
     if ($billing->validate()) {
         $mj_order->set_billing_address($billing);
     }
     // add shipping address to order
     $shipping = new Mijireh_Address();
     $shipping->first_name = $wc_order->shipping_first_name;
     $shipping->last_name = $wc_order->shipping_last_name;
     $shipping->street = $wc_order->shipping_address_1;
     $shipping->apt_suite = $wc_order->shipping_address_2;
     $shipping->city = $wc_order->shipping_city;
     $shipping->state_province = $wc_order->shipping_state;
     $shipping->zip_code = $wc_order->shipping_postcode;
     $shipping->country = $wc_order->shipping_country;
     $shipping->company = $wc_order->shipping_company;
     if ($shipping->validate()) {
         $mj_order->set_shipping_address($shipping);
     }
     // set order name
     $mj_order->first_name = $wc_order->billing_first_name;
     $mj_order->last_name = $wc_order->billing_last_name;
     $mj_order->email = $wc_order->billing_email;
     // set order totals
     $mj_order->total = $wc_order->get_order_total();
     $mj_order->tax = $wc_order->get_total_tax();
     $mj_order->discount = $wc_order->get_total_discount();
     $mj_order->shipping = $wc_order->get_shipping();
     // add meta data to identify woocommerce order
     $mj_order->add_meta_data('wc_order_id', $order_id);
     // Set URL for mijireh payment notificatoin - use WC API
     $mj_order->return_url = str_replace('https:', 'http:', add_query_arg('wc-api', 'WC_Mijireh_Checkout', home_url('/')));
     // Identify woocommerce
     $mj_order->partner_id = 'woo';
     try {
         $mj_order->create();
         $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url);
         return $result;
     } catch (Mijireh_Exception $e) {
         $woocommerce->add_error(__('Mijireh error:', 'woocommerce') . $e->getMessage());
     }
 }
 /**
  * Google Analytics eCommerce tracking
  *
  * @access public
  * @param mixed $order_id
  * @return void
  */
 function ecommerce_tracking_code($order_id)
 {
     global $woocommerce;
     if ($this->ga_ecommerce_tracking_enabled == "no" || current_user_can('manage_options') || get_post_meta($order_id, '_ga_tracked', true) == 1) {
         return;
     }
     $tracking_id = $this->ga_id;
     if (!$tracking_id) {
         return;
     }
     // Doing eCommerce tracking so unhook standard tracking from the footer
     remove_action('wp_footer', array($this, 'google_tracking_code'));
     // Get the order and output tracking code
     $order = new WC_Order($order_id);
     $loggedin = is_user_logged_in() ? 'yes' : 'no';
     if (is_user_logged_in()) {
         $user_id = get_current_user_id();
         $current_user = get_user_by('id', $user_id);
         $username = $current_user->user_login;
     } else {
         $user_id = '';
         $username = __('Guest', 'woocommerce');
     }
     if (!empty($this->ga_set_domain_name)) {
         $set_domain_name = "['_setDomainName', '" . esc_js($this->ga_set_domain_name) . "'],";
     } else {
         $set_domain_name = '';
     }
     $code = "\r\n\t\t\tvar _gaq = _gaq || [];\r\n\r\n\t\t\t_gaq.push(\r\n\t\t\t\t['_setAccount', '" . esc_js($tracking_id) . "'], " . $set_domain_name . "\r\n\t\t\t\t['_setCustomVar', 1, 'logged-in', '" . esc_js($loggedin) . "', 1],\r\n\t\t\t\t['_trackPageview']\r\n\t\t\t);\r\n\r\n\t\t\t_gaq.push(['_addTrans',\r\n\t\t\t\t'" . esc_js($order->get_order_number()) . "', // order ID - required\r\n\t\t\t\t'" . esc_js(get_bloginfo('name')) . "',  \t// affiliation or store name\r\n\t\t\t\t'" . esc_js($order->get_total()) . "',   \t    // total - required\r\n\t\t\t\t'" . esc_js($order->get_total_tax()) . "',    // tax\r\n\t\t\t\t'" . esc_js($order->get_shipping()) . "',\t    // shipping\r\n\t\t\t\t'" . esc_js($order->billing_city) . "',       // city\r\n\t\t\t\t'" . esc_js($order->billing_state) . "',      // state or province\r\n\t\t\t\t'" . esc_js($order->billing_country) . "'     // country\r\n\t\t\t]);\r\n\t\t";
     // Order items
     if ($order->get_items()) {
         foreach ($order->get_items() as $item) {
             $_product = $order->get_product_from_item($item);
             $code .= "_gaq.push(['_addItem',";
             $code .= "'" . esc_js($order->get_order_number()) . "',";
             $code .= "'" . esc_js($_product->get_sku() ? __('SKU:', 'woocommerce') . ' ' . $_product->get_sku() : $_product->id) . "',";
             $code .= "'" . esc_js($item['name']) . "',";
             if (isset($_product->variation_data)) {
                 $code .= "'" . esc_js(woocommerce_get_formatted_variation($_product->variation_data, true)) . "',";
             } else {
                 $out = array();
                 $categories = get_the_terms($_product->id, 'product_cat');
                 if ($categories) {
                     foreach ($categories as $category) {
                         $out[] = $category->name;
                     }
                 }
                 $code .= "'" . esc_js(join("/", $out)) . "',";
             }
             $code .= "'" . esc_js($order->get_item_total($item, true, true)) . "',";
             $code .= "'" . esc_js($item['qty']) . "'";
             $code .= "]);";
         }
     }
     $code .= "\r\n\t\t\t_gaq.push(['_trackTrans']); \t\t\t\t\t// submits transaction to the Analytics servers\r\n\r\n\t\t\t(function() {\r\n\t\t\t\tvar ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\r\n\t\t\t\tga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\r\n\t\t\t\tvar s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\r\n\t\t\t})();\r\n\t\t";
     echo '<script type="text/javascript">' . $code . '</script>';
     update_post_meta($order_id, '_ga_tracked', 1);
 }
Esempio n. 18
0
/**
 * ecommerce tracking with piwik
 */
function woocommerce_ecommerce_tracking_piwik($order_id)
{
    global $woocommerce;
    if (is_admin()) {
        return;
    }
    // Don't track admin
    // Call the Piwik ecommerce function if WP-Piwik is configured to add tracking codes to the page
    $wp_piwik_global_settings = get_option('wp-piwik_global-settings');
    // Return if Piwik settings are not here, or if global is not set
    if (!isset($wp_piwik_global_settings['add_tracking_code']) || !$wp_piwik_global_settings['add_tracking_code']) {
        return;
    }
    if (!isset($GLOBALS['wp_piwik'])) {
        return;
    }
    // Remove WP-Piwik from wp_footer and run it here instead, to get Piwik
    // loaded *before* we do our ecommerce tracking calls
    remove_action('wp_footer', array($GLOBALS['wp_piwik'], 'footer'));
    $GLOBALS['wp_piwik']->footer();
    // Get the order and output tracking code
    $order = new WC_Order($order_id);
    ?>
	<script type="text/javascript">
	try {
		// Add order items
		<?php 
    if ($order->get_items()) {
        foreach ($order->get_items() as $item) {
            $_product = $order->get_product_from_item($item);
            ?>
			piwikTracker.addEcommerceItem(
				"<?php 
            echo $_product->sku;
            ?>
",	// (required) SKU: Product unique identifier
				"<?php 
            echo $item['name'];
            ?>
",		// (optional) Product name
				"<?php 
            if (isset($_product->variation_data)) {
                echo woocommerce_get_formatted_variation($_product->variation_data, true);
            }
            ?>
",	// (optional) Product category. You can also specify an array of up to 5 categories eg. ["Books", "New releases", "Biography"]
				<?php 
            echo $item['line_cost'] / $item['qty'];
            ?>
,		// (recommended) Product price
				<?php 
            echo $item['qty'];
            ?>
 		// (optional, default to 1) Product quantity
			);
		<?php 
        }
    }
    ?>
		// Track order
		piwikTracker.trackEcommerceOrder(
			"<?php 
    echo $order_id;
    ?>
",		// (required) Unique Order ID
			<?php 
    echo $order->order_total;
    ?>
,	// (required) Order Revenue grand total (includes tax, shipping, and subtracted discount)
			false,					// (optional) Order sub total (excludes shipping)
			<?php 
    echo $order->get_total_tax();
    ?>
,	// (optional) Tax amount
			<?php 
    echo $order->get_shipping();
    ?>
,	// (optional) Shipping amount
			false 					// (optional) Discount offered (set to false for unspecified parameter)
		);
	} catch( err ) {}
	</script>
	<?php 
}
Esempio n. 19
0
 function charge_payment($order_id)
 {
     global $woocommerce;
     $order_items = array();
     $order = new WC_Order($order_id);
     MEOWallet_Config::$isProduction = $this->environment == 'production' ? TRUE : FALSE;
     MEOWallet_Config::$apikey = MEOWallet_Config::$isProduction ? $this->apikey_live : $this->apikey_sandbox;
     //MEOWallet_Config::$isTuned = 'yes';
     $params = array('payment' => array('client' => array('name' => $order->billing_first_name . ' ' . $order->billing_last_name, 'email' => $_POST['billing_email'], 'address' => array('country' => $_POST['billing_country'], 'address' => $_POST['billing_address_1'], 'city' => $_POST['billing_city'], 'postalcode' => $_POST['billing_postcode'])), 'amount' => $order->get_total(), 'currency' => 'EUR', 'items' => $items, 'url_confirm' => get_permalink(woocommerce_get_page_id('shop')) . '?' . $post_result_array->id, 'url_cancel' => get_permalink(woocommerce_get_page_id('shop')) . '?' . $post_result_array->id));
     $client_details = array();
     $client_details['name'] = $_POST['billing_first_name'] . ' ' . $_POST['billing_last_name'];
     $client_details['email'] = $_POST['billing_email'];
     //$client_details['address'] = $client_address;
     $client_address = array();
     $client_address['country'] = $_POST['billing_country'];
     $client_address['address'] = $_POST['billing_address_1'];
     $client_address['city'] = $_POST['billing_city'];
     $client_address['postalcode'] = $_POST['billing_postcode'];
     //$params['payment']['client'] = $client_details;
     //$params['payment']['client']['address'] = $client_address;
     $items = array();
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if ($item['qty']) {
                 $product = $order->get_product_from_item($item);
                 $client_items = array();
                 $client_items['client']['id'] = $item['id'];
                 $client_item['client']['name'] = $item['name'];
                 $client_items['client']['description'] = $item['name'];
                 $client_item['client']['qt'] = $item['qty'];
                 $items['client'][] = $client_items;
             }
         }
     }
     if ($order->get_total_shipping() > 0) {
         $items[] = array('id' => 'shippingfee', 'price' => $order->get_total_shipping(), 'quantity' => 1, 'name' => 'Shipping Fee');
     }
     if ($order->get_total_tax() > 0) {
         $items[] = array('id' => 'taxfee', 'price' => $order->get_total_tax(), 'quantity' => 1, 'name' => 'Tax');
     }
     if ($order->get_order_discount() > 0) {
         $items[] = array('id' => 'totaldiscount', 'price' => $order->get_total_discount() * -1, 'quantity' => 1, 'name' => 'Total Discount');
     }
     if (sizeof($order->get_fees()) > 0) {
         $fees = $order->get_fees();
         $i = 0;
         foreach ($fees as $item) {
             $items[] = array('id' => 'itemfee' . $i, 'price' => $item['line_total'], 'quantity' => 1, 'name' => $item['name']);
             $i++;
         }
     }
     //$params['client']['amount'] = $order->get_total();
     //if (get_woocommerce_currency() != 'EUR'){
     //	foreach ($items as &$item){
     //		$item['price'] = $item['price'] * $this->to_euro_rate;
     //	}
     //	unset($item);
     //	$params['payment']['amount'] *= $this->to_euro_rate;
     //}
     //$params['payment']['items'] = $items;
     //$woocommerce->cart->empty_cart();
     return MEOWallet_Checkout::getRedirectionUrl($params);
 }
<?php

add_action('woocommerce_thankyou', function ($order) {
    $trans = new WC_Order($order);
    $items = $trans->get_items();
    $length = count($items);
    foreach ($items as $key => $item) {
        if ($key + 1 < $length) {
            $cartProducts[$key] = "\n\t\t{\n\t\t'sku': '" . $item['product_id'] . "',\n\t\t'name': '" . $item['name'] . "',\n\t\t'category': '',\n\t\t'price': '" . $item['line_total'] . "',\n\t\t'quantity': '" . $item['qty'] . "'\n\t\t},";
        } else {
            $cartProducts[$key] = "\n\t\t{\n\t\t'sku': '" . $item['product_id'] . "',\n\t\t'name': '" . $item['name'] . "',\n\t\t'category': '',\n\t\t'price': '" . $item['line_total'] . "',\n\t\t'quantity': '" . $item['qty'] . "'\n\t\t}";
        }
    }
    echo "<script>dataLayer.push({'transactionId': '" . $trans->get_order_number() . "','transactionAffiliation': '','transactionTotal': '" . $trans->get_total() . "','transactionTax': '" . $trans->get_total_tax() . "','transactionShipping': '" . $trans->get_total_shipping() . "','transactionProducts': [";
    foreach ($cartProducts as $row) {
        echo $row;
    }
    echo "]});</script>";
});
 function get_monthly_sales_report()
 {
     $execution_time_start = microtime(true);
     $months_array = array('');
     $months_days_array = array(__('Days', 'woocommerce-jetpack'));
     $total_orders_array = array(__('Total Orders', 'woocommerce-jetpack'));
     $total_orders_average_array = array(__('Orders Average / Day', 'woocommerce-jetpack'));
     $total_orders_sum_array = array(__('Total Sum', 'woocommerce-jetpack'));
     $total_orders_sum_excl_tax_array = array(__('Total Sum (excl. TAX)', 'woocommerce-jetpack'));
     $total_orders_sum_average_order_array = array(__('Average / Order (excl. TAX)', 'woocommerce-jetpack'));
     $total_orders_sum_average_array = array(__('Average / Day (excl. TAX)', 'woocommerce-jetpack'));
     $currency_rates_array = array(__('Currency Rates', 'woocommerce-jetpack'));
     $total_months_days = 0;
     $total_orders_total = 0;
     $total_orders_sum_total = 0;
     $total_orders_sum_excl_tax_total = 0;
     $order_currencies_array = array();
     $report_currency = isset($_GET['currency']) && 'merge' != $_GET['currency'] ? $_GET['currency'] : get_woocommerce_currency();
     $block_size = 96;
     $table_data = array();
     for ($i = 1; $i <= 12; $i++) {
         $current_months_averages = array();
         $total_orders = 0;
         $total_orders_sum = 0;
         $total_orders_sum_excl_tax = 0;
         $offset = 0;
         $day_for_average = $i == date('m') && $this->year == date('Y') ? date('d') - 1 : date('t', strtotime($this->year . '-' . sprintf('%02d', $i) . '-' . '01'));
         if (0 == $day_for_average) {
             $months_array[] = date_i18n('F', mktime(0, 0, 0, $i, 1, $this->year));
             $months_days_array[] = '-';
             $total_orders_array[] = '-';
             $total_orders_average_array[] = '-';
             $total_orders_sum_array[] = '-';
             $total_orders_sum_excl_tax_array[] = '-';
             $total_orders_sum_average_order_array[] = '-';
             $total_orders_sum_average_array[] = '-';
             $currency_rates_array[] = '';
             continue;
         }
         while (true) {
             $args_orders = array('post_type' => 'shop_order', 'post_status' => 'wc-completed', 'posts_per_page' => $block_size, 'orderby' => 'date', 'order' => 'DESC', 'offset' => $offset, 'date_query' => array('after' => array('year' => $this->year, 'month' => $i, 'day' => 1), 'before' => array('year' => $this->year, 'month' => $i, 'day' => $day_for_average), 'inclusive' => true));
             $loop_orders = new WP_Query($args_orders);
             if (!$loop_orders->have_posts()) {
                 break;
             }
             while ($loop_orders->have_posts()) {
                 $loop_orders->the_post();
                 $order_id = $loop_orders->post->ID;
                 $order = new WC_Order($order_id);
                 $order_currency = $order->get_order_currency();
                 if (!isset($order_currencies_array[$order_currency])) {
                     $order_currencies_array[$order_currency] = 0;
                 }
                 $order_currencies_array[$order_currency]++;
                 $total_orders++;
                 $order_total = $order->get_total();
                 $order_total_excl_tax = $order->get_total() - $order->get_total_tax();
                 if (!isset($current_months_averages[$order_currency][$report_currency])) {
                     $start_date = $this->year . '-' . sprintf('%02d', $i) . '-' . '01';
                     $end_date = date('Y-m-t', strtotime($start_date));
                     $the_rate = $this->get_exchange_rate_average($order_currency, $report_currency, $start_date, $end_date);
                     if (false === $the_rate) {
                         // Try previous month
                         $start_date_prev_month = date('Y-m-d', strtotime('first day of last month', strtotime($start_date)));
                         $end_date_prev_month = date('Y-m-t', strtotime($start_date_prev_month));
                         $the_rate = $this->get_exchange_rate_average($order_currency, $report_currency, $start_date_prev_month, $end_date_prev_month);
                         if (false === $the_rate) {
                             return '<p>' . sprintf(__('Error getting currency rate for %s', 'woocommerce-jetpack'), $order_currency . $report_currency) . '</p>';
                         }
                     }
                     $current_months_averages[$order_currency][$report_currency] = $the_rate;
                 }
                 $total_orders_sum += $order_total * $current_months_averages[$order_currency][$report_currency];
                 $total_orders_sum_excl_tax += $order_total_excl_tax * $current_months_averages[$order_currency][$report_currency];
             }
             $offset += $block_size;
         }
         // Month Name
         $months_array[] = date_i18n('F', mktime(0, 0, 0, $i, 1, $this->year));
         // Month Days
         $months_days_array[] = date('m') >= $i || $this->year != date('Y') ? $day_for_average : '-';
         $total_months_days += date('m') >= $i || $this->year != date('Y') ? $day_for_average : 0;
         // Sales
         $total_orders_array[] = $total_orders > 0 ? $total_orders : '-';
         $total_orders_total += $total_orders;
         // Sales Average
         $average_sales_result = $total_orders / $day_for_average;
         $total_orders_average_array[] = $average_sales_result > 0 ? number_format($average_sales_result, 2, '.', ',') : '-';
         // Sum
         $total_orders_sum_array[] = $total_orders_sum > 0 ? $report_currency . ' ' . number_format($total_orders_sum, 2, '.', ',') : '-';
         $total_orders_sum_total += $total_orders_sum;
         // Sum excl. Tax
         //if ( $total_orders_sum != $total_orders_sum_excl_tax) {
         $total_orders_sum_excl_tax_array[] = $total_orders_sum_excl_tax > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax, 2, '.', ',') : '-';
         $total_orders_sum_excl_tax_total += $total_orders_sum_excl_tax;
         //}
         // Order Average
         $total_orders_sum_average_order_array[] = $total_orders_sum_excl_tax > 0 && $total_orders > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax / $total_orders, 2, '.', ',') : '-';
         // Sum Average
         $average_result = $total_orders_sum_excl_tax / $day_for_average;
         $total_orders_sum_average_array[] = $average_result > 0 ? $report_currency . ' ' . number_format($average_result, 2, '.', ',') : '-';
         // Currency Rates
         //			if ( isset( $_GET['show_rates'] ) ) {
         ksort($current_months_averages, true);
         //				$currency_rates_html = '<pre style="font-size:8px;">' . print_r( $current_months_averages, true ) . '</pre>';
         $currency_rates_html = '<pre style="font-size:x-small;">';
         foreach ($current_months_averages as $currency_from => $currencies_to) {
             foreach ($currencies_to as $currency_to => $rate) {
                 if ($currency_from != $currency_to) {
                     $currency_rates_html .= $currency_from . $currency_to . '~' . number_format($rate, 4) . '<br>';
                 }
             }
         }
         $currency_rates_html .= '</pre>';
         //			}
         $currency_rates_array[] = $currency_rates_html;
     }
     // Totals
     $months_array[] = __('Totals', 'woocommerce-jetpack');
     $months_days_array[] = $total_months_days;
     $total_orders_array[] = $total_orders_total;
     $total_orders_average_array[] = $total_months_days > 0 ? number_format($total_orders_total / $total_months_days, 2, '.', ',') : '-';
     $total_orders_sum_array[] = $report_currency . ' ' . number_format($total_orders_sum_total, 2, '.', ',');
     $total_orders_sum_excl_tax_array[] = $report_currency . ' ' . number_format($total_orders_sum_excl_tax_total, 2, '.', ',');
     $total_orders_sum_average_order_array[] = $total_orders_total > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax_total / $total_orders_total, 2, '.', ',') : '-';
     $total_orders_sum_average_array[] = $total_months_days > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax_total / $total_months_days, 2, '.', ',') : '-';
     $currency_rates_array[] = '';
     // Table
     $table_data[] = $months_array;
     $table_data[] = $months_days_array;
     $table_data[] = $total_orders_array;
     $table_data[] = $total_orders_average_array;
     $table_data[] = $total_orders_sum_array;
     $table_data[] = $total_orders_sum_excl_tax_array;
     $table_data[] = $total_orders_sum_average_order_array;
     $table_data[] = $total_orders_sum_average_array;
     $table_data[] = $currency_rates_array;
     /* foreach ( $order_currencies_array as $order_currency => $total_currency_orders ) {
     			$table_data[] = array( $order_currency . ' (' . $total_currency_orders . ')' );
     		} */
     $execution_time_end = microtime(true);
     // HTML
     $html = '';
     $menu = '';
     $menu .= '<ul class="subsubsub">';
     $menu .= '<li><a href="' . add_query_arg('year', date('Y')) . '" class="' . ($this->year == date('Y') ? 'current' : '') . '">' . date('Y') . '</a> | </li>';
     $menu .= '<li><a href="' . add_query_arg('year', date('Y') - 1) . '" class="' . ($this->year == date('Y') - 1 ? 'current' : '') . '">' . (date('Y') - 1) . '</a> | </li>';
     $menu .= '</ul>';
     $menu .= '<br class="clear">';
     $html .= $menu;
     $html .= '<h4>' . __('Report currency', 'woocommerce-jetpack') . ': ' . $report_currency . '</h4>';
     $months_styles = array();
     for ($i = 1; $i <= 12; $i++) {
         $months_styles[] = 'width:6%;';
     }
     $html .= wcj_get_table_html($table_data, array('table_class' => 'widefat striped', 'table_heading_type' => 'horizontal', 'columns_styles' => array_merge(array('width:16%;'), $months_styles, array('width:12%;font-weight:bold;'))));
     $html .= '<p style="font-size:x-small;"><em>' . sprintf(__('Report generated in: %s s', 'woocommerce-jetpack'), number_format($execution_time_end - $execution_time_start, 2, '.', ',')) . '</em></p>';
     $html .= '<form method="post" action="">' . '<input name="wcj_reset_currency_rates" type="submit" class="button button-primary" value="' . __('Reset Currency Rates', 'woocommerce-jetpack') . '">' . '</form>';
     //		$html .= '<pre>' . print_r( get_option( 'wcj_reports_currency_rates' ), true ) . '</pre>';
     return $html;
 }
 /**
  * Process the payment and return the result
  *
  * @access public
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $this->init_mijireh();
     $mj_order = new Mijireh_Order();
     $wc_order = new WC_Order($order_id);
     // Avoid rounding issues altogether by sending the order as one lump
     if (get_option('woocommerce_prices_include_tax') == 'yes') {
         // Don't pass items - Pass 1 item for the order items overall
         $item_names = array();
         if (sizeof($wc_order->get_items()) > 0) {
             foreach ($wc_order->get_items() as $item) {
                 if ($item['qty']) {
                     $item_names[] = $item['name'] . ' x ' . $item['qty'];
                 }
             }
         }
         $mj_order->add_item(sprintf(__('Order %s', 'woocommerce'), $wc_order->get_order_number()) . " - " . implode(', ', $item_names), number_format($wc_order->get_total() - round($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2) + $wc_order->get_order_discount(), 2, '.', ''), 1);
         if ($wc_order->get_total_shipping() + $wc_order->get_shipping_tax() > 0) {
             $mj_order->shipping = number_format($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2, '.', '');
         }
         $mj_order->show_tax = false;
         // No issues when prices exclude tax
     } else {
         // add items to order
         $items = $wc_order->get_items();
         foreach ($items as $item) {
             $product = $wc_order->get_product_from_item($item);
             $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, false, true), $item['qty'], $product->get_sku());
         }
         // Handle fees
         $items = $wc_order->get_fees();
         foreach ($items as $item) {
             $mj_order->add_item($item['name'], number_format($item['line_total'], 2, '.', ','), 1, '');
         }
         $mj_order->shipping = round($wc_order->get_total_shipping(), 2);
         $mj_order->tax = $wc_order->get_total_tax();
     }
     // set order totals
     $mj_order->total = $wc_order->get_total();
     $mj_order->discount = $wc_order->get_total_discount();
     // add billing address to order
     $billing = new Mijireh_Address();
     $billing->first_name = $wc_order->billing_first_name;
     $billing->last_name = $wc_order->billing_last_name;
     $billing->street = $wc_order->billing_address_1;
     $billing->apt_suite = $wc_order->billing_address_2;
     $billing->city = $wc_order->billing_city;
     $billing->state_province = $wc_order->billing_state;
     $billing->zip_code = $wc_order->billing_postcode;
     $billing->country = $wc_order->billing_country;
     $billing->company = $wc_order->billing_company;
     $billing->phone = $wc_order->billing_phone;
     if ($billing->validate()) {
         $mj_order->set_billing_address($billing);
     }
     // add shipping address to order
     $shipping = new Mijireh_Address();
     $shipping->first_name = $wc_order->shipping_first_name;
     $shipping->last_name = $wc_order->shipping_last_name;
     $shipping->street = $wc_order->shipping_address_1;
     $shipping->apt_suite = $wc_order->shipping_address_2;
     $shipping->city = $wc_order->shipping_city;
     $shipping->state_province = $wc_order->shipping_state;
     $shipping->zip_code = $wc_order->shipping_postcode;
     $shipping->country = $wc_order->shipping_country;
     $shipping->company = $wc_order->shipping_company;
     if ($shipping->validate()) {
         $mj_order->set_shipping_address($shipping);
     }
     // set order name
     $mj_order->first_name = $wc_order->billing_first_name;
     $mj_order->last_name = $wc_order->billing_last_name;
     $mj_order->email = $wc_order->billing_email;
     // add meta data to identify woocommerce order
     $mj_order->add_meta_data('wc_order_id', $order_id);
     // Set URL for mijireh payment notificatoin - use WC API
     $mj_order->return_url = WC()->api_request_url('WC_Gateway_Mijireh');
     // Identify woocommerce
     $mj_order->partner_id = 'woo';
     try {
         $mj_order->create();
         $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url);
         return $result;
     } catch (Mijireh_Exception $e) {
         wc_add_notice(__('Mijireh error:', 'woocommerce') . $e->getMessage() . print_r($mj_order, true), 'error');
     }
 }
 public function process_refund($order_id, $amount = NULL, $reason = '')
 {
     global $woocommerce;
     $wc_order = new WC_Order($order_id);
     $trx_id = get_post_meta($order_id, '_transaction_id', true);
     $trx_metas = get_post_meta($order_id, '_' . $order_id . '_' . $trx_id . '_metas', true);
     $last_four = isset($trx_metas['account_number']) ? esc_attr($trx_metas['account_number']) : '';
     $refund = new AuthorizeNetAIM();
     $customer = (object) array();
     $customer->first_name = $wc_order->billing_first_name;
     $customer->last_name = $wc_order->billing_last_name;
     $customer->company = $wc_order->billing_company;
     $customer->address = $wc_order->billing_address_1 . ' ' . $wc_order->billing_address_2;
     $customer->city = $wc_order->billing_city;
     $customer->state = $wc_order->billing_state;
     $customer->zip = $wc_order->billing_postcode;
     $customer->country = $wc_order->billing_country;
     $customer->phone = $wc_order->billing_phone;
     $customer->email = $wc_order->billing_email;
     $customer->cust_id = $wc_order->user_id;
     $customer->invoice_num = $wc_order->get_order_number();
     $customer->description = get_bloginfo('blogname') . ' Order #' . $wc_order->get_order_number();
     $customer->ship_to_first_name = $wc_order->shipping_first_name;
     $customer->ship_to_last_name = $wc_order->shipping_last_name;
     $customer->ship_to_company = $wc_order->shipping_company;
     $customer->ship_to_address = $wc_order->shipping_address_1 . ' ' . $wc_order->shipping_address_2;
     $customer->ship_to_city = $wc_order->shipping_city;
     $customer->ship_to_state = $wc_order->shipping_state;
     $customer->ship_to_zip = $wc_order->shipping_postcode;
     $customer->ship_to_country = $wc_order->shipping_country;
     $customer->delim_char = '|';
     $customer->encap_char = '';
     $customer->customer_ip = $this->get_client_ip();
     $customer->tax = $wc_order->get_total_tax();
     $customer->freight = $wc_order->get_total_shipping();
     $customer->header_email_receipt = 'Refund From ' . get_bloginfo('blogname') . ' ' . $reason;
     $customer->footer_email_receipt = 'Thank you for Using ' . get_bloginfo('blogname');
     $refund->setFields($customer);
     $refundtrx = $refund->credit($trx_id, $amount, $last_four);
     if (1 == $refundtrx->approved) {
         $wc_order->add_order_note(__($refundtrx->response_reason_text . 'on' . date("d-m-Y h:i:s e") . 'with Transaction ID = ' . $refundtrx->transaction_id . ' using ' . strtoupper($refundtrx->transaction_type) . ' and authorization code ' . $refundtrx->authorization_code, 'woocommerce'));
         if ($wc_order->order_total == $amount) {
             $wc_order->update_status('wc-refunded');
         }
         return true;
     } else {
         if (2 == $refundtrx->response_subcode || 54 == $refundtrx->response_reason_code) {
             $refundtrx = $refund->void($trx_id);
             if (1 == $refundtrx->approved) {
                 $wc_order->add_order_note(__($refundtrx->response_reason_text . 'on ' . date("d-m-Y h:i:s e") . 'with Transaction ID = ' . $refundtrx->transaction_id . ' using ' . strtoupper($refundtrx->transaction_type) . ' and authorization code ' . $refundtrx->authorization_code, 'woocommerce'));
                 $wc_order->update_status('wc-cancelled');
                 return true;
             } else {
                 $wc_order->add_order_note(__($refundtrx->response_reason_text . '--' . $refundtrx->error_message . ' on ' . date("d-m-Y h:i:s e") . ' using ' . strtoupper($refundtrx->transaction_type), 'woocommerce'));
                 return false;
             }
         } else {
             $wc_order->add_order_note(__($refundtrx->response_reason_text . '--' . $refundtrx->error_message . ' on ' . date("d-m-Y h:i:s e") . ' using ' . strtoupper($refundtrx->transaction_type), 'woocommerce'));
             return false;
         }
         return false;
     }
     return false;
 }
</th>
                						<td style="text-align:left;"><?php 
    echo woocommerce_price($order->order_discount);
    ?>
</td>
                					</tr><?php 
}
?>
                          <tr>
                            <th colspan="2" style="text-align:left; padding-top: 12px;">&nbsp;</th>
                						<th scope="row" style="text-align:right; padding-right: 10px;"><?php 
_e('Tax:', 'woocommerce-pip');
?>
</th>
                						<td style="text-align:left;"><?php 
echo woocommerce_price($order->get_total_tax());
?>
</td>
                					</tr>
                					<tr>
                					  <th colspan="2" style="text-align:left; padding-top: 12px;">&nbsp;</th>
                						<th scope="row" style="text-align:right; padding-right: 10px;"><?php 
_e('Total:', 'woocommerce-pip');
?>
</th>
                						<td style="text-align:left;"><?php 
echo woocommerce_price($order->order_total);
?>
</td>
                					</tr>
                				</tfoot>
 /**
  * Get the order data for the given ID.
  *
  * @since  2.5.0
  * @param  WC_Order $order The order instance
  * @return array
  */
 protected function get_order_data($order)
 {
     $order_post = get_post($order->id);
     $dp = wc_get_price_decimals();
     $order_data = array('id' => $order->id, 'order_number' => $order->get_order_number(), 'created_at' => $this->format_datetime($order_post->post_date_gmt), 'updated_at' => $this->format_datetime($order_post->post_modified_gmt), 'completed_at' => $this->format_datetime($order->completed_date, true), 'status' => $order->get_status(), 'currency' => $order->get_order_currency(), 'total' => wc_format_decimal($order->get_total(), $dp), 'subtotal' => wc_format_decimal($order->get_subtotal(), $dp), 'total_line_items_quantity' => $order->get_item_count(), 'total_tax' => wc_format_decimal($order->get_total_tax(), $dp), 'total_shipping' => wc_format_decimal($order->get_total_shipping(), $dp), 'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp), 'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp), 'total_discount' => wc_format_decimal($order->get_total_discount(), $dp), 'shipping_methods' => $order->get_shipping_method(), 'payment_details' => array('method_id' => $order->payment_method, 'method_title' => $order->payment_method_title, 'paid' => isset($order->paid_date)), 'billing_address' => array('first_name' => $order->billing_first_name, 'last_name' => $order->billing_last_name, 'company' => $order->billing_company, 'address_1' => $order->billing_address_1, 'address_2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'postcode' => $order->billing_postcode, 'country' => $order->billing_country, 'email' => $order->billing_email, 'phone' => $order->billing_phone), 'shipping_address' => array('first_name' => $order->shipping_first_name, 'last_name' => $order->shipping_last_name, 'company' => $order->shipping_company, 'address_1' => $order->shipping_address_1, 'address_2' => $order->shipping_address_2, 'city' => $order->shipping_city, 'state' => $order->shipping_state, 'postcode' => $order->shipping_postcode, 'country' => $order->shipping_country), 'note' => $order->customer_note, 'customer_ip' => $order->customer_ip_address, 'customer_user_agent' => $order->customer_user_agent, 'customer_id' => $order->get_user_id(), 'view_order_url' => $order->get_view_order_url(), 'line_items' => array(), 'shipping_lines' => array(), 'tax_lines' => array(), 'fee_lines' => array(), 'coupon_lines' => array());
     // add line items
     foreach ($order->get_items() as $item_id => $item) {
         $product = $order->get_product_from_item($item);
         $product_id = null;
         $product_sku = null;
         // Check if the product exists.
         if (is_object($product)) {
             $product_id = isset($product->variation_id) ? $product->variation_id : $product->id;
             $product_sku = $product->get_sku();
         }
         $meta = new WC_Order_Item_Meta($item, $product);
         $item_meta = array();
         foreach ($meta->get_formatted(null) as $meta_key => $formatted_meta) {
             $item_meta[] = array('key' => $meta_key, 'label' => $formatted_meta['label'], 'value' => $formatted_meta['value']);
         }
         $order_data['line_items'][] = array('id' => $item_id, 'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp), 'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp), 'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp), 'total_tax' => wc_format_decimal($item['line_tax'], $dp), 'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp), 'quantity' => wc_stock_amount($item['qty']), 'tax_class' => !empty($item['tax_class']) ? $item['tax_class'] : null, 'name' => $item['name'], 'product_id' => $product_id, 'sku' => $product_sku, 'meta' => $item_meta);
     }
     // Add shipping.
     foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) {
         $order_data['shipping_lines'][] = array('id' => $shipping_item_id, 'method_id' => $shipping_item['method_id'], 'method_title' => $shipping_item['name'], 'total' => wc_format_decimal($shipping_item['cost'], $dp));
     }
     // Add taxes.
     foreach ($order->get_tax_totals() as $tax_code => $tax) {
         $order_data['tax_lines'][] = array('id' => $tax->id, 'rate_id' => $tax->rate_id, 'code' => $tax_code, 'title' => $tax->label, 'total' => wc_format_decimal($tax->amount, $dp), 'compound' => (bool) $tax->is_compound);
     }
     // Add fees.
     foreach ($order->get_fees() as $fee_item_id => $fee_item) {
         $order_data['fee_lines'][] = array('id' => $fee_item_id, 'title' => $fee_item['name'], 'tax_class' => !empty($fee_item['tax_class']) ? $fee_item['tax_class'] : null, 'total' => wc_format_decimal($order->get_line_total($fee_item), $dp), 'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp));
     }
     // Add coupons.
     foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) {
         $order_data['coupon_lines'][] = array('id' => $coupon_item_id, 'code' => $coupon_item['name'], 'amount' => wc_format_decimal($coupon_item['discount_amount'], $dp));
     }
     $order_data = apply_filters('woocommerce_cli_order_data', $order_data);
     return $this->flatten_array($order_data);
 }
function show_my_custom_orders()
{
    $page_id = get_the_ID();
    $product_id = (int) get_post_meta($page_id, 'report_product_id', true);
    $after = strtotime(get_post_meta($page_id, 'report_after_date', true));
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    if ($product_id && $after) {
        global $wpdb;
        $after = strftime('%Y-%m-%d %H:%M:%S', $after);
        // Получаем id релевантных посты-заказы.
        $sql = $wpdb->prepare("SELECT oi.order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta AS om\n                               JOIN {$wpdb->prefix}woocommerce_order_items AS oi ON om.order_item_id=oi.order_item_id\n                               JOIN {$wpdb->posts} AS p ON p.ID=oi.order_id\n                               WHERE om.meta_key='_product_id' AND om.meta_value=%d AND p.post_date >=%s", $product_id, $after);
        $order_ids = $wpdb->get_col($sql);
        if ($order_ids) {
            // Дальше используем стандартные методы
            $args = array('ignore_sticky_posts' => true, 'posts_per_page' => 50, 'paged' => $paged, 'post_type' => 'shop_order', 'post_status' => 'publish', 'post__in' => $order_ids);
            $loop = new WP_Query($args);
            while ($loop->have_posts()) {
                $loop->the_post();
                $order_id = $loop->post->ID;
                $order = new WC_Order($order_id);
                ?>
				<article>
					<header>
						<h2><?php 
                _e('Order', 'woocommerce');
                ?>
							№<?php 
                echo $order_id;
                ?>
 &mdash; <?php 
                the_time('d.m.Y h:i:s');
                ?>
</time></h2>
					</header>
					<table cellspacing="0" cellpadding="2">
						<thead>
						<tr>
							<th scope="col" style="text-align:left;"><?php 
                _e('Product', 'woocommerce');
                ?>
</th>
							<th scope="col" style="text-align:left;"><?php 
                _e('Quantity', 'woocommerce');
                ?>
</th>
							<th scope="col" style="text-align:left;"><?php 
                _e('Price', 'woocommerce');
                ?>
</th>
						</tr>
						</thead>
						<tfoot>
						<tr>
							<th scope="row" colspan="2"
							    style="text-align:left; padding-top: 12px;"><?php 
                _e('Subtotal:', 'woocommerce');
                ?>
</th>
							<td style="text-align:left; padding-top: 12px;"><?php 
                echo $order->get_subtotal_to_display();
                ?>
</td>
						</tr>
						<tr>
							<th scope="row" colspan="2"
							    style="text-align:left; padding-top: 12px;"><?php 
                _e('Status', 'woocommerce');
                ?>
</th>
							<td style="text-align:left; padding-top: 12px;"><?php 
                echo _e(wc_get_order_status_name(get_post_status()), 'woocommerce');
                ?>
</td>
						</tr>
						<?php 
                if ($order->order_shipping > 0) {
                    ?>
							<tr>
								<th scope="row" colspan="2"
								    style="text-align:left;"><?php 
                    _e('Shipping:', 'woocommerce');
                    ?>
</th>
								<td style="text-align:left;"><?php 
                    echo $order->get_shipping_to_display();
                    ?>
</td>
							</tr>
						<?php 
                }
                ?>
						<?php 
                if ($order->order_discount > 0) {
                    ?>
							<tr>
								<th scope="row" colspan="2"
								    style="text-align:left;"><?php 
                    _e('Discount:', 'woocommerce');
                    ?>
</th>
								<td style="text-align:left;"><?php 
                    echo woocommerce_price($order->order_discount);
                    ?>
</td>
							</tr>
						<?php 
                }
                ?>
						<?php 
                if ($order->get_total_tax() > 0) {
                    ?>
							<tr>
								<th scope="row" colspan="2"
								    style="text-align:left;"><?php 
                    _e('Tax:', 'woocommerce');
                    ?>
</th>
								<td style="text-align:left;"><?php 
                    echo woocommerce_price($order->get_total_tax());
                    ?>
</td>
							</tr>
						<?php 
                }
                ?>
						<tr>
							<th scope="row" colspan="2"
							    style="text-align:left;"><?php 
                _e('Total:', 'woocommerce');
                ?>
</th>
							<td style="text-align:left;"><?php 
                echo woocommerce_price($order->order_total);
                ?>
</td>
						</tr>
						</tfoot>
						<tbody>
						<?php 
                echo $order->email_order_items_table();
                ?>
						</tbody>
					</table>

					<?php 
                show_customer_details($order);
                ?>

					<hr>

					<div style="clear:both;"></div>
				</article>
				<?php 
            }
            ?>
			<nav>
				<span style="float:left"><?php 
            previous_posts_link('&laquo; Назад', $loop->max_num_pages);
            ?>
</span>
				<span style="float:right"><?php 
            next_posts_link('Вперёд &raquo;', $loop->max_num_pages);
            ?>
</span>
			</nav>

			<?php 
            wp_reset_query();
        } else {
            ?>
			<p>Заказов товара <?php 
            echo $product_id;
            ?>
 после <?php 
            echo $after;
            ?>
 нет.</p>
			<?php 
        }
    }
}
 /**
  * Charge Payment
  * Method ini digunakan untuk mendapatkan link halaman pembayaran Veritrans
  * dengan mengirimkan JSON yang berisi data transaksi
  */
 function charge_payment($order_id)
 {
     global $woocommerce;
     $order_items = array();
     $cart = $woocommerce->cart;
     $order = new WC_Order($order_id);
     // add discount
     // WC()->cart->add_discount( 'veritrans' );
     $cart->add_discount('veritrans');
     $order->add_coupon('veritrans', WC()->cart->get_coupon_discount_amount('veritrans'), WC()->cart->get_coupon_discount_tax_amount('veritrans'));
     $order->set_total(WC()->cart->shipping_total, 'shipping');
     $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
     $order->set_total(WC()->cart->get_cart_discount_tax_total(), 'cart_discount_tax');
     $order->set_total(WC()->cart->tax_total, 'tax');
     $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
     $order->set_total(WC()->cart->total);
     // $order->add_coupon('veritrans',10000);
     // end of add discount
     Veritrans_Config::$isProduction = $this->environment == 'production' ? true : false;
     Veritrans_Config::$serverKey = Veritrans_Config::$isProduction ? $this->server_key_v2_production : $this->server_key_v2_sandbox;
     Veritrans_Config::$is3ds = true;
     Veritrans_Config::$isSanitized = $this->enable_sanitization == 'yes' ? true : false;
     $params = array('transaction_details' => array('order_id' => $order_id, 'gross_amount' => 0), 'vtweb' => array());
     $enabled_payments = array();
     // if ($this->enable_credit_card == 'yes'){
     //   $enabled_payments[] = 'credit_card';
     // }
     // check enabled payment
     if ($this->enable_credit_card == 'yes') {
         $params['vtweb']['enabled_payments'] = 'credit_card';
     }
     if ($this->enable_permata_va == 'yes') {
         $params['vtweb']['enabled_payments'] = 'bank_transfer';
     }
     // add bin filter
     $bins = $this->bin_filter;
     $bins = explode(',', $bins);
     $params['vtweb']['credit_card_bins'] = $bins;
     $customer_details = array();
     $customer_details['first_name'] = $order->billing_first_name;
     $customer_details['last_name'] = $order->billing_last_name;
     $customer_details['email'] = $order->billing_email;
     $customer_details['phone'] = $order->billing_phone;
     $billing_address = array();
     $billing_address['first_name'] = $order->billing_first_name;
     $billing_address['last_name'] = $order->billing_last_name;
     $billing_address['address'] = $order->billing_address_1;
     $billing_address['city'] = $order->billing_city;
     $billing_address['postal_code'] = $order->billing_postcode;
     $billing_address['phone'] = $order->billing_phone;
     $billing_address['country_code'] = strlen($this->convert_country_code($order->billing_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
     $customer_details['billing_address'] = $billing_address;
     $customer_details['shipping_address'] = $billing_address;
     if (isset($_POST['ship_to_different_address'])) {
         $shipping_address = array();
         $shipping_address['first_name'] = $order->shipping_first_name;
         $shipping_address['last_name'] = $order->shipping_last_name;
         $shipping_address['address'] = $order->shipping_address_1;
         $shipping_address['city'] = $order->shipping_city;
         $shipping_address['postal_code'] = $order->shipping_postcode;
         $shipping_address['phone'] = $order->billing_phone;
         $shipping_address['country_code'] = strlen($this->convert_country_code($order->shipping_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
         $customer_details['shipping_address'] = $shipping_address;
     }
     $params['customer_details'] = $customer_details;
     //error_log(print_r($params,true));
     $items = array();
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if ($item['qty']) {
                 $product = $order->get_product_from_item($item);
                 $veritrans_item = array();
                 $veritrans_item['id'] = $item['product_id'];
                 $veritrans_item['price'] = $order->get_item_subtotal($item, false);
                 $veritrans_item['quantity'] = $item['qty'];
                 $veritrans_item['name'] = $item['name'];
                 $items[] = $veritrans_item;
             }
         }
     }
     // Shipping fee
     if ($order->get_total_shipping() > 0) {
         $items[] = array('id' => 'shippingfee', 'price' => $order->get_total_shipping(), 'quantity' => 1, 'name' => 'Shipping Fee');
     }
     // Tax
     if ($order->get_total_tax() > 0) {
         $items[] = array('id' => 'taxfee', 'price' => $order->get_total_tax(), 'quantity' => 1, 'name' => 'Tax');
     }
     // Discount
     if ($order->get_cart_discount() > 0) {
         $items[] = array('id' => 'totaldiscount', 'price' => $order->get_cart_discount() * -1, 'quantity' => 1, 'name' => 'Total Discount');
     }
     // Fees
     if (sizeof($order->get_fees()) > 0) {
         $fees = $order->get_fees();
         $i = 0;
         foreach ($fees as $item) {
             $items[] = array('id' => 'itemfee' . $i, 'price' => $item['line_total'], 'quantity' => 1, 'name' => $item['name']);
             $i++;
         }
     }
     //calculate gross amount
     $total_amount = 0;
     // error_log('print r items[]' . print_r($items,true)); //debugan
     foreach ($items as $item) {
         $total_amount += $item['price'] * $item['quantity'];
         // error_log('|||| Per item[]' . print_r($item,true)); //debugan
     }
     $params['transaction_details']['gross_amount'] = $total_amount;
     // error_log('bni'.$this->enable_bni);
     // error_log('mandiri'.$this->enable_mandiri);
     // if($this->enable_bni == 'yes' || $this->enable_mandiri == 'yes')
     if (false) {
         $installment_terms = array();
         $payment_options = array('installment' => array('required' => true, 'installment_terms' => new stdClass(), 'offline_installment_terms' => array()));
         // $term_bni = $this->bni_terms;
         // error_log('term bni '.$term_bni);
         // $term_bni_array = explode(',' , $term_bni);
         // if($term_bni == "yes" || $term_bni_array != null)
         // {
         //   $installment_terms['bni'] = $term_bni_array;
         // }
         // $term_mandiri =  $this->mandiri_terms;
         // error_log('term mandiri '.$term_mandiri);
         // $term_mandiri_array = explode(',' , $term_mandiri);
         // if($term_mandiri == "yes" || $term_mandiri_array != null)
         // {
         //   $installment_terms['mandiri'] = $term_mandiri_array;
         // }
         $term = $this->installment_terms;
         error_log('============installment_terms ' . $term);
         $term_array = explode(',', $term);
     }
     // sift through the entire item to ensure that currency conversion is applied
     if (get_woocommerce_currency() != 'IDR') {
         foreach ($items as &$item) {
             $item['price'] = $item['price'] * $this->to_idr_rate;
         }
         unset($item);
         $params['transaction_details']['gross_amount'] *= $this->to_idr_rate;
     }
     $params['item_details'] = $items;
     // if($params['transaction_details']['gross_amount'] >= $this->min_amount)
     // {
     //   $payment_options['installment']['offline_installment_terms'] = $term_array;
     //   $params['vtweb']['payment_options'] = $payment_options;
     // }
     $woocommerce->cart->empty_cart();
     error_log(print_r($params, TRUE));
     // error_log(json_encode($params));
     return Veritrans_VtWeb::getRedirectionUrl($params);
 }
Esempio n. 28
0
 /**
  * Test: calculate_taxes
  */
 function test_calculate_taxes()
 {
     global $wpdb;
     update_option('woocommerce_calc_taxes', 'yes');
     $tax_rate = array('tax_rate_country' => '', 'tax_rate_state' => '', 'tax_rate' => '10.0000', 'tax_rate_name' => 'TAX', 'tax_rate_priority' => '1', 'tax_rate_compound' => '0', 'tax_rate_shipping' => '1', 'tax_rate_order' => '1', 'tax_rate_class' => '');
     WC_Tax::_insert_tax_rate($tax_rate);
     $object = new WC_Order();
     $object->add_product(WC_Helper_Product::create_simple_product(), 4);
     $rate = new WC_Shipping_Rate('flat_rate_shipping', 'Flat rate shipping', '10', array(), 'flat_rate');
     $item = new WC_Order_Item_Shipping();
     $item->set_props(array('method_title' => $rate->label, 'method_id' => $rate->id, 'total' => wc_format_decimal($rate->cost), 'taxes' => $rate->taxes, 'meta_data' => $rate->get_meta_data()));
     $object->add_item($item);
     $object->calculate_taxes();
     $this->assertEquals(5, $object->get_total_tax());
     // Cleanup
     $wpdb->query("DELETE FROM {$wpdb->prefix}woocommerce_tax_rates");
     $wpdb->query("DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations");
     update_option('woocommerce_calc_taxes', 'no');
 }
Esempio n. 29
0
File: woo.php Progetto: bulats/chef
function sm_woo_get_packing_slip($purchase_ids, $purchase_id_arr)
{
    if (!empty($purchase_ids) && !empty($purchase_id_arr)) {
        ?>
        <style type="text/css">
            body {
                font-family:"Helvetica Neue", Helvetica, Arial, Verdana, sans-serif;
            }

            h1 span {
                font-size:0.75em;
            }

            h2 {
                color: #333;
            }
            .no-page-break {
                page-break-after: avoid;
            }

            #wrapper {
                margin:0 auto;
                width:95%;
                page-break-after: always;
            }

            #wrapper_last {
                margin:0 auto;
                width:95%;
                page-break-after: avoid;
            }

            .address{
                width:98%;
                border-top:1px;
                border-right:1px;
                margin:1em auto;
                border-collapse:collapse;
            }
            
            .address_border{
                border-bottom:1px;
                border-left:1px ;
                padding:.2em 1em;
                text-align:left;
            }
           
            table {
                width:98%;
                border-top:1px solid #e5eff8;
                border-right:1px solid #e5eff8;
                margin:1em auto;
                border-collapse:collapse;
                font-size:10pt;
            }
            td {
                border-bottom:1px solid #e5eff8;
                border-left:1px solid #e5eff8;
                padding:.3em 1em;
                text-align:center;
            }

            tr.odd td,
            tr.odd .column1 {
                background:#f4f9fe url(background.gif) no-repeat;
            }
            .column1 {
                background:#f4f9fe;
            }

            thead th {
                background:#f4f9fe;
                text-align:center;
                font:bold 1.2em/2em "Century Gothic","Trebuchet MS",Arial,Helvetica,sans-serif;
            }
            .datagrid {

                position: relative;
                top:-30pt;
            }
            .producthead{ 
                text-align: left;
            }
            .pricehead{
                text-align: right;
            }
            .sm_address_div{
                position: relative;
                left:28pt;
            }
            .sm_email_span{
                position: relative;
                left:10pt;
            }

        </style>
        <?php 
        $counter = 0;
        foreach ($purchase_id_arr as $purchase_id_value) {
            $order = new WC_Order($purchase_id_value);
            $date_format = get_option('date_format');
            if (is_plugin_active('woocommerce-sequential-order-numbers-pro/woocommerce-sequential-order-numbers.php')) {
                $purchase_display_id = isset($order->order_custom_fields['_order_number_formatted'][0]) ? $order->order_custom_fields['_order_number_formatted'][0] : $purchase_id_value;
            } else {
                $purchase_display_id = $purchase_id_value;
            }
            $counter++;
            if (count($purchase_id_arr) == $counter) {
                echo '<div id="wrapper_last">';
            } else {
                echo '<div id="wrapper">';
            }
            echo smart_manager_print_logo();
            echo '<div style="margin-top:-0.8em;">';
            echo '<h4 style="font:bold 1.2em/2em "Century Gothic","Trebuchet MS",Arial,Helvetica,sans-serif;
                    position:relative; 12pt;">&nbsp; ' . get_bloginfo('name') . '</h4>';
            echo '<table class="address" style="position:relative; top:-22pt; left:-35pt;">';
            echo '<tr><td class="address_border" colspan="2" valign="top" width="50%"><span style="position:relative; left:27pt; top:10pt;">
                    <b>Order # ' . $purchase_display_id . ' - ' . date($date_format, strtotime($order->order_date)) . '</b></span><br/></td></tr>';
            echo '<tr><td class="address_border" width="35%" align="center"><br/><div class="sm_address_div">';
            $formatted_billing_address = $order->get_formatted_billing_address();
            if ($formatted_billing_address != '') {
                echo '<b>' . __('Billing Address', 'smart-manager') . '</b><p>';
                echo $formatted_billing_address;
                echo '</p></td>';
            }
            $formatted_shipping_address = $order->get_formatted_shipping_address();
            if ($formatted_shipping_address != '') {
                echo '<td class="address_border" width="30%"><br/><div style="position:relative; top:3pt;"><b>' . __('Shipping Address', 'smart-manager') . '</b><p>';
                echo $formatted_shipping_address;
                echo '</p></div></td>';
            }
            echo '</tr>';
            echo '<tr><td colspan="2" class="address_border"><span class="sm_email_span"><table class="address"><tr><td colspan="2" class="address_border" >
                    <b>' . __('Email id', 'smart-manager') . ':</b> ' . $order->billing_email . '</td></tr>
                    <tr><td class="address_border"><b>' . __('Tel', 'smart-manager') . ' :</b> ' . $order->billing_phone . '</td></tr></table> </span></td></tr>';
            echo '</table>';
            echo '<div class="datagrid"><table><tr class="column1">
                    <td class="producthead">' . __('Product', 'smart-manager') . '</td><td>' . __('SKU', 'smart-manager') . '</td>
                    <td>' . __('Quantity', 'smart-manager') . '</td><td class="pricehead">' . __('Price', 'smart-manager') . '</td></tr>';
            foreach ($order->get_items() as $item) {
                $_product = $order->get_product_from_item($item);
                $sku = $variation = '';
                $sku = $_product->get_sku();
                $formatted_variation = woocommerce_get_formatted_variation($_product->variation_data, true);
                $variation = !empty($formatted_variation) ? ' (' . $formatted_variation . ')' : '';
                $item_total = $_product->get_price() * $item['item_meta']['_qty'][0];
                $total_order += $item_total;
                echo '<tr><td class="producthead">';
                echo $item['name'] . $variation;
                echo '</td><td>' . $sku . '</td><td>';
                echo $item['item_meta']['_qty'][0];
                echo '</td><td class="pricehead">';
                echo woocommerce_price($item_total);
                echo '</td></tr>';
            }
            echo '<tr><td colspan="2" rowspan="5" class="address_border" valign="top"><br/>
                    <i>' . ($order->customer_note != '' ? __('Order Notes', 'smart-manager') . ' : ' . $order->customer_note : '') . '</i></td><td style="text-align:right;" class="address_border" valign="top">
                    <b>Subtotal </b></td><td class="pricehead">' . $order->get_subtotal_to_display() . '</td></tr>';
            echo '<tr><td style="text-align:right;" class="address_border"><b>' . __('Shipping', 'smart-manager') . ' </b></td><td class="pricehead">' . $order->get_shipping_to_display() . '</td></tr>';
            if ($order->cart_discount > 0) {
                echo '<tr><td style="text-align:right;" class="address_border">' . __('Cart Discount', 'smart-manager') . '</td><td style="text-align:right;">';
                echo woocommerce_price($order->cart_discount);
                echo '</td></tr>';
            }
            if ($order->order_discount > 0) {
                echo '<tr><td style="text-align:right;" class="address_border"><b>' . __('Order Discount', 'smart-manager') . ' </b></td>';
                echo '<td class="pricehead">' . woocommerce_price($order->order_discount) . '</td></tr>';
            }
            echo '<tr><td style="text-align:right;" class="address_border"><b>' . __('Tax', 'smart-manager') . ' </b></td><td class="pricehead">' . woocommerce_price($order->get_total_tax()) . '</td></tr>';
            echo '<tr><td class="column1" style="text-align:right;"><b>' . __('Total', 'smart-manager') . ' </b></td><td class="column1" style="text-align:right;">' . woocommerce_price($order->order_total) . ' -via ' . $order->payment_method_title . '</td></tr>';
            echo '</table></div></div></div>';
        }
    }
    exit;
}
    /**
     * Google Analytics eCommerce tracking
     **/
    function ecommerce_tracking_code($order_id)
    {
        global $woocommerce;
        if (is_admin() || current_user_can('manage_options') || $this->ga_ecommerce_tracking_enabled == "no") {
            return;
        }
        $tracking_id = $this->ga_id;
        if (!$tracking_id) {
            return;
        }
        // Doing eCommerce tracking so unhook standard tracking from the footer
        remove_action('wp_footer', array(&$this, 'google_tracking_code'));
        // Get the order and output tracking code
        $order = new WC_Order($order_id);
        $loggedin = is_user_logged_in() ? 'yes' : 'no';
        if (is_user_logged_in()) {
            $user_id = get_current_user_id();
            $current_user = get_user_by('id', $user_id);
            $username = $current_user->user_login;
        } else {
            $user_id = '';
            $username = __('Guest', 'woocommerce');
        }
        ?>
		<script type="text/javascript">
			var _gaq = _gaq || [];
			
			_gaq.push(
				['_setAccount', '<?php 
        echo $tracking_id;
        ?>
'],
				['_setCustomVar', 1, 'logged-in', '<?php 
        echo $loggedin;
        ?>
', 1],
				['_setCustomVar', 2, 'user-id', '<?php 
        echo $user_id;
        ?>
', 1],
				['_setCustomVar', 3, 'username', '<?php 
        echo $username;
        ?>
', 1],
				['_trackPageview']
			);
			
			_gaq.push(['_addTrans',
				'<?php 
        echo $order_id;
        ?>
',           		// order ID - required
				'<?php 
        bloginfo('name');
        ?>
',  				// affiliation or store name
				'<?php 
        echo $order->order_total;
        ?>
',   	// total - required
				'<?php 
        echo $order->get_total_tax();
        ?>
',   // tax
				'<?php 
        echo $order->get_shipping();
        ?>
',	// shipping
				'<?php 
        echo $order->billing_city;
        ?>
',      // city
				'<?php 
        echo $order->billing_state;
        ?>
',     // state or province
				'<?php 
        echo $order->billing_country;
        ?>
'    // country
			]);
			
			// Order items
			<?php 
        if ($order->get_items()) {
            foreach ($order->get_items() as $item) {
                $_product = $order->get_product_from_item($item);
                ?>
				_gaq.push(['_addItem',
					'<?php 
                echo $order_id;
                ?>
',           	// order ID - required
					'<?php 
                if (!empty($_product->sku)) {
                    echo __('SKU:', 'woocommerce') . ' ' . $_product->sku;
                } else {
                    echo $_product->id;
                }
                ?>
', // SKU/code - required
					'<?php 
                echo $item['name'];
                ?>
',        	// product name
					'<?php 
                if (isset($_product->variation_data)) {
                    echo woocommerce_get_formatted_variation($_product->variation_data, true);
                } else {
                    $out = array();
                    $categories = get_the_terms($_product->id, 'product_cat');
                    if ($categories) {
                        foreach ($categories as $category) {
                            $out[] = $category->name;
                        }
                    }
                    echo join("/", $out);
                }
                ?>
',   // category or variation
					'<?php 
                echo $item['line_total'] / $item['qty'];
                ?>
',         // unit price - required
					'<?php 
                echo $item['qty'];
                ?>
'           // quantity - required
				]);
			<?php 
            }
        }
        ?>
			
			_gaq.push(['_trackTrans']); 					// submits transaction to the Analytics servers
			
			(function() {
				var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
				ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
				var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
			})();
		</script>
		<?php 
    }