コード例 #1
1
 /**
  * Add order item via ajax
  * exact copy from /wp-content/plugins/woocommerce/includes/class-wc-ajax.php, with change to template selection
  */
 public static function add_order_item()
 {
     check_ajax_referer('order-item', 'security');
     $item_to_add = sanitize_text_field($_POST['item_to_add']);
     $order_id = absint($_POST['order_id']);
     // Find the item
     if (!is_numeric($item_to_add)) {
         die;
     }
     $post = get_post($item_to_add);
     if (!$post || 'product' !== $post->post_type && 'product_variation' !== $post->post_type) {
         die;
     }
     $_product = wc_get_product($post->ID);
     $order = wc_get_order($order_id);
     $order_taxes = $order->get_taxes();
     $class = 'new_row';
     // Set values
     $item = array();
     $item['product_id'] = $_product->id;
     $item['variation_id'] = isset($_product->variation_id) ? $_product->variation_id : '';
     $item['variation_data'] = isset($_product->variation_data) ? $_product->variation_data : '';
     $item['name'] = $_product->get_title();
     $item['tax_class'] = $_product->get_tax_class();
     $item['qty'] = 1;
     $item['line_subtotal'] = wc_format_decimal($_product->get_price_excluding_tax());
     $item['line_subtotal_tax'] = '';
     $item['line_total'] = wc_format_decimal($_product->get_price_excluding_tax());
     $item['line_tax'] = '';
     // Add line item
     $item_id = wc_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'line_item'));
     // Add line item meta
     if ($item_id) {
         wc_add_order_item_meta($item_id, '_qty', $item['qty']);
         wc_add_order_item_meta($item_id, '_tax_class', $item['tax_class']);
         wc_add_order_item_meta($item_id, '_product_id', $item['product_id']);
         wc_add_order_item_meta($item_id, '_variation_id', $item['variation_id']);
         wc_add_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
         wc_add_order_item_meta($item_id, '_line_subtotal_tax', $item['line_subtotal_tax']);
         wc_add_order_item_meta($item_id, '_line_total', $item['line_total']);
         wc_add_order_item_meta($item_id, '_line_tax', $item['line_tax']);
         // Since 2.2
         wc_add_order_item_meta($item_id, '_line_tax_data', array('total' => array(), 'subtotal' => array()));
         // Store variation data in meta
         if ($item['variation_data'] && is_array($item['variation_data'])) {
             foreach ($item['variation_data'] as $key => $value) {
                 wc_add_order_item_meta($item_id, str_replace('attribute_', '', $key), $value);
             }
         }
         do_action('woocommerce_ajax_add_order_item_meta', $item_id, $item);
     }
     $item = apply_filters('woocommerce_ajax_order_item', $item, $item_id);
     //include( 'admin/meta-boxes/views/html-order-item.php' );
     //@@@@LOUSHOU - allow overtake of template
     include apply_filters('qsot-woo-template', 'meta-boxes/views/html-order-item.php', 'admin');
     // Quit out
     die;
 }
コード例 #2
0
 /**
  * Add the details of an order item to a subscription as a product line item.
  *
  * When adding a product to a subscription, we can't use WC_Abstract_Order::add_product() because it requires a product object
  * and the details of the product may have changed since it was purchased so we can't simply instantiate an instance of the
  * product based on ID.
  *
  * @param WC_Subscription $new_subscription A subscription object
  * @param int $order_item_id ID of the subscription item on the original order
  * @param array $order_item An array of order item data in the form returned by WC_Abstract_Order::get_items()
  * @return int Subscription $item_id The order item id of the new line item added to the subscription.
  * @since 2.0
  */
 private static function add_product($new_subscription, $order_item_id, $order_item)
 {
     global $wpdb;
     $item_id = wc_add_order_item($new_subscription->id, array('order_item_name' => $order_item['name'], 'order_item_type' => 'line_item'));
     WCS_Upgrade_Logger::add(sprintf('For subscription %d: new line item ID %d added', $new_subscription->id, $item_id));
     $order_item = WCS_Repair_2_0::maybe_repair_order_item($order_item);
     $wpdb->query($wpdb->prepare("INSERT INTO `{$wpdb->prefix}woocommerce_order_itemmeta` (`order_item_id`, `meta_key`, `meta_value`)\n\t\t\t VALUES\n\t\t\t\t(%d, '_qty', %s),\n\t\t\t\t(%d, '_tax_class', %s),\n\t\t\t\t(%d, '_product_id', %s),\n\t\t\t\t(%d, '_variation_id', %s),\n\t\t\t\t(%d, '_line_subtotal', %s),\n\t\t\t\t(%d, '_line_total', %s),\n\t\t\t\t(%d, '_line_subtotal_tax', %s),\n\t\t\t\t(%d, '_line_tax', %s)", $item_id, $order_item['qty'], $item_id, $order_item['tax_class'], $item_id, $order_item['product_id'], $item_id, $order_item['variation_id'], $item_id, $order_item['recurring_line_subtotal'], $item_id, $order_item['recurring_line_total'], $item_id, $order_item['recurring_line_subtotal_tax'], $item_id, $order_item['recurring_line_tax']));
     // Save tax data array added in WC 2.2 (so it won't exist for all orders/subscriptions)
     self::add_line_tax_data($item_id, $order_item_id, $order_item);
     if (isset($order_item['subscription_trial_length']) && $order_item['subscription_trial_length'] > 0) {
         wc_add_order_item_meta($item_id, '_has_trial', 'true');
     }
     // Don't copy item meta already copied
     $reserved_item_meta_keys = array('_item_meta', '_qty', '_tax_class', '_product_id', '_variation_id', '_line_subtotal', '_line_total', '_line_tax', '_line_tax_data', '_line_subtotal_tax');
     $meta_keys_to_copy = array_diff(array_keys($order_item['item_meta']), array_merge($reserved_item_meta_keys, self::$subscription_item_meta_keys));
     // Add variation and any other meta
     foreach ($meta_keys_to_copy as $meta_key) {
         foreach ($order_item['item_meta'][$meta_key] as $meta_value) {
             wc_add_order_item_meta($item_id, $meta_key, $meta_value);
         }
     }
     WCS_Upgrade_Logger::add(sprintf('For subscription %d: for item %d added %s', $new_subscription->id, $item_id, implode(', ', $meta_keys_to_copy)));
     // Now that we've copied over the old data, prefix some the subscription meta keys with _wcs_migrated to deprecate it without deleting it (yet)
     $rows_affected = self::deprecate_item_meta($order_item_id);
     WCS_Upgrade_Logger::add(sprintf('For subscription %d: %s rows of line item meta deprecated', $new_subscription->id, $rows_affected));
     return $item_id;
 }
コード例 #3
0
            $wpdb->query($wpdb->prepare("\n\t\t\t\tUPDATE {$wpdb->postmeta}\n\t\t\t\tSET meta_key = '_order_items_old'\n\t\t\t\tWHERE meta_key = '_order_items'\n\t\t\t\tAND post_id = %d\n\t\t\t", $order_item_row->post_id));
        }
        unset($meta_rows, $item_id, $order_item);
    }
}
// Do the same kind of update for order_taxes - move to lines
// Reverse with UPDATE `wpwc_postmeta` SET meta_key = '_order_taxes' WHERE meta_key = '_order_taxes_old'
$order_tax_rows = $wpdb->get_results("\n\tSELECT * FROM {$wpdb->postmeta}\n\tWHERE meta_key = '_order_taxes'\n");
foreach ($order_tax_rows as $order_tax_row) {
    $order_taxes = (array) maybe_unserialize($order_tax_row->meta_value);
    if ($order_taxes) {
        foreach ($order_taxes as $order_tax) {
            if (!isset($order_tax['label']) || !isset($order_tax['cart_tax']) || !isset($order_tax['shipping_tax'])) {
                continue;
            }
            $item_id = wc_add_order_item($order_tax_row->post_id, array('order_item_name' => $order_tax['label'], 'order_item_type' => 'tax'));
            // Add line item meta
            if ($item_id) {
                wc_add_order_item_meta($item_id, 'compound', absint(isset($order_tax['compound']) ? $order_tax['compound'] : 0));
                wc_add_order_item_meta($item_id, 'tax_amount', wc_clean($order_tax['cart_tax']));
                wc_add_order_item_meta($item_id, 'shipping_tax_amount', wc_clean($order_tax['shipping_tax']));
            }
            // Delete from DB (rename)
            $wpdb->query($wpdb->prepare("\n\t\t\t\tUPDATE {$wpdb->postmeta}\n\t\t\t\tSET meta_key = '_order_taxes_old'\n\t\t\t\tWHERE meta_key = '_order_taxes'\n\t\t\t\tAND post_id = %d\n\t\t\t", $order_tax_row->post_id));
            unset($tax_amount);
        }
    }
}
// Grab the pre 2.0 Image options and use to populate the new image options settings,
// cleaning up afterwards like nice people do
foreach (array('catalog', 'single', 'thumbnail') as $value) {
コード例 #4
0
ファイル: wc-functions.php プロジェクト: amirkchetu/dokan
/**
 * Create shipping for a sub-order if neccessary
 *
 * @param WC_Order $parent_order
 * @param int $order_id
 * @param array $product_ids
 * @return type
 */
function dokan_create_sub_order_shipping($parent_order, $order_id, $seller_products)
{
    // take only the first shipping method
    $shipping_methods = $parent_order->get_shipping_methods();
    $shipping_method = is_array($shipping_methods) ? reset($shipping_methods) : array();
    // bail out if no shipping methods found
    if (!$shipping_method) {
        return;
    }
    $shipping_products = array();
    $packages = array();
    // emulate shopping cart for calculating the shipping method
    foreach ($seller_products as $product_item) {
        $product = get_product($product_item['product_id']);
        if ($product->needs_shipping()) {
            $shipping_products[] = array('product_id' => $product_item['product_id'], 'variation_id' => $product_item['variation_id'], 'variation' => '', 'quantity' => $product_item['qty'], 'data' => $product, 'line_total' => $product_item['line_total'], 'line_tax' => $product_item['line_tax'], 'line_subtotal' => $product_item['line_subtotal'], 'line_subtotal_tax' => $product_item['line_subtotal_tax']);
        }
    }
    if ($shipping_products) {
        $package = array('contents' => $shipping_products, 'contents_cost' => array_sum(wp_list_pluck($shipping_products, 'line_total')), 'applied_coupons' => array(), 'destination' => array('country' => $parent_order->shipping_country, 'state' => $parent_order->shipping_state, 'postcode' => $parent_order->shipping_postcode, 'city' => $parent_order->shipping_city, 'address' => $parent_order->shipping_address_1, 'address_2' => $parent_order->shipping_address_2));
        $wc_shipping = WC_Shipping::instance();
        $pack = $wc_shipping->calculate_shipping_for_package($package);
        if (array_key_exists($shipping_method['method_id'], $pack['rates'])) {
            $method = $pack['rates'][$shipping_method['method_id']];
            $cost = wc_format_decimal($method->cost);
            $item_id = wc_add_order_item($order_id, array('order_item_name' => $method->label, 'order_item_type' => 'shipping'));
            if ($item_id) {
                wc_add_order_item_meta($item_id, 'method_id', $method->id);
                wc_add_order_item_meta($item_id, 'cost', $cost);
            }
            return $cost;
        }
    }
    return 0;
}
コード例 #5
0
 /**
  * Add an item to the provided order
  *
  * @since 3.0.0
  * @param \WC_Order $order
  * @param array $item Parsed item data from CSV
  * @param string $type Line item type
  * @return int|false ID of the inserted order item, false on failure
  */
 private function add_order_item(WC_Order $order, $item, $type)
 {
     $result = false;
     switch ($type) {
         case 'line_item':
             $product = $this->get_product_for_item($item);
             $args = $this->prepare_product_args($item);
             $result = $order->add_product($product, $args['qty'], $args);
             if (!$result) {
                 wc_csv_import_suite()->log(sprintf(__('> > Warning: cannot add order item "%s".', 'woocommerce-csv-import-suite'), esc_html($identifier)));
             }
             break;
         case 'shipping':
             $args = array('order_item_name' => $item['method_title'], 'order_item_type' => 'shipping');
             // we're using wc_add_order_item instead of $order->add_shipping because
             // we do not want the order total to be recalculated
             $result = wc_add_order_item($order->id, $args);
             if (!$result) {
                 wc_csv_import_suite()->log(sprintf(__('> > Warning: cannot add shipping method "%s".', 'woocommerce-csv-import-suite'), esc_html($item['title'])));
             }
             break;
         case 'tax':
             $args = array('order_item_name' => $item['code'], 'order_item_type' => 'tax');
             $result = wc_add_order_item($order->id, $args);
             if (!$result) {
                 wc_csv_import_suite()->log(sprintf(__('> > Warning: cannot add tax "%s".', 'woocommerce-csv-import-suite'), esc_html($item['label'])));
             }
             break;
         case 'coupon':
             $result = $order->add_coupon($item['code'], $item['amount']);
             if (!$result) {
                 wc_csv_import_suite()->log(sprintf(__('> > Warning: cannot add coupon "%s".', 'woocommerce-csv-import-suite'), esc_html($item['code'])));
             }
             break;
         case 'fee':
             $order_fee = new stdClass();
             $order_fee->id = sanitize_title($item['title']);
             $order_fee->name = $item['title'];
             $order_fee->amount = isset($item['total']) ? floatval($item['total']) : 0;
             $order_fee->taxable = false;
             $order_fee->tax = 0;
             $order_fee->tax_data = array();
             $order_fee->tax_class = '';
             // if taxable, tax class and total are required
             if (isset($item['taxable']) && $item['taxable']) {
                 $order_fee->taxable = true;
                 $order_fee->tax_class = $item['tax_class'];
                 if (isset($item['total_tax'])) {
                     $order_fee->tax = isset($item['total_tax']) ? wc_format_refund_total($item['total_tax']) : 0;
                 }
                 if (isset($item['tax_data'])) {
                     $tax_data = isset($item['tax_data']['total']) ? $item['tax_data']['total'] : $item['tax_data'];
                     $order_fee->tax = wc_format_refund_total(array_sum($tax_data));
                     $order_fee->tax_data = array_map('wc_format_refund_total', $tax_data);
                 }
             }
             $result = $order->add_fee($order_fee);
             if (!$result) {
                 wc_csv_import_suite()->log(sprintf(__('> > Warning: cannot add fee "%s".', 'woocommerce-csv-import-suite'), esc_html($item['title'])));
             }
             break;
     }
     // store original order item ID
     if ($result && isset($item['order_item_id']) && $item['order_item_id'] > 0) {
         wc_update_order_item_meta($result, '_original_order_item_id', $item['order_item_id']);
     }
     return $result;
 }
コード例 #6
0
 public function sync()
 {
     global $wp;
     global $wpdb;
     set_time_limit(0);
     @ini_set('display_errors', '1');
     @ini_set('zlib.output_compression', 'Off');
     @ini_set('output_buffering', 'Off');
     @ini_set('output_handler', '');
     while (ob_get_level() > 1) {
         @ob_end_clean();
     }
     if (ob_get_level() > 0) {
         @ob_clean();
     }
     if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
         $this->sendHttpHeaders('500 Config Error', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
         echo $this->json_encode(array('ack' => 'failed', 'message' => 'WooCommerce Deactivated'));
         exit;
     }
     $type = $wp->query_vars['codisto-sync-route'];
     if (strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
         if ($type == 'test' || $type == 'sync' && preg_match('/\\/sync\\/testHash\\?/', $_SERVER['REQUEST_URI'])) {
             if (!$this->check_hash()) {
                 exit;
             }
             $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
             echo $this->json_encode(array('ack' => 'ok'));
         } else {
             if ($type === 'settings') {
                 if (!$this->check_hash()) {
                     exit;
                 }
                 $logo_url = get_header_image();
                 if (function_exists('site_logo')) {
                     $logo = site_logo()->logo;
                     $logo_id = get_theme_mod('custom_logo');
                     $logo_id = $logo_id ? $logo_id : $logo['id'];
                     if ($logo_id) {
                         $logo_url = wp_get_attachment_image_src($logo_id, 'full');
                         $logo_url = $logo_url[0];
                     }
                 }
                 $currency = get_option('woocommerce_currency');
                 $dimension_unit = get_option('woocommerce_dimension_unit');
                 $weight_unit = get_option('woocommerce_weight_unit');
                 $default_location = explode(':', get_option('woocommerce_default_country'));
                 $country_code = isset($default_location[0]) ? $default_location[0] : '';
                 $state_code = isset($default_location[1]) ? $default_location[1] : '';
                 $response = array('ack' => 'ok', 'logo' => $logo_url, 'currency' => $currency, 'dimension_unit' => $dimension_unit, 'weight_unit' => $weight_unit, 'country_code' => $country_code, 'state_code' => $state_code);
                 $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                 echo $this->json_encode($response);
                 exit;
             } else {
                 if ($type === 'tax') {
                     if (!$this->check_hash()) {
                         exit;
                     }
                     $tax_enabled = true;
                     if (function_exists('wc_tax_enabled')) {
                         $tax_enabled = wc_tax_enabled();
                     } else {
                         $tax_enabled = get_option('woocommerce_calc_taxes') === 'yes';
                     }
                     if ($tax_enabled) {
                         $rates = $wpdb->get_results("SELECT tax_rate_country AS country, tax_rate_state AS state, tax_rate AS rate, tax_rate_name AS name, tax_rate_class AS class, tax_rate_order AS sequence, tax_rate_priority AS priority FROM `{$wpdb->prefix}woocommerce_tax_rates` ORDER BY tax_rate_order");
                     } else {
                         $rates = array();
                     }
                     $response = array('ack' => 'ok', 'tax_rates' => $rates);
                     $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                     echo $this->json_encode($response);
                     exit;
                 } else {
                     if ($type === 'products') {
                         if (!$this->check_hash()) {
                             exit;
                         }
                         $page = isset($_GET['page']) ? (int) $_GET['page'] : 0;
                         $count = isset($_GET['count']) ? (int) $_GET['count'] : 0;
                         $product_ids = isset($_GET['product_ids']) ? json_decode(wp_unslash($_GET['product_ids'])) : null;
                         if (!is_null($product_ids)) {
                             if (!is_array($product_ids)) {
                                 $product_ids = array($product_ids);
                             }
                             $product_ids = array_filter($product_ids, create_function('$v', 'return is_numeric($v);'));
                             if (!isset($_GET['count'])) {
                                 $count = count($product_ids);
                             }
                         }
                         $products = $wpdb->get_results($wpdb->prepare("SELECT id AS id " . "FROM `{$wpdb->prefix}posts` AS P " . "WHERE post_type = 'product' " . "\t\tAND post_status IN ('publish', 'future', 'pending', 'private') " . "\t" . (is_array($product_ids) ? 'AND id IN (' . implode(',', $product_ids) . ')' : '') . "" . "ORDER BY ID LIMIT %d, %d", $page * $count, $count));
                         if (!is_array($product_ids) && $page === 0) {
                             $total_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$wpdb->prefix}posts` WHERE post_type = 'product' AND post_status IN ('publish', 'future', 'pending', 'private')");
                         }
                         $acf_installed = function_exists('acf');
                         foreach ($products as $product) {
                             $wc_product = $this->get_product($product->id);
                             $categoryproduct = $wc_product->get_categories();
                             $product->sku = $wc_product->get_sku();
                             $product->name = html_entity_decode(apply_filters('woocommerce_product_title', $wc_product->post->post_title, $wc_product), ENT_COMPAT | ENT_HTML401, 'UTF-8');
                             $product->enabled = $wc_product->is_purchasable() && ($wc_product->managing_stock() || $wc_product->is_in_stock());
                             $product->price = $wc_product->get_price_excluding_tax();
                             $product->listprice = floatval($wc_product->get_regular_price());
                             $product->is_taxable = $wc_product->is_taxable();
                             $product->tax_class = $wc_product->get_tax_class();
                             $product->stock_control = $wc_product->managing_stock();
                             $product->stock_level = $wc_product->get_stock_quantity();
                             if (method_exists($wc_product, 'get_type')) {
                                 $product->type = $wc_product->get_type();
                             } else {
                                 $product->type = $wc_product->product_type;
                             }
                             $product->description = apply_filters('the_content', $wc_product->post->post_content);
                             $product->short_description = apply_filters('the_content', $wc_product->post->post_excerpt);
                             if (method_exists($wc_product, 'get_width')) {
                                 $product->width = $wc_product->get_width();
                                 if (!is_numeric($product->width)) {
                                     unset($product->width);
                                 }
                                 $product->height = $wc_product->get_height();
                                 if (!is_numeric($product->height)) {
                                     unset($product->height);
                                 }
                                 $product->length = $wc_product->get_length();
                                 if (!is_numeric($product->length)) {
                                     unset($product->length);
                                 }
                             } else {
                                 $product->length = $wc_product->length;
                                 $product->width = $wc_product->width;
                                 $product->height = $wc_product->height;
                             }
                             $product->weight = $wc_product->get_weight();
                             if (!is_numeric($product->weight)) {
                                 unset($product->weight);
                             }
                             if ($product->is_taxable && 'yes' === get_option('woocommerce_prices_include_tax')) {
                                 $tax_rates = WC_Tax::get_shop_base_rate($product->tax_class);
                                 $taxes = WC_Tax::calc_tax($product->listprice, $tax_rates, true);
                                 $product->listprice = $product->listprice - array_sum($taxes);
                             }
                             if ($product->type == 'variable') {
                                 $product->skus = array();
                                 foreach ($wc_product->get_children() as $child_id) {
                                     $child_product = $wc_product->get_child($child_id);
                                     $img = wp_get_attachment_image_src($child_product->get_image_id(), 'full');
                                     $img = $img[0];
                                     $child_product_data = array('id' => $child_id, 'sku' => $child_product->get_sku(), 'enabled' => $wc_product->is_purchasable() && ($wc_product->managing_stock() || $wc_product->is_in_stock()), 'price' => $child_product->get_price_excluding_tax(), 'listprice' => $child_product->get_regular_price(), 'is_taxable' => $child_product->is_taxable(), 'tax_class' => $child_product->get_tax_class(), 'stock_control' => $child_product->managing_stock(), 'stock_level' => $child_product->get_stock_quantity(), 'images' => array(array('source' => $img, 'sequence' => 0)));
                                     $attributes = array();
                                     $termsmap = array();
                                     $names = array();
                                     foreach ($child_product->get_variation_attributes() as $name => $value) {
                                         $name = preg_replace('/(pa_)?attribute_/', '', $name);
                                         if (!isset($names[$name])) {
                                             $names[$name] = true;
                                             $terms = get_terms(array('taxonomy' => $name));
                                             if ($terms) {
                                                 foreach ($terms as $term) {
                                                     $termsmap[$term->slug] = $term->name;
                                                 }
                                             }
                                         }
                                         if ($value && (gettype($value) == 'string' || gettype($value) == 'integer')) {
                                             if (array_key_exists($value, $termsmap)) {
                                                 $newvalue = $termsmap[$value];
                                             } else {
                                                 $newvalue = $value;
                                             }
                                         } else {
                                             $newvalue = '';
                                         }
                                         $name = wc_attribute_label($name, $child_product);
                                         $attributes[] = array('name' => $name, 'value' => $newvalue, 'slug' => $value);
                                     }
                                     foreach (get_post_custom_keys($child_product->variation_id) as $attribute) {
                                         if (!(in_array($attribute, array('_sku', '_weight', '_length', '_width', '_height', '_thumbnail_id', '_virtual', '_downloadable', '_regular_price', '_sale_price', '_sale_price_dates_from', '_sale_price_dates_to', '_price', '_download_limit', '_download_expiry', '_file_paths', '_manage_stock', '_stock_status', '_downloadable_files', '_variation_description', '_tax_class', '_tax_status', '_stock', '_default_attributes', '_product_attributes', '_file_path', '_backorders')) || substr($attribute, 0, 4) === '_wp_' || substr($attribute, 0, 13) === 'attribute_pa_')) {
                                             $value = get_post_meta($child_product->variation_id, $attribute, false);
                                             if (is_array($value)) {
                                                 if (count($value) === 1) {
                                                     $value = $value[0];
                                                 } else {
                                                     $value = implode(',', $value);
                                                 }
                                             }
                                             $attributes[] = array('name' => $attribute, 'value' => $value, 'custom' => true);
                                         }
                                     }
                                     $child_product_data['attributes'] = $attributes;
                                     $product->skus[] = $child_product_data;
                                 }
                                 $attrs = array();
                                 foreach ($wc_product->get_variation_attributes() as $name => $value) {
                                     $name = preg_replace('/(pa_)?attribute_/', '', $name);
                                     if (!isset($names[$name])) {
                                         $names[$name] = true;
                                         $terms = get_terms(array('taxonomy' => $name));
                                         if ($terms) {
                                             foreach ($terms as $term) {
                                                 $termsmap[$term->slug] = $term->name;
                                             }
                                         }
                                     }
                                     if ($value && (gettype($value) == 'string' || gettype($value) == 'integer')) {
                                         if (array_key_exists($value, $termsmap)) {
                                             $newvalue = $termsmap[$value];
                                         } else {
                                             $newvalue = $value;
                                         }
                                     } else {
                                         $newvalue = '';
                                     }
                                     $name = wc_attribute_label($name, $child_product);
                                     $attrs[] = array('name' => $name, 'value' => $newvalue, 'slug' => $value);
                                 }
                                 $product->options = $attrs;
                             } else {
                                 if ($product->type == 'grouped') {
                                     $product->skus = array();
                                     foreach ($wc_product->get_children() as $child_id) {
                                         $child_product = $wc_product->get_child($child_id);
                                         $child_product_data = array('id' => $child_id, 'price' => $child_product->get_price_excluding_tax(), 'sku' => $child_product->get_sku(), 'name' => $child_product->get_title());
                                         $product->skus[] = $child_product_data;
                                     }
                                 }
                             }
                             $product->categories = array();
                             $product_categories = get_the_terms($product->id, 'product_cat');
                             if (is_array($product_categories)) {
                                 $sequence = 0;
                                 foreach ($product_categories as $category) {
                                     $product->categories[] = array('category_id' => $category->term_id, 'sequence' => $sequence);
                                     $sequence++;
                                 }
                             }
                             $image_sequence = 1;
                             $product->images = array();
                             $imagesUsed = array();
                             $primaryimage_path = wp_get_attachment_image_src($wc_product->get_image_id(), 'full');
                             $primaryimage_path = $primaryimage_path[0];
                             if ($primaryimage_path) {
                                 $product->images[] = array('source' => $primaryimage_path, 'sequence' => 0);
                                 $imagesUsed[$primaryimage_path] = true;
                                 foreach ($wc_product->get_gallery_attachment_ids() as $image_id) {
                                     $image_path = wp_get_attachment_image_src($image_id, 'full');
                                     $image_path = $image_path[0];
                                     if (!array_key_exists($image_path, $imagesUsed)) {
                                         $product->images[] = array('source' => $image_path, 'sequence' => $image_sequence);
                                         $imagesUsed[$image_path] = true;
                                         $image_sequence++;
                                     }
                                 }
                             }
                             $product->attributes = array();
                             $attributesUsed = array();
                             foreach ($wc_product->get_attributes() as $attribute) {
                                 if (!$attribute['is_variation']) {
                                     if (!array_key_exists($attribute['name'], $attributesUsed)) {
                                         $attributesUsed[$attribute['name']] = true;
                                         $attributeName = wc_attribute_label($attribute['name']);
                                         if (!$attribute['is_taxonomy']) {
                                             $product->attributes[] = array('name' => $attributeName, 'value' => $attribute['value']);
                                         } else {
                                             $attributeValue = implode(', ', wc_get_product_terms($product->id, $attribute['name'], array('fields' => 'names')));
                                             $product->attributes[] = array('name' => $attributeName, 'value' => $attributeValue);
                                         }
                                     }
                                 }
                             }
                             foreach (get_post_custom_keys($product->id) as $attribute) {
                                 if (!(substr($attribute, 0, 1) === '_' || substr($attribute, 0, 3) === 'pa_')) {
                                     if (!array_key_exists($attribute, $attributesUsed)) {
                                         $attributesUsed[$attribute] = true;
                                         $value = get_post_meta($product->id, $attribute, false);
                                         if (is_array($value)) {
                                             if (count($value) === 1) {
                                                 $value = $value[0];
                                             } else {
                                                 $value = implode(',', $value);
                                             }
                                         }
                                         $product->attributes[] = array('name' => $attribute, 'value' => $value);
                                     }
                                 }
                             }
                             // acf
                             if ($acf_installed) {
                                 if (function_exists('get_field_objects')) {
                                     $fields = get_field_objects($product->id);
                                     if (is_array($fields)) {
                                         foreach ($fields as $field) {
                                             if ($field['type'] == 'image') {
                                                 $image_path = $field['value']['url'];
                                                 if (!array_key_exists($image_path, $imagesUsed)) {
                                                     $product->images[] = array('source' => $image_path, 'sequence' => $image_sequence);
                                                     $imagesUsed[$image_path] = true;
                                                     $image_sequence++;
                                                 }
                                             } else {
                                                 if ($field['type'] == 'gallery') {
                                                     $gallery = $field['value'];
                                                     if (is_array($gallery)) {
                                                         foreach ($gallery as $image) {
                                                             $image_path = $image['url'];
                                                             if (!array_key_exists($image_path, $imagesUsed)) {
                                                                 $product->images[] = array('source' => $image_path, 'sequence' => $image_sequence);
                                                                 $imagesUsed[$image_path] = true;
                                                                 $image_sequence++;
                                                             }
                                                         }
                                                     }
                                                 } else {
                                                     if (in_array($field['type'], array('textarea', 'wysiwyg', 'text', 'number', 'select', 'radio', 'checkbox', 'true_false'))) {
                                                         if (!array_key_exists($field['label'], $attributesUsed)) {
                                                             $attributesUsed[$field['label']] = true;
                                                             $value = $field['value'];
                                                             if (is_array($value)) {
                                                                 if (count($value) === 1) {
                                                                     $value = $value[0];
                                                                 } else {
                                                                     $value = implode(',', $value);
                                                                 }
                                                             }
                                                             $product->attributes[] = array('name' => $field['name'], 'value' => $value);
                                                         }
                                                     }
                                                 }
                                             }
                                             if (!$product->description) {
                                                 if (in_array($field['type'], array('textarea', 'wysiwyg')) && $field['name'] == 'description') {
                                                     $product->description = $field['value'];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                         $response = array('ack' => 'ok', 'products' => $products);
                         if (isset($total_count)) {
                             $response['total_count'] = $total_count;
                         }
                         $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                         echo $this->json_encode($response);
                         exit;
                     } else {
                         if ($type === 'categories') {
                             if (!$this->check_hash()) {
                                 exit;
                             }
                             $categories = get_categories(array('taxonomy' => 'product_cat', 'orderby' => 'term_order', 'hide_empty' => 0));
                             $result = array();
                             foreach ($categories as $category) {
                                 $result[] = array('category_id' => $category->term_id, 'name' => $category->name, 'parent_id' => $category->parent);
                             }
                             $response = array('ack' => 'ok', 'categories' => $result, 'total_count' => count($categories));
                             $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                             echo $this->json_encode($response);
                             exit;
                         } else {
                             if ($type === 'orders') {
                                 if (!$this->check_hash()) {
                                     exit;
                                 }
                                 $page = isset($_GET['page']) ? (int) $_GET['page'] : 0;
                                 $count = isset($_GET['count']) ? (int) $_GET['count'] : 0;
                                 $orders = $wpdb->get_results($wpdb->prepare("SELECT (SELECT meta_value FROM `{$wpdb->prefix}postmeta` WHERE post_id = P.id AND meta_key = '_codisto_orderid') AS id, ID AS post_id, post_status AS status FROM `{$wpdb->prefix}posts` AS P WHERE post_type = 'shop_order' AND ID IN (SELECT post_id FROM `{$wpdb->prefix}postmeta` WHERE meta_key = '_codisto_orderid') ORDER BY ID LIMIT %d, %d", $page * $count, $count));
                                 if ($page == 0) {
                                     $total_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$wpdb->prefix}posts` AS P WHERE post_type = 'shop_order' AND ID IN (SELECT post_id FROM `{$wpdb->prefix}postmeta` WHERE meta_key = '_codisto_orderid')");
                                 }
                                 $order_data = array();
                                 foreach ($orders as $order) {
                                     $ship_date = get_post_meta($order->post_id, '_date_shipped', true);
                                     if ($ship_date) {
                                         if (is_numeric($ship_date)) {
                                             $ship_date = date('Y-m-d H:i:s', $ship_date);
                                         }
                                         $order->ship_date = $ship_date;
                                     }
                                     $carrier = get_post_meta($order->post_id, '_tracking_provider', true);
                                     if ($carrier) {
                                         if ($carrier === 'custom') {
                                             $carrier = get_post_meta($order->post_id, '_custom_tracking_provider', true);
                                         }
                                         if ($carrier) {
                                             $order->carrier = $carrier;
                                         }
                                     }
                                     $tracking_number = get_post_meta($order->post_id, '_tracking_number', true);
                                     if ($tracking_number) {
                                         $order->track_number = $tracking_number;
                                     }
                                     unset($order->post_id);
                                     $order_data[] = $order;
                                 }
                                 $response = array('ack' => 'ok', 'orders' => $order_data);
                                 if (isset($total_count)) {
                                     $response['total_count'] = $total_count;
                                 }
                                 $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                                 echo $this->json_encode($response);
                                 exit;
                             } else {
                                 if ($type == 'sync') {
                                     if ($_SERVER['HTTP_X_ACTION'] === 'TEMPLATE') {
                                         if (!$this->check_hash()) {
                                             exit;
                                         }
                                         $ebayDesignDir = WP_CONTENT_DIR . '/ebay/';
                                         $merchantid = (int) $_GET['merchantid'];
                                         if (!$merchantid) {
                                             $merchantid = 0;
                                         }
                                         $templatedb = get_temp_dir() . '/ebay-template-' . $merchantid . '.db';
                                         $db = new PDO('sqlite:' . $templatedb);
                                         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                                         $db->setAttribute(PDO::ATTR_TIMEOUT, 60);
                                         $db->exec('PRAGMA synchronous=0');
                                         $db->exec('PRAGMA temp_store=2');
                                         $db->exec('PRAGMA page_size=65536');
                                         $db->exec('PRAGMA encoding=\'UTF-8\'');
                                         $db->exec('PRAGMA cache_size=15000');
                                         $db->exec('PRAGMA soft_heap_limit=67108864');
                                         $db->exec('PRAGMA journal_mode=MEMORY');
                                         $db->exec('BEGIN EXCLUSIVE TRANSACTION');
                                         $db->exec('CREATE TABLE IF NOT EXISTS File(Name text NOT NULL PRIMARY KEY, Content blob NOT NULL, LastModified datetime NOT NULL, Changed bit NOT NULL DEFAULT -1)');
                                         $db->exec('COMMIT TRANSACTION');
                                         if (isset($_GET['markreceived'])) {
                                             $update = $db->prepare('UPDATE File SET LastModified = ? WHERE Name = ?');
                                             $files = $db->query('SELECT Name FROM File WHERE Changed != 0');
                                             $files->execute();
                                             $db->exec('BEGIN EXCLUSIVE TRANSACTION');
                                             while ($row = $files->fetch()) {
                                                 $stat = stat(WP_CONTENT_DIR . '/ebay/' . $row['Name']);
                                                 $lastModified = strftime('%Y-%m-%d %H:%M:%S', $stat['mtime']);
                                                 $update->bindParam(1, $lastModified);
                                                 $update->bindParam(2, $row['Name']);
                                                 $update->execute();
                                             }
                                             $db->exec('UPDATE File SET Changed = 0');
                                             $db->exec('COMMIT TRANSACTION');
                                             $db = null;
                                             $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, must-revalidate', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                                             echo $this->json_encode(array('ack' => 'ok'));
                                             exit;
                                         } else {
                                             $insert = $db->prepare('INSERT OR IGNORE INTO File(Name, Content, LastModified) VALUES (?, ?, ?)');
                                             $update = $db->prepare('UPDATE File SET Content = ?, Changed = -1 WHERE Name = ? AND LastModified != ?');
                                             $filelist = $this->files_in_dir($ebayDesignDir);
                                             $db->exec('BEGIN EXCLUSIVE TRANSACTION');
                                             foreach ($filelist as $key => $name) {
                                                 try {
                                                     $fileName = $ebayDesignDir . $name;
                                                     if (!in_array($name, array('README'))) {
                                                         $content = @file_get_contents($fileName);
                                                         if ($content !== false) {
                                                             $stat = stat($fileName);
                                                             $lastModified = strftime('%Y-%m-%d %H:%M:%S', $stat['mtime']);
                                                             $update->bindParam(1, $content);
                                                             $update->bindParam(2, $name);
                                                             $update->bindParam(3, $lastModified);
                                                             $update->execute();
                                                             if ($update->rowCount() == 0) {
                                                                 $insert->bindParam(1, $name);
                                                                 $insert->bindParam(2, $content);
                                                                 $insert->bindParam(3, $lastModified);
                                                                 $insert->execute();
                                                             }
                                                         }
                                                     }
                                                 } catch (Exception $e) {
                                                 }
                                             }
                                             $db->exec('COMMIT TRANSACTION');
                                             $tmpDb = wp_tempnam();
                                             $db = new PDO('sqlite:' . $tmpDb);
                                             $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                                             $db->exec('PRAGMA synchronous=0');
                                             $db->exec('PRAGMA temp_store=2');
                                             $db->exec('PRAGMA page_size=512');
                                             $db->exec('PRAGMA encoding=\'UTF-8\'');
                                             $db->exec('PRAGMA cache_size=15000');
                                             $db->exec('PRAGMA soft_heap_limit=67108864');
                                             $db->exec('PRAGMA journal_mode=OFF');
                                             $db->exec('ATTACH DATABASE \'' . $templatedb . '\' AS Source');
                                             $db->exec('CREATE TABLE File AS SELECT * FROM Source.File WHERE Changed != 0');
                                             $db->exec('DETACH DATABASE Source');
                                             $db->exec('VACUUM');
                                             $fileCountStmt = $db->query('SELECT COUNT(*) AS fileCount FROM File');
                                             $fileCountStmt->execute();
                                             $fileCountRow = $fileCountStmt->fetch();
                                             $fileCount = $fileCountRow['fileCount'];
                                             $db = null;
                                             if ($fileCount == 0) {
                                                 $this->sendHttpHeaders('204 No Content', array('Cache-Control' => 'no-cache, must-revalidate', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                                             } else {
                                                 $headers = array('Cache-Control' => 'no-cache, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename=' . basename($tmpDb), 'Content-Length' => filesize($tmpDb));
                                                 $this->sendHttpHeaders('200 OK', $headers);
                                                 while (ob_get_level() > 0) {
                                                     if (!@ob_end_clean()) {
                                                         break;
                                                     }
                                                 }
                                                 flush();
                                                 readfile($tmpDb);
                                             }
                                             unlink($tmpDb);
                                             exit;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     } else {
         if ($type === 'createorder') {
             if (!$this->check_hash()) {
                 exit;
             }
             try {
                 $xml = simplexml_load_string(file_get_contents('php://input'));
                 $ordercontent = $xml->entry->content->children('http://api.codisto.com/schemas/2009/');
                 $wpdb->query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
                 $wpdb->query('START TRANSACTION');
                 $billing_address = $ordercontent->orderaddresses->orderaddress[0];
                 $shipping_address = $ordercontent->orderaddresses->orderaddress[1];
                 $billing_first_name = $billing_last_name = '';
                 if (strpos($billing_address->name, ' ') !== false) {
                     $billing_name = explode(' ', $billing_address->name, 2);
                     $billing_first_name = $billing_name[0];
                     $billing_last_name = $billing_name[1];
                 } else {
                     $billing_first_name = (string) $billing_address->name;
                 }
                 $billing_country_code = (string) $billing_address->countrycode;
                 $billing_division = (string) $billing_address->division;
                 $billing_states = WC()->countries->get_states($billing_country_code);
                 if ($billing_states) {
                     $billing_division_match = preg_replace('/\\s+/', '', strtolower($billing_division));
                     foreach ($billing_states as $state_code => $state_name) {
                         if (preg_replace('/\\s+/', '', strtolower($state_name)) == $billing_division_match) {
                             $billing_division = $state_code;
                             break;
                         }
                     }
                 }
                 $shipping_first_name = $shipping_last_name = '';
                 if (strpos($shipping_address->name, ' ') !== false) {
                     $shipping_name = explode(' ', $shipping_address->name, 2);
                     $shipping_first_name = $shipping_name[0];
                     $shipping_last_name = $shipping_name[1];
                 } else {
                     $shipping_first_name = (string) $shipping_address->name;
                 }
                 $shipping_country_code = (string) $shipping_address->countrycode;
                 $shipping_division = (string) $shipping_address->division;
                 if ($billing_country_code === $shipping_country_code) {
                     $shipping_states = $billing_states;
                 } else {
                     $shipping_states = WC()->countries->get_states($shipping_country_code);
                 }
                 if ($shipping_states) {
                     $shipping_division_match = preg_replace('/\\s+/', '', strtolower($shipping_division));
                     foreach ($shipping_states as $state_code => $state_name) {
                         if (preg_replace('/\\s+/', '', strtolower($state_name)) == $shipping_division_match) {
                             $shipping_division = $state_code;
                             break;
                         }
                     }
                 }
                 $address_data = array('billing_first_name' => $billing_first_name, 'billing_last_name' => $billing_last_name, 'billing_company' => (string) $billing_address->companyname, 'billing_address_1' => (string) $billing_address->address1, 'billing_address_2' => (string) $billing_address->address2, 'billing_city' => (string) $billing_address->place, 'billing_postcode' => (string) $billing_address->postalcode, 'billing_state' => $billing_division, 'billing_country' => $billing_country_code, 'billing_email' => (string) $billing_address->email, 'billing_phone' => (string) $billing_address->phone, 'shipping_first_name' => $shipping_first_name, 'shipping_last_name' => $shipping_last_name, 'shipping_company' => (string) $shipping_address->companyname, 'shipping_address_1' => (string) $shipping_address->address1, 'shipping_address_2' => (string) $shipping_address->address2, 'shipping_city' => (string) $shipping_address->place, 'shipping_postcode' => (string) $shipping_address->postalcode, 'shipping_state' => $shipping_division, 'shipping_country' => $shipping_country_code, 'shipping_email' => (string) $shipping_address->email, 'shipping_phone' => (string) $shipping_address->phone);
                 $email = (string) $billing_address->email;
                 if (!$email) {
                     $email = (string) $shipping_address->email;
                 }
                 if ($email) {
                     $user = get_user_by('email', $email);
                     if (!$user) {
                         $username = (string) $ordercontent->ebayusername;
                         if (!$username) {
                             $username = current(explode('@', $email));
                         }
                         if ($username) {
                             $username = sanitize_user($username);
                         }
                         if (username_exists($username)) {
                             $counter = 1;
                             $newusername = $username . $counter;
                             while (username_exists($newusername)) {
                                 $counter++;
                                 $newusername = $username . $counter;
                             }
                             $username = $newusername;
                         }
                         $password = wp_generate_password();
                         $customer_data = apply_filters('woocommerce_new_customer_data', array('user_login' => $username, 'user_pass' => $password, 'user_email' => $email, 'role' => 'customer'));
                         $customer_id = wp_insert_user($customer_data);
                         foreach ($address_data as $key => $value) {
                             update_user_meta($customer_id, $key, $value);
                         }
                         do_action('woocommerce_created_customer', $customer_id, $customer_data, true);
                     } else {
                         $customer_id = $user->ID;
                     }
                 } else {
                     $customer_id = 0;
                 }
                 $customer_note = @count($ordercontent->instructions) ? strval($ordercontent->instructions) : '';
                 $order_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM `{$wpdb->prefix}posts` AS P WHERE ID IN (SELECT post_id FROM `{$wpdb->prefix}postmeta` WHERE meta_key = '_codisto_orderid' AND meta_value = %d)", (int) $ordercontent->orderid));
                 $shipping = 0;
                 $shipping_tax = 0;
                 $cart_discount = 0;
                 $cart_discount_tax = 0;
                 $total = (double) $ordercontent->ordertotal;
                 $tax = 0;
                 if (!$order_id) {
                     $new_order_data_callback = array($this, 'order_set_date');
                     add_filter('woocommerce_new_order_data', $new_order_data_callback, 1, 1);
                     $order = wc_create_order(array('customer_id' => $customer_id, 'customer_note' => $customer_note, 'created_via' => 'eBay'));
                     remove_filter('woocommerce_new_order_data', $new_order_data_callback);
                     $order_id = $order->id;
                     update_post_meta($order_id, '_codisto_orderid', (int) $ordercontent->orderid);
                     update_post_meta($order_id, '_codisto_ebayuser', (string) $ordercontent->ebayusername);
                     update_post_meta($order_id, '_order_currency', (string) $ordercontent->transactcurrency);
                     update_post_meta($order_id, '_customer_ip_address', '-');
                     delete_post_meta($order_id, '_prices_include_tax');
                     do_action('woocommerce_new_order', $order_id);
                     foreach ($ordercontent->orderlines->orderline as $orderline) {
                         if ($orderline->productcode[0] != 'FREIGHT') {
                             $productcode = (string) $orderline->productcode;
                             if ($productcode == null) {
                                 $productcode = '';
                             }
                             $productname = (string) $orderline->productname;
                             if ($productname == null) {
                                 $productname = '';
                             }
                             $product_id = $orderline->externalreference[0];
                             if ($product_id != null) {
                                 $product_id = intval($product_id);
                             }
                             $variation_id = 0;
                             if (get_post_type($product_id) === 'product_variation') {
                                 $variation_id = $product_id;
                                 $product_id = wp_get_post_parent_id($variation_id);
                                 if (!is_numeric($product_id) || $product_id === 0) {
                                     $product_id = 0;
                                     $variation_id = 0;
                                 }
                             }
                             $qty = (int) $orderline->quantity[0];
                             $item_id = wc_add_order_item($order_id, array('order_item_name' => $productname, 'order_item_type' => 'line_item'));
                             wc_add_order_item_meta($item_id, '_qty', $qty);
                             if (!is_null($product_id) && $product_id !== 0) {
                                 wc_add_order_item_meta($item_id, '_product_id', $product_id);
                                 wc_add_order_item_meta($item_id, '_variation_id', $variation_id);
                                 wc_add_order_item_meta($item_id, '_tax_class', '');
                             } else {
                                 wc_add_order_item_meta($item_id, '_product_id', 0);
                                 wc_add_order_item_meta($item_id, '_variation_id', 0);
                                 wc_add_order_item_meta($item_id, '_tax_class', '');
                             }
                             $line_total = wc_format_decimal((double) $orderline->linetotal);
                             $line_total_tax = wc_format_decimal((double) $orderline->linetotalinctax - (double) $orderline->linetotal);
                             wc_add_order_item_meta($item_id, '_line_subtotal', $line_total);
                             wc_add_order_item_meta($item_id, '_line_total', $line_total);
                             wc_add_order_item_meta($item_id, '_line_subtotal_tax', $line_total_tax);
                             wc_add_order_item_meta($item_id, '_line_tax', $line_total_tax);
                             wc_add_order_item_meta($item_id, '_line_tax_data', array('total' => array(1 => $line_total_tax), 'subtotal' => array(1 => $line_total_tax)));
                             $tax += $line_total_tax;
                         } else {
                             $item_id = wc_add_order_item($order_id, array('order_item_name' => (string) $orderline->productname, 'order_item_type' => 'shipping'));
                             wc_add_order_item_meta($item_id, 'cost', wc_format_decimal((double) $orderline->linetotal));
                             $shipping += (double) $orderline->linetotal;
                             $shipping_tax += (double) $orderline->linetotalinctax - (double) $orderline->linetotal;
                         }
                     }
                     if ($ordercontent->paymentstatus == 'complete') {
                         $transaction_id = (string) $ordercontent->orderpayments[0]->orderpayment->transactionid;
                         if ($transaction_id) {
                             update_post_meta($order_id, '_payment_method', 'paypal');
                             update_post_meta($order_id, '_payment_method_title', __('PayPal', 'woocommerce'));
                             update_post_meta($order_id, '_transaction_id', $transaction_id);
                         } else {
                             update_post_meta($order_id, '_payment_method', 'bacs');
                             update_post_meta($order_id, '_payment_method_title', __('BACS', 'woocommerce'));
                         }
                         // payment_complete
                         add_post_meta($order_id, '_paid_date', current_time('mysql'), true);
                         if (!get_post_meta($order_id, '_order_stock_reduced', true)) {
                             $order->reduce_order_stock();
                         }
                     }
                 } else {
                     $order = wc_get_order($order_id);
                     foreach ($ordercontent->orderlines->orderline as $orderline) {
                         if ($orderline->productcode[0] != 'FREIGHT') {
                             $line_total = wc_format_decimal((double) $orderline->linetotal);
                             $line_total_tax = wc_format_decimal((double) $orderline->linetotalinctax - (double) $orderline->linetotal);
                             $tax += $line_total_tax;
                         } else {
                             $order->remove_order_items('shipping');
                             $item_id = wc_add_order_item($order_id, array('order_item_name' => (string) $orderline->productname, 'order_item_type' => 'shipping'));
                             wc_add_order_item_meta($item_id, 'cost', wc_format_decimal((double) $orderline->linetotal));
                             $shipping += (double) $orderline->linetotal;
                             $shipping_tax += (double) $orderline->linetotalinctax - (double) $orderline->linetotal;
                         }
                     }
                     if ($ordercontent->paymentstatus == 'complete') {
                         $transaction_id = (string) $ordercontent->orderpayments[0]->orderpayment->transactionid;
                         if ($transaction_id) {
                             update_post_meta($order_id, '_payment_method', 'paypal');
                             update_post_meta($order_id, '_payment_method_title', __('PayPal', 'woocommerce'));
                             update_post_meta($order_id, '_transaction_id', $transaction_id);
                         } else {
                             update_post_meta($order_id, '_payment_method', 'bacs');
                             update_post_meta($order_id, '_payment_method_title', __('BACS', 'woocommerce'));
                         }
                         // payment_complete
                         add_post_meta($order_id, '_paid_date', current_time('mysql'), true);
                         if (!get_post_meta($order_id, '_order_stock_reduced', true)) {
                             $order->reduce_order_stock();
                         }
                     }
                 }
                 foreach ($address_data as $key => $value) {
                     update_post_meta($order_id, '_' . $key, $value);
                 }
                 $order->remove_order_items('tax');
                 $order->add_tax(1, $tax, $shipping_tax);
                 $order->set_total($shipping, 'shipping');
                 $order->set_total($shipping_tax, 'shipping_tax');
                 $order->set_total($cart_discount, 'cart_discount');
                 $order->set_total($cart_discount_tax, 'cart_discount_tax');
                 $order->set_total($tax, 'tax');
                 $order->set_total($total, 'total');
                 if ($ordercontent->orderstate == 'cancelled') {
                     if (!$order->has_status('cancelled')) {
                         // update_status
                         $order->post_status = 'wc-cancelled';
                         $update_post_data = array('ID' => $order_id, 'post_status' => 'wc-cancelled', 'post_date' => current_time('mysql', 0), 'post_date_gmt' => current_time('mysql', 1));
                         wp_update_post($update_post_data);
                         $order->decrease_coupon_usage_counts();
                         wc_delete_shop_order_transients($order_id);
                     }
                 } else {
                     if ($ordercontent->orderstate == 'inprogress' || $ordercontent->orderstate == 'processing') {
                         if ($ordercontent->paymentstatus == 'complete') {
                             if (!$order->has_status('processing')) {
                                 // update_status
                                 $order->post_status = 'wc-processing';
                                 $update_post_data = array('ID' => $order_id, 'post_status' => 'wc-processing', 'post_date' => current_time('mysql', 0), 'post_date_gmt' => current_time('mysql', 1));
                                 wp_update_post($update_post_data);
                             }
                         } else {
                             if (!$order->has_status('pending')) {
                                 // update_status
                                 $order->post_status = 'wc-pending';
                                 $update_post_data = array('ID' => $order_id, 'post_status' => 'wc-pending', 'post_date' => current_time('mysql', 0), 'post_date_gmt' => current_time('mysql', 1));
                                 wp_update_post($update_post_data);
                             }
                         }
                     } else {
                         if ($ordercontent->orderstate == 'complete') {
                             if (!$order->has_status('completed')) {
                                 // update_status
                                 $order->post_status = 'wc-completed';
                                 $update_post_data = array('ID' => $order_id, 'post_status' => 'wc-completed', 'post_date' => current_time('mysql', 0), 'post_date_gmt' => current_time('mysql', 1));
                                 wp_update_post($update_post_data);
                                 $order->record_product_sales();
                                 $order->increase_coupon_usage_counts();
                                 update_post_meta($order_id, '_completed_date', current_time('mysql'));
                                 wc_delete_shop_order_transients($order_id);
                             }
                         }
                     }
                 }
                 $wpdb->query('COMMIT');
                 $response = array('ack' => 'ok', 'orderid' => $order_id);
                 $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                 echo $this->json_encode($response);
                 exit;
             } catch (Exception $e) {
                 $wpdb->query('ROLLBACK');
                 $response = array('ack' => 'failed', 'message' => $e->getMessage() . '  ' . $e->getFile() . ' ' . $e->getLine());
                 $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                 echo $this->json_encode($response);
                 exit;
             }
         } else {
             if ($type == 'sync') {
                 if ($_SERVER['HTTP_X_ACTION'] === 'TEMPLATE') {
                     if (!$this->check_hash()) {
                         exit;
                     }
                     $ebayDesignDir = WP_CONTENT_DIR . '/ebay/';
                     $tmpPath = wp_tempnam();
                     @file_put_contents($tmpPath, file_get_contents('php://input'));
                     $db = new PDO('sqlite:' . $tmpPath);
                     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                     $db->exec('PRAGMA synchronous=0');
                     $db->exec('PRAGMA temp_store=2');
                     $db->exec('PRAGMA page_size=65536');
                     $db->exec('PRAGMA encoding=\'UTF-8\'');
                     $db->exec('PRAGMA cache_size=15000');
                     $db->exec('PRAGMA soft_heap_limit=67108864');
                     $db->exec('PRAGMA journal_mode=MEMORY');
                     $files = $db->prepare('SELECT Name, Content FROM File');
                     $files->execute();
                     $files->bindColumn(1, $name);
                     $files->bindColumn(2, $content);
                     while ($files->fetch()) {
                         $fileName = $ebayDesignDir . $name;
                         if (strpos($name, '..') === false) {
                             if (!file_exists($fileName)) {
                                 $dir = dirname($fileName);
                                 if (!is_dir($dir)) {
                                     mkdir($dir . '/', 0755, true);
                                 }
                                 @file_put_contents($fileName, $content);
                             }
                         }
                     }
                     $db = null;
                     unlink($tmpPath);
                     $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                     echo $this->json_encode(array('ack' => 'ok'));
                     exit;
                 }
             } else {
                 if ($type == 'index/calc') {
                     $product_ids = array();
                     $quantities = array();
                     for ($i = 0;; $i++) {
                         if (!isset($_POST['PRODUCTCODE(' . $i . ')'])) {
                             break;
                         }
                         $productid = (int) $_POST['PRODUCTID(' . $i . ')'];
                         if (!$productid) {
                             $productcode = $_POST['PRODUCTCODE(' . $i . ')'];
                             $productid = wc_get_product_id_by_sku($productcode);
                         }
                         $productqty = $_POST['PRODUCTQUANTITY(' . $i . ')'];
                         if (!$productqty && $productqty != 0) {
                             $productqty = 1;
                         }
                         WC()->cart->add_to_cart($productid, $productqty);
                     }
                     WC()->customer->set_location($_POST['COUNTRYCODE'], $_POST['DIVISION'], $_POST['POSTALCODE'], $_POST['PLACE']);
                     WC()->customer->set_shipping_location($_POST['COUNTRYCODE'], $_POST['DIVISION'], $_POST['POSTALCODE'], $_POST['PLACE']);
                     WC()->cart->calculate_totals();
                     WC()->cart->calculate_shipping();
                     $response = '';
                     $idx = 0;
                     $methods = WC()->shipping()->get_shipping_methods();
                     foreach ($methods as $method) {
                         if (file_exists(plugin_dir_path(__FILE__) . 'shipping/' . $method->id)) {
                             include plugin_dir_path(__FILE__) . 'shipping/' . $method->id;
                         } else {
                             foreach ($method->rates as $method => $rate) {
                                 $method_name = $rate->get_label();
                                 if (!$method_name) {
                                     $method_name = 'Shipping';
                                 }
                                 $method_cost = $rate->cost;
                                 if (is_numeric($method_cost)) {
                                     if (isset($rate->taxes) && is_array($rate->taxes)) {
                                         foreach ($rate->taxes as $tax) {
                                             if (is_numeric($tax)) {
                                                 $method_cost += $tax;
                                             }
                                         }
                                     }
                                     $response .= ($idx > 0 ? '&' : '') . 'FREIGHTNAME(' . $idx . ')=' . rawurlencode($method_name) . '&FREIGHTCHARGEINCTAX(' . $idx . ')=' . number_format((double) $method_cost, 2, '.', '');
                                     $idx++;
                                 }
                             }
                         }
                     }
                     $this->sendHttpHeaders('200 OK', array('Content-Type' => 'application/json', 'Cache-Control' => 'no-cache, no-store', 'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT', 'Pragma' => 'no-cache'));
                     echo $response;
                     exit;
                 }
             }
         }
     }
 }
コード例 #7
0
 /**
  * create_order function.
  * @access public
  * @throws Exception
  * @return int
  */
 public function create_order()
 {
     global $wpdb;
     // Give plugins the opportunity to create an order themselves
     $order_id = apply_filters('woocommerce_create_order', null, $this);
     if (is_numeric($order_id)) {
         return $order_id;
     }
     // Create Order (send cart variable so we can record items and reduce inventory). Only create if this is a new order, not if the payment was rejected.
     $order_data = apply_filters('woocommerce_new_order_data', array('post_type' => 'shop_order', 'post_title' => sprintf(__('Order – %s', 'woocommerce'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'woocommerce'))), 'post_status' => 'publish', 'ping_status' => 'closed', 'post_excerpt' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '', 'post_author' => 1, 'post_password' => uniqid('order_')));
     // Insert or update the post data
     $create_new_order = true;
     if (WC()->session->order_awaiting_payment > 0) {
         $order_id = absint(WC()->session->order_awaiting_payment);
         /* Check order is unpaid by getting its status */
         $terms = wp_get_object_terms($order_id, 'shop_order_status', array('fields' => 'slugs'));
         $order_status = isset($terms[0]) ? $terms[0] : 'pending';
         // Resume the unpaid order if its pending
         if ($order_status == 'pending' || $order_status == 'failed') {
             // Update the existing order as we are resuming it
             $create_new_order = false;
             $order_data['ID'] = $order_id;
             wp_update_post($order_data);
             // Clear the old line items - we'll add these again in case they changed
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d )", $order_id));
             $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d", $order_id));
             // Trigger an action for the resumed order
             do_action('woocommerce_resume_order', $order_id);
         }
     }
     if ($create_new_order) {
         $order_id = wp_insert_post($order_data, true);
         if (is_wp_error($order_id)) {
             throw new Exception('Error: Unable to create order. Please try again.');
         } else {
             do_action('woocommerce_new_order', $order_id);
         }
     }
     // Store user data
     if ($this->checkout_fields['billing']) {
         foreach ($this->checkout_fields['billing'] as $key => $field) {
             update_post_meta($order_id, '_' . $key, $this->posted[$key]);
             if ($this->customer_id && apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                 update_user_meta($this->customer_id, $key, $this->posted[$key]);
             }
         }
     }
     if ($this->checkout_fields['shipping'] && WC()->cart->needs_shipping()) {
         foreach ($this->checkout_fields['shipping'] as $key => $field) {
             $postvalue = false;
             if ($this->posted['ship_to_different_address'] == false) {
                 if (isset($this->posted[str_replace('shipping_', 'billing_', $key)])) {
                     $postvalue = $this->posted[str_replace('shipping_', 'billing_', $key)];
                     update_post_meta($order_id, '_' . $key, $postvalue);
                 }
             } else {
                 $postvalue = $this->posted[$key];
                 update_post_meta($order_id, '_' . $key, $postvalue);
             }
             // User
             if ($postvalue && $this->customer_id && apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                 update_user_meta($this->customer_id, $key, $postvalue);
             }
         }
     }
     // Save any other user meta
     if ($this->customer_id) {
         do_action('woocommerce_checkout_update_user_meta', $this->customer_id, $this->posted);
     }
     // Store the line items to the new/resumed order
     foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
         $_product = $values['data'];
         // Add line item
         $item_id = wc_add_order_item($order_id, array('order_item_name' => $_product->get_title(), 'order_item_type' => 'line_item'));
         // Add line item meta
         if ($item_id) {
             wc_add_order_item_meta($item_id, '_qty', apply_filters('woocommerce_stock_amount', $values['quantity']));
             wc_add_order_item_meta($item_id, '_tax_class', $_product->get_tax_class());
             wc_add_order_item_meta($item_id, '_product_id', $values['product_id']);
             wc_add_order_item_meta($item_id, '_variation_id', $values['variation_id']);
             wc_add_order_item_meta($item_id, '_line_subtotal', wc_format_decimal($values['line_subtotal']));
             wc_add_order_item_meta($item_id, '_line_total', wc_format_decimal($values['line_total']));
             wc_add_order_item_meta($item_id, '_line_tax', wc_format_decimal($values['line_tax']));
             wc_add_order_item_meta($item_id, '_line_subtotal_tax', wc_format_decimal($values['line_subtotal_tax']));
             // Store variation data in meta so admin can view it
             if ($values['variation'] && is_array($values['variation'])) {
                 foreach ($values['variation'] as $key => $value) {
                     wc_add_order_item_meta($item_id, esc_attr(str_replace('attribute_', '', $key)), $value);
                 }
             }
             // Add line item meta for backorder status
             if ($_product->backorders_require_notification() && $_product->is_on_backorder($values['quantity'])) {
                 wc_add_order_item_meta($item_id, apply_filters('woocommerce_backordered_item_meta_name', __('Backordered', 'woocommerce'), $cart_item_key, $order_id), $values['quantity'] - max(0, $_product->get_total_stock()));
             }
             // Allow plugins to add order item meta
             do_action('woocommerce_add_order_item_meta', $item_id, $values, $cart_item_key);
         }
     }
     // Store fees
     foreach (WC()->cart->get_fees() as $fee) {
         $item_id = wc_add_order_item($order_id, array('order_item_name' => $fee->name, 'order_item_type' => 'fee'));
         if ($fee->taxable) {
             wc_add_order_item_meta($item_id, '_tax_class', $fee->tax_class);
         } else {
             wc_add_order_item_meta($item_id, '_tax_class', '0');
         }
         wc_add_order_item_meta($item_id, '_line_total', wc_format_decimal($fee->amount));
         wc_add_order_item_meta($item_id, '_line_tax', wc_format_decimal($fee->tax));
     }
     // Store shipping for all packages
     $packages = WC()->shipping->get_packages();
     foreach ($packages as $i => $package) {
         if (isset($package['rates'][$this->shipping_methods[$i]])) {
             $method = $package['rates'][$this->shipping_methods[$i]];
             $item_id = wc_add_order_item($order_id, array('order_item_name' => $method->label, 'order_item_type' => 'shipping'));
             if ($item_id) {
                 wc_add_order_item_meta($item_id, 'method_id', $method->id);
                 wc_add_order_item_meta($item_id, 'cost', wc_format_decimal($method->cost));
                 do_action('woocommerce_add_shipping_order_item', $order_id, $item_id, $i);
             }
         }
     }
     // Store tax rows
     foreach (array_keys(WC()->cart->taxes + WC()->cart->shipping_taxes) as $key) {
         $code = WC()->cart->tax->get_rate_code($key);
         if ($code) {
             $item_id = wc_add_order_item($order_id, array('order_item_name' => $code, 'order_item_type' => 'tax'));
             // Add line item meta
             if ($item_id) {
                 wc_add_order_item_meta($item_id, 'rate_id', $key);
                 wc_add_order_item_meta($item_id, 'label', WC()->cart->tax->get_rate_label($key));
                 wc_add_order_item_meta($item_id, 'compound', absint(WC()->cart->tax->is_compound($key) ? 1 : 0));
                 wc_add_order_item_meta($item_id, 'tax_amount', wc_format_decimal(isset(WC()->cart->taxes[$key]) ? WC()->cart->taxes[$key] : 0));
                 wc_add_order_item_meta($item_id, 'shipping_tax_amount', wc_format_decimal(isset(WC()->cart->shipping_taxes[$key]) ? WC()->cart->shipping_taxes[$key] : 0));
             }
         }
     }
     // Store coupons
     if ($applied_coupons = WC()->cart->get_coupons()) {
         foreach ($applied_coupons as $code => $coupon) {
             $item_id = wc_add_order_item($order_id, array('order_item_name' => $code, 'order_item_type' => 'coupon'));
             // Add line item meta
             if ($item_id) {
                 wc_add_order_item_meta($item_id, 'discount_amount', isset(WC()->cart->coupon_discount_amounts[$code]) ? WC()->cart->coupon_discount_amounts[$code] : 0);
             }
         }
     }
     if ($this->payment_method) {
         update_post_meta($order_id, '_payment_method', $this->payment_method->id);
         update_post_meta($order_id, '_payment_method_title', $this->payment_method->get_title());
     }
     if (empty($this->posted['billing_email']) && is_user_logged_in()) {
         $current_user = wp_get_current_user();
         update_post_meta($order_id, '_billing_email', $current_user->user_email);
     }
     update_post_meta($order_id, '_order_shipping', wc_format_decimal(WC()->cart->shipping_total));
     update_post_meta($order_id, '_order_discount', wc_format_decimal(WC()->cart->get_order_discount_total()));
     update_post_meta($order_id, '_cart_discount', wc_format_decimal(WC()->cart->get_cart_discount_total()));
     update_post_meta($order_id, '_order_tax', wc_format_decimal(WC()->cart->tax_total));
     update_post_meta($order_id, '_order_shipping_tax', wc_format_decimal(WC()->cart->shipping_tax_total));
     update_post_meta($order_id, '_order_total', wc_format_decimal(WC()->cart->total, get_option('woocommerce_price_num_decimals')));
     update_post_meta($order_id, '_order_key', 'wc_' . apply_filters('woocommerce_generate_order_key', uniqid('order_')));
     update_post_meta($order_id, '_customer_user', absint($this->customer_id));
     update_post_meta($order_id, '_order_currency', get_woocommerce_currency());
     update_post_meta($order_id, '_prices_include_tax', get_option('woocommerce_prices_include_tax'));
     update_post_meta($order_id, '_customer_ip_address', isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
     update_post_meta($order_id, '_customer_user_agent', isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
     // Let plugins add meta
     do_action('woocommerce_checkout_update_order_meta', $order_id, $this->posted);
     // Order status
     wp_set_object_terms($order_id, 'pending', 'shop_order_status');
     return $order_id;
 }
コード例 #8
0
 /**
  * Save meta box data
  */
 public static function save($post_id, $post)
 {
     global $wpdb;
     // Save tax rows
     $total_tax = 0;
     $total_shipping_tax = 0;
     if (isset($_POST['order_taxes_id'])) {
         $get_values = array('order_taxes_id', 'order_taxes_rate_id', 'order_taxes_amount', 'order_taxes_shipping_amount');
         foreach ($get_values as $value) {
             ${$value} = isset($_POST[$value]) ? $_POST[$value] : array();
         }
         foreach ($order_taxes_id as $item_id => $value) {
             if ($item_id == 'new') {
                 foreach ($value as $new_key => $new_value) {
                     $rate_id = absint($order_taxes_rate_id[$item_id][$new_key]);
                     if ($rate_id) {
                         $rate = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $rate_id));
                         $label = $rate->tax_rate_name ? $rate->tax_rate_name : WC()->countries->tax_or_vat();
                         $compound = $rate->tax_rate_compound ? 1 : 0;
                         $code = array();
                         $code[] = $rate->tax_rate_country;
                         $code[] = $rate->tax_rate_state;
                         $code[] = $rate->tax_rate_name ? $rate->tax_rate_name : 'TAX';
                         $code[] = absint($rate->tax_rate_priority);
                         $code = strtoupper(implode('-', array_filter($code)));
                     } else {
                         $code = '';
                         $label = WC()->countries->tax_or_vat();
                     }
                     // Add line item
                     $new_id = wc_add_order_item($post_id, array('order_item_name' => wc_clean($code), 'order_item_type' => 'tax'));
                     // Add line item meta
                     if ($new_id) {
                         wc_update_order_item_meta($new_id, 'rate_id', $rate_id);
                         wc_update_order_item_meta($new_id, 'label', $label);
                         wc_update_order_item_meta($new_id, 'compound', $compound);
                         if (isset($order_taxes_amount[$item_id][$new_key])) {
                             wc_update_order_item_meta($new_id, 'tax_amount', wc_format_decimal($order_taxes_amount[$item_id][$new_key]));
                             $total_tax += wc_format_decimal($order_taxes_amount[$item_id][$new_key]);
                         }
                         if (isset($order_taxes_shipping_amount[$item_id][$new_key])) {
                             wc_update_order_item_meta($new_id, 'shipping_tax_amount', wc_format_decimal($order_taxes_shipping_amount[$item_id][$new_key]));
                             $total_shipping_tax += wc_format_decimal($order_taxes_shipping_amount[$item_id][$new_key]);
                         }
                     }
                 }
             } else {
                 $item_id = absint($item_id);
                 $rate_id = absint($order_taxes_rate_id[$item_id]);
                 if ($rate_id) {
                     $rate = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %s", $rate_id));
                     $label = $rate->tax_rate_name ? $rate->tax_rate_name : WC()->countries->tax_or_vat();
                     $compound = $rate->tax_rate_compound ? 1 : 0;
                     $code = array();
                     $code[] = $rate->tax_rate_country;
                     $code[] = $rate->tax_rate_state;
                     $code[] = $rate->tax_rate_name ? $rate->tax_rate_name : 'TAX';
                     $code[] = absint($rate->tax_rate_priority);
                     $code = strtoupper(implode('-', array_filter($code)));
                 } else {
                     $code = '';
                     $label = WC()->countries->tax_or_vat();
                 }
                 $wpdb->update($wpdb->prefix . "woocommerce_order_items", array('order_item_name' => wc_clean($code)), array('order_item_id' => $item_id), array('%s'), array('%d'));
                 wc_update_order_item_meta($item_id, 'rate_id', $rate_id);
                 wc_update_order_item_meta($item_id, 'label', $label);
                 wc_update_order_item_meta($item_id, 'compound', $compound);
                 if (isset($order_taxes_amount[$item_id])) {
                     wc_update_order_item_meta($item_id, 'tax_amount', wc_format_decimal($order_taxes_amount[$item_id]));
                     $total_tax += wc_format_decimal($order_taxes_amount[$item_id]);
                 }
                 if (isset($order_taxes_shipping_amount[$item_id])) {
                     wc_update_order_item_meta($item_id, 'shipping_tax_amount', wc_format_decimal($order_taxes_shipping_amount[$item_id]));
                     $total_shipping_tax += wc_format_decimal($order_taxes_shipping_amount[$item_id]);
                 }
             }
         }
     }
     // Update totals
     update_post_meta($post_id, '_order_tax', wc_format_decimal($total_tax));
     update_post_meta($post_id, '_order_shipping_tax', wc_format_decimal($total_shipping_tax));
     update_post_meta($post_id, '_order_discount', wc_format_decimal($_POST['_order_discount']));
     update_post_meta($post_id, '_order_total', wc_format_decimal($_POST['_order_total']));
     // Shipping Rows
     $order_shipping = 0;
     if (isset($_POST['shipping_method_id'])) {
         $get_values = array('shipping_method_id', 'shipping_method_title', 'shipping_method', 'shipping_cost');
         foreach ($get_values as $value) {
             ${$value} = isset($_POST[$value]) ? $_POST[$value] : array();
         }
         foreach ($shipping_method_id as $item_id => $value) {
             if ($item_id == 'new') {
                 foreach ($value as $new_key => $new_value) {
                     $method_id = wc_clean($shipping_method[$item_id][$new_key]);
                     $method_title = wc_clean($shipping_method_title[$item_id][$new_key]);
                     $cost = wc_format_decimal($shipping_cost[$item_id][$new_key]);
                     $new_id = wc_add_order_item($post_id, array('order_item_name' => $method_title, 'order_item_type' => 'shipping'));
                     if ($new_id) {
                         wc_add_order_item_meta($new_id, 'method_id', $method_id);
                         wc_add_order_item_meta($new_id, 'cost', $cost);
                     }
                     $order_shipping += $cost;
                 }
             } else {
                 $item_id = absint($item_id);
                 $method_id = wc_clean($shipping_method[$item_id]);
                 $method_title = wc_clean($shipping_method_title[$item_id]);
                 $cost = wc_format_decimal($shipping_cost[$item_id]);
                 $wpdb->update($wpdb->prefix . "woocommerce_order_items", array('order_item_name' => $method_title), array('order_item_id' => $item_id), array('%s'), array('%d'));
                 wc_update_order_item_meta($item_id, 'method_id', $method_id);
                 wc_update_order_item_meta($item_id, 'cost', $cost);
                 $order_shipping += $cost;
             }
         }
     }
     // Delete rows
     if (isset($_POST['delete_order_item_id'])) {
         $delete_ids = $_POST['delete_order_item_id'];
         foreach ($delete_ids as $id) {
             wc_delete_order_item(absint($id));
         }
     }
     delete_post_meta($post_id, '_shipping_method');
     delete_post_meta($post_id, '_shipping_method_title');
     update_post_meta($post_id, '_order_shipping', $order_shipping);
 }
コード例 #9
0
    /**
     * Create renewal order
     * Based on the WooCommerce procedure found in class-wc-checkout.php
     * 
     * @access public
     * @param object $subscription
     * @return int
     */
    public static function create_renewal_order($subscription)
    {
        // Get instance of main plugin class to access settings
        $subscriptio = Subscriptio::get_instance();

        // Since WooCommerce 2.2 order statuses are stored as post statuses
        $post_status = Subscriptio::wc_version_gte('2.2') ? 'wc-pending' : 'publish';

        // Prepare post properties
        $order_data = array(
            'post_type' 	=> 'shop_order',
            'post_title' 	=> sprintf(__('Order – %s', 'subscriptio'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'subscriptio'))),
            'post_status' 	=> $post_status,
            'ping_status'	=> 'closed',
            'post_excerpt' 	=> $subscription->renewal_customer_note,
            'post_author' 	=> 1,
            'post_password'	=> uniqid('order_'),
        );

        // Insert post into database
        $order_id = wp_insert_post($order_data, true);

        // Successfully inserted order post?
        if (is_wp_error($order_id)) {
            throw new Exception(__('Unable to create renewal order - failed inserting post.', 'subscriptio'));
        }

        // Load user meta
        $user_meta = Subscriptio::unwrap_post_meta(get_user_meta($subscription->user_id));

        // Insert billing and shipping details
        $billing_shipping_fields = array(
            'billing'  => array(
                '_first_name',
                '_last_name',
                '_company',
                '_address_1',
                '_address_2',
                '_city',
                '_state',
                '_postcode',
                '_country',
                '_email',
                '_phone',
            ),
        );

        // Check if subscription needs shipping
        if ($subscription->needs_shipping()) {
            $billing_shipping_fields['shipping'] = array(
                '_first_name',
                '_last_name',
                '_company',
                '_address_1',
                '_address_2',
                '_city',
                '_state',
                '_postcode',
                '_country',
            );
        }

        // Iterate over billing/shipping fields and save them
        foreach ($billing_shipping_fields as $type => $fields) {
            foreach ($fields as $field) {

                // Billing fields
                if ($type == 'billing' && isset($user_meta[$type . $field])) {
                    $field_value = $user_meta[$type . $field];
                }

                // Shipping fields
                else if ($type == 'shipping' && isset($subscription->shipping_address['_' . $type . $field])) {
                    $field_value = $subscription->shipping_address['_' . $type . $field];
                }

                // In case some field does not exist
                else {
                    $field_value = '';
                }

                // Save field to post meta
                update_post_meta($order_id, '_' . $type . $field, $field_value);
            }
        }

        // Add other meta fields
        $other_meta_fields = array(
            '_order_shipping'       => $subscription->renewal_order_shipping,
            '_order_shipping_tax'   => $subscription->renewal_order_shipping_tax,
            '_cart_discount'        => $subscription->renewal_cart_discount,
            '_order_discount'       => $subscription->renewal_order_discount,
            '_order_tax'            => $subscription->renewal_order_tax,
            '_order_total'          => $subscription->renewal_order_total,
            '_customer_user'        => $subscription->user_id,
            '_order_currency'       => $subscription->renewal_order_currency,
            '_order_key'            => 'wc_' . apply_filters('woocommerce_generate_order_key', uniqid('order_')),
            '_prices_include_tax'   => $subscription->renewal_prices_include_tax,
            '_customer_ip_address'  => $subscription->renewal_customer_ip_address,
            '_customer_user_agent'  => $subscription->renewal_customer_user_agent,
            '_payment_method'       => '',  // Not yet paid
            '_payment_method_title' => '',  // Not yet paid
            '_subscriptio_renewal'  => 'yes',
        );

        foreach ($other_meta_fields as $field_key => $field_value) {
            update_post_meta($order_id, $field_key, $field_value);
        }

        // Check if subscription product is variable
        $product_id_to_use = !empty($subscription->variation_id) ? $subscription->variation_id : $subscription->product_id;

        // Check if product still exists
        if (Subscriptio::product_is_active($product_id_to_use)) {

            // Load product object
            $product = new WC_Product($product_id_to_use);

            // Get product name
            $product_title = $product->get_title();

            // Update product name on subscription if it was changed
            if ($product_title != $subscription->product_name) {
                $subscription->update_subscription_details(array(
                    'product_name'  => $product_title,
                ));
            }
        }

        // If not - use saved product "snapshot" from previous order
        else {
            $product_title = $subscription->product_name;
        }

        // Add line item (product) to order
        $item_id = wc_add_order_item($order_id, array(
            'order_item_name'   => $product_title,
            'order_item_type'   => 'line_item',
        ));

        if (!$item_id) {
            throw new Exception(__('Unable to add product to renewal order.', 'subscriptio'));
        }

        // Add line item meta
        $item_meta = array(
            '_qty'                  => !empty($subscription->quantity) ? $subscription->quantity : 1,
            '_tax_class'            => $subscription->renewal_tax_class,
            '_product_id'           => $subscription->product_id,
            '_variation_id'         => !empty($subscription->variation_id) ? $subscription->variation_id : '',
            '_line_subtotal'        => wc_format_decimal($subscription->renewal_line_subtotal),
            '_line_subtotal_tax'    => wc_format_decimal($subscription->renewal_line_subtotal_tax),
            '_line_total'           => wc_format_decimal($subscription->renewal_line_total),
            '_line_tax'             => wc_format_decimal($subscription->renewal_line_tax),
        );

        foreach ($item_meta as $item_meta_key => $item_meta_value) {
            wc_add_order_item_meta($item_id, $item_meta_key, $item_meta_value);
        }

        // Save shipping info (if any)
        if (!empty($subscription->shipping)) {
            $shipping_item_id = wc_add_order_item($order_id, array(
                'order_item_name'   => $subscription->shipping['name'],
                'order_item_type'   => 'shipping',
            ));

            wc_add_order_item_meta($shipping_item_id, 'method_id', $subscription->shipping['method_id']);
            wc_add_order_item_meta($shipping_item_id, 'cost', wc_format_decimal($subscription->shipping['cost']));
        }

        // Save taxes (if any)
        foreach ($subscription->taxes as $tax) {
            $tax_item_id = wc_add_order_item($order_id, array(
                'order_item_name'   => $tax['name'],
                'order_item_type'   => 'tax',
            ));

            wc_add_order_item_meta($tax_item_id, 'rate_id', $tax['rate_id']);
            wc_add_order_item_meta($tax_item_id, 'label', $tax['label']);
            wc_add_order_item_meta($tax_item_id, 'compound', $tax['compound']);
            wc_add_order_item_meta($tax_item_id, 'tax_amount', wc_format_decimal($tax['tax_amount'], 4));
            wc_add_order_item_meta($tax_item_id, 'shipping_tax_amount', wc_format_decimal($tax['shipping_tax_amount'], 4));
        }

        // Schedule payment due reminders
        if ($payment_due_timestamp = wp_next_scheduled('subscriptio_scheduled_payment', $subscription->id)) {
            foreach ($subscription->get_reminders('pre_payment_due', $payment_due_timestamp) as $timestamp) {
                Subscriptio_Scheduler::schedule_reminder($subscription->id, $timestamp);
            }
        }

        // Update appropriate subscription fields with new order id
        $subscription->update_subscription_details(array(
            'last_order_id' => $order_id,
            'all_order_ids' => $order_id,
        ));

        // Create a new order object
        $order = new WC_Order($order_id);

        // Set status to pending (pre- WooCommerce 2.2)
        if (!Subscriptio::wc_version_gte('2.2')) {
            $order->update_status('pending');
        }

        // Send New Order email
        Subscriptio_Mailer::send('new_order', $order);

        return $order_id;
    }
 function update_orders()
 {
     global $wpdb;
     // loop through orders
     $wpec_order_table = $wpdb->prefix . 'wpsc_purchase_logs';
     $wpec_formdata_table = $wpdb->prefix . 'wpsc_submited_form_data';
     $order_data = $wpdb->get_results("SELECT * FROM `" . $wpec_order_table . "`", ARRAY_A);
     foreach ((array) $order_data as $order) {
         $post_title = "WPEC Order - " . $order['id'] . " - " . date('Y-m-d H:i:s', $order['date']);
         // check to see if order has already been added
         $order_exists = $wpdb->get_var($wpdb->prepare("\n          SELECT ID FROM {$wpdb->posts} \n          WHERE post_title = %s \n          AND post_type = 'shop_order'", $post_title));
         if ($order_exists) {
             continue;
         }
         // create a new post with custom post type 'shop_order'
         $post = array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $this->post_author, 'post_parent' => '0', 'post_status' => 'publish', 'post_title' => $post_title, 'post_type' => 'shop_order');
         // insert post
         $post_id = wp_insert_post($post, true);
         // wpec tables
         $wpsc_cart_contents_table = $wpdb->prefix . 'wpsc_cart_contents';
         $wpsc_purchase_logs_table = $wpdb->prefix . 'wpsc_purchase_logs';
         $wpsc_submited_form_data_table = $wpdb->prefix . 'wpsc_submited_form_data';
         $wpsc_checkout_forms_table = $wpdb->prefix . 'wpsc_checkout_forms';
         /*
           CUSTOMER DATA
         */
         $userinfo = $wpdb->get_results("\n          SELECT \n          `" . $wpsc_submited_form_data_table . "`.`value`,\n          `" . $wpsc_checkout_forms_table . "`.`name`,\n          `" . $wpsc_checkout_forms_table . "`.`unique_name`\n          FROM `" . $wpsc_checkout_forms_table . "`\n          LEFT JOIN `" . $wpsc_submited_form_data_table . "`\n          ON `" . $wpsc_checkout_forms_table . "`.id = `" . $wpsc_submited_form_data_table . "`.`form_id`\n          WHERE `" . $wpsc_submited_form_data_table . "`.`log_id`=" . $order['id'] . "\n          ORDER BY `" . $wpsc_checkout_forms_table . "`.`checkout_order`\n          ", ARRAY_A);
         foreach ($userinfo as $info) {
             $userinfo[$info['unique_name']] = $info['value'];
         }
         // ID
         update_post_meta($post_id, '_customer_user', $order['user_ID']);
         // billing address
         update_post_meta($post_id, '_billing_first_name', $userinfo['billingfirstname']);
         update_post_meta($post_id, '_billing_last_name', $userinfo['billinglastname']);
         update_post_meta($post_id, '_billing_address_1', $userinfo['billingaddress']);
         update_post_meta($post_id, '_billing_address_2', "");
         update_post_meta($post_id, '_billing_city', $userinfo['billingcity']);
         update_post_meta($post_id, '_billing_postcode', $userinfo['billingpostcode']);
         update_post_meta($post_id, '_billing_country', $userinfo['billingcountry']);
         update_post_meta($post_id, '_billing_email', $userinfo['billingemail']);
         update_post_meta($post_id, '_billing_phone', $userinfo['billingphone']);
         // shipping address
         update_post_meta($post_id, '_shipping_first_name', $userinfo['shippingfirstname']);
         update_post_meta($post_id, '_shipping_last_name', $userinfo['shippinglastname']);
         update_post_meta($post_id, '_shipping_company', "");
         update_post_meta($post_id, '_shipping_address_1', $userinfo['shippingaddress']);
         update_post_meta($post_id, '_shipping_address_2', "");
         update_post_meta($post_id, '_shipping_city', $userinfo['shippingcity']);
         update_post_meta($post_id, '_shipping_postcode', $userinfo['shippingpostcode']);
         update_post_meta($post_id, '_shipping_country', $userinfo['shippingcountry']);
         update_post_meta($post_id, '_shipping_state', "");
         /*
           ORDER ITEMS
         */
         $cartcontent = $wpdb->get_results("\n          SELECT * \n          FROM `" . $wpsc_cart_contents_table . "` \n          WHERE `purchaseid`=" . $order['id'] . "\n          ");
         foreach ($cartcontent as $item) {
             $item_id = wc_add_order_item($post_id, array('order_item_name' => $item->name, 'order_item_type' => 'line_item'));
             if ($item_id) {
                 wc_add_order_item_meta($item_id, '_qty', $item->quantity);
                 wc_add_order_item_meta($item_id, '_product_id', $item->prodid);
                 wc_add_order_item_meta($item_id, '_variation_id', null);
                 $subtotal = $item->quantity * $item->price;
                 wc_add_order_item_meta($item_id, '_line_subtotal', $subtotal);
                 wc_add_order_item_meta($item_id, '_line_subtotal_tax', $subtotal + $item->tax_charged);
                 wc_add_order_item_meta($item_id, '_line_total', $subtotal + $item->tax_charged);
                 wc_add_order_item_meta($item_id, '_line_tax', $item->tax_charged);
             }
         }
         /*
           ORDER DATA
         */
         $extrainfo = $wpdb->get_results("\n          SELECT DISTINCT `" . $wpsc_purchase_logs_table . "` . * \n          FROM `" . $wpsc_submited_form_data_table . "`\n          LEFT JOIN `" . $wpsc_purchase_logs_table . "`\n          ON `" . $wpsc_submited_form_data_table . "`.`log_id` = `" . $wpsc_purchase_logs_table . "`.`id`\n          WHERE `" . $wpsc_purchase_logs_table . "`.`id`=" . $order['id'] . "\n          ");
         $extrainfo = $extrainfo[0];
         update_post_meta($post_id, '_payment_method', $extrainfo->gateway);
         update_post_meta($post_id, '_order_shipping', $extrainfo->base_shipping);
         update_post_meta($post_id, '_order_discount', $extrainfo->base_shipping);
         update_post_meta($post_id, '_cart_discount', $extrainfo->base_shipping);
         update_post_meta($post_id, '_order_tax', $extrainfo->base_shipping);
         update_post_meta($post_id, '_order_shipping_tax', $extrainfo->base_shipping);
         update_post_meta($post_id, '_order_total', $extrainfo->totalprice);
         update_post_meta($post_id, '_order_key', uniqid('order_'));
         update_post_meta($post_id, '_order_currency', "EUR");
         update_post_meta($post_id, '_prices_include_tax', "no");
         // order date
         wp_update_post(array('ID' => $post_id, 'post_date' => date_i18n('Y-m-d H:i:s', $extrainfo->date), 'post_date_gmt' => date_i18n('Y-m-d H:i:s', $extrainfo->date, true)));
         // order status
         switch ($order['processed']) {
             case "1":
                 $status = 'failed';
                 break;
             case "2":
                 $status = 'pending';
                 break;
             case "3":
             case "4":
                 $status = 'processing';
                 break;
             case "5":
                 $status = 'completed';
                 break;
             case "6":
                 $status = 'cancelled';
                 break;
         }
         wp_set_post_terms($post_id, $status, 'shop_order_status');
         // add to log
         $this->log['orders'][] = array('name' => $post_title);
     }
 }
コード例 #11
0
 public function update_cart_by_woocart($order_id, $data)
 {
     global $wp;
     global $wpdb, $woocommerce, $pwa;
     $xml = simplexml_load_string($data);
     $order = new WC_Order($order_id);
     $billing_address = array('first_name' => (string) $xml->ProcessedOrder->BuyerInfo->BuyerName, 'last_name' => '', 'company' => '', 'email' => (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress, 'phone' => '', 'address_1' => '', 'address_2' => '', 'city' => '', 'state' => '', 'postcode' => '', 'country' => '');
     $shipping_address = array('first_name' => (string) $xml->ProcessedOrder->ShippingAddress->Name, 'last_name' => '', 'company' => '', 'email' => '', 'phone' => '', 'address_1' => (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldOne, 'address_2' => (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldTwo, 'city' => (string) $xml->ProcessedOrder->ShippingAddress->City, 'state' => (string) $xml->ProcessedOrder->ShippingAddress->State, 'postcode' => (string) $xml->ProcessedOrder->ShippingAddress->PostalCode, 'country' => (string) $xml->ProcessedOrder->ShippingAddress->CountryCode);
     $order->set_address($shipping_address, 'shipping');
     add_post_meta($order_id, '_payment_method', 'pwa');
     add_post_meta($order_id, '_payment_method_title', 'Pay with Amazon');
     $total_amount = 0;
     $subtotal_amount = 0;
     $shipping_amount = 0;
     $ClientRequestId = 0;
     try {
         foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
             // XML DATA
             $ClientRequestId = (int) $item->ClientRequestId;
             foreach ($item->ItemCharges->Component as $amount_type) {
                 $item_charge_type = (string) $amount_type->Type;
                 if ($item_charge_type == 'Shipping') {
                     $Shipping = (string) $amount_type->Charge->Amount;
                 }
             }
             $shipping_amount = $shipping_amount + $Shipping;
         }
     } catch (Exception $e) {
         $param['message'] = 'IOPN Notifications : Caught exception : ' . $e->getMessage() . '.';
         $this->generate_log($param);
     }
     if ($ClientRequestId == 0) {
         $order->set_address($billing_address, 'billing');
     }
     // CART DATA
     $cartdata = '';
     $user_id = 0;
     $prefix = $wpdb->prefix;
     $carts = $wpdb->get_results("SELECT * FROM `" . $prefix . "pwa_before_cart_save` WHERE id = {$ClientRequestId} ");
     foreach ($carts as $key => $value) {
         $cartdata = maybe_unserialize($value->cart_data);
         $user_id = $value->user_id;
     }
     update_post_meta($order_id, '_customer_user', $user_id);
     // ENTRY
     try {
         foreach ($cartdata->cart_contents as $key => $value) {
             $product_id = $value['product_id'];
             $cart_product = get_product($product_id);
             $product = array();
             $product['order_item_name'] = $cart_product->get_title();
             $product['order_item_type'] = 'line_item';
             $order_item_id = wc_add_order_item($order_id, $product);
             wc_add_order_item_meta($order_item_id, '_qty', $value['quantity']);
             wc_add_order_item_meta($order_item_id, '_product_id', $product_id);
             wc_add_order_item_meta($order_item_id, '_line_total', $value['line_total']);
             wc_add_order_item_meta($order_item_id, '_line_subtotal', $value['line_subtotal']);
             wc_add_order_item_meta($order_item_id, '_line_tax', $value['line_tax']);
             wc_add_order_item_meta($order_item_id, '_line_subtotal_tax', $value['line_subtotal_tax']);
             wc_add_order_item_meta($order_item_id, '_line_tax_data', maybe_serialize($value['line_tax_data']));
             foreach ($value['line_tax_data']['total'] as $tax_rate_id => $tax_data) {
                 $tax_class = $wpdb->get_results("SELECT * FROM `" . $prefix . "woocommerce_tax_rates` WHERE tax_rate_id = {$tax_rate_id} ");
                 wc_add_order_item_meta($order_item_id, '_tax_class', $tax_class[0]->tax_rate_class);
             }
             if ($value['variation_id'] > 0) {
                 wc_add_order_item_meta($order_item_id, '_variation_id', $value['variation_id']);
             }
             foreach ($value['variation'] as $attrib_key => $attrib_value) {
                 $meta_key = str_replace('attribute_', '', $attrib_key);
                 wc_add_order_item_meta($order_item_id, $meta_key, $attrib_value);
             }
             $this->reduce_order_stock($product_id, $value['quantity']);
             $total_amount = $total_amount + $value['line_total'] + $value['line_tax'];
             $subtotal_amount = $subtotal_amount + $value['line_subtotal'];
         }
     } catch (Exception $e) {
         $param['message'] = 'IOPN Notifications : Caught exception : ' . $e->getMessage() . '.';
         $this->generate_log($param);
     }
     add_post_meta($order_id, '_order_total', $total_amount + $shipping_amount);
     add_post_meta($order_id, '_order_shipping', $shipping_amount);
     add_post_meta($order_id, '_cart_discount', $cartdata->discount_cart);
     add_post_meta($order_id, '_cart_discount_tax', $cartdata->discount_cart_tax);
     add_post_meta($order_id, '_order_tax', $cartdata->tax_total);
     $shipitem = array();
     $shipitem['order_item_name'] = (string) $xml->ProcessedOrder->ShippingServiceLevel;
     $shipitem['order_item_type'] = 'shipping';
     $order_shipping_id = wc_add_order_item($order_id, $shipitem);
     wc_add_order_item_meta($order_shipping_id, 'method_id', str_replace(' ', '_', strtolower((string) $xml->ProcessedOrder->ShippingServiceLevel)));
     wc_add_order_item_meta($order_shipping_id, 'cost', $shipping_amount);
     if (!empty($cartdata->taxes)) {
         foreach ($cartdata->taxes as $key => $value) {
             $order->add_tax($key, $value);
         }
     }
     if (!empty($cartdata->applied_coupons)) {
         foreach ($cartdata->applied_coupons as $key => $value) {
             $order->add_coupon($value, $cartdata->coupon_discount_amounts[$value], $cartdata->coupon_discount_tax_amounts[$value]);
         }
     }
     // Send notification mails to seller and customer for order
     $mail_class = new WC_Emails();
     $mail_class->emails['WC_Email_New_Order']->trigger($order_id);
     // Acknowledge the order in seller central using MWS FEED API
     $pwa->pwa_acknowledge_feed($order_id);
 }
コード例 #12
0
 protected function _import_line_items(&$order, $order_id, $index)
 {
     $is_product_founded = false;
     switch ($this->import->options['pmwi_order']['products_source']) {
         // Get data from existing products
         case 'existing':
             foreach ($this->data['pmwi_order']['products'][$index] as $productIndex => $productItem) {
                 if (empty($productItem['sku'])) {
                     continue;
                 }
                 $args = array('post_type' => 'product', 'meta_key' => '_sku', 'meta_value' => $productItem['sku'], 'meta_compare' => '=');
                 $product = false;
                 $query = new WP_Query($args);
                 while ($query->have_posts()) {
                     $query->the_post();
                     $product = WC()->product_factory->get_product($query->post->ID);
                     break;
                 }
                 wp_reset_postdata();
                 if (empty($product)) {
                     $args['post_type'] = 'product_variation';
                     $query = new WP_Query($args);
                     while ($query->have_posts()) {
                         $query->the_post();
                         $product = WC()->product_factory->get_product($query->post->ID);
                         break;
                     }
                     wp_reset_postdata();
                 }
                 if ($product) {
                     $is_product_founded = true;
                     $item_price = $product->get_price();
                     $item_qty = empty($productItem['qty']) ? 1 : $productItem['qty'];
                     $item_subtotal = $item_price * $item_qty;
                     $item_subtotal_tax = 0;
                     $line_taxes = array();
                     foreach ($productItem['tax_rates'] as $key => $tax_rate) {
                         if (empty($tax_rate['code'])) {
                             continue;
                         }
                         $tax_rate_codes = explode("|", $tax_rate['code']);
                         $percentage_value = explode("|", $tax_rate['percentage_value']);
                         $amount_per_unit = explode("|", $tax_rate['amount_per_unit']);
                         foreach ($tax_rate_codes as $rate_key => $tax_rate_code) {
                             if ($tax_rate_code == 'standard') {
                                 $tax_rate_code = '';
                             }
                             $line_tax = 0;
                             switch ($tax_rate['calculate_logic']) {
                                 case 'percentage':
                                     if (!empty($percentage_value[$rate_key]) and is_numeric($percentage_value[$rate_key])) {
                                         $line_tax = WC_Tax::round($item_subtotal / 100 * $percentage_value[$rate_key]);
                                         $item_subtotal_tax += $line_tax;
                                     }
                                     if (!empty($this->tax_rates)) {
                                         foreach ($this->tax_rates as $rate_id => $rate) {
                                             if ($rate->tax_rate_name == $tax_rate_code) {
                                                 $line_taxes[$rate->tax_rate_id] = $line_tax;
                                                 break;
                                             }
                                         }
                                     }
                                     break;
                                 case 'per_unit':
                                     if (!empty($amount_per_unit[$rate_key]) and is_numeric($amount_per_unit[$rate_key])) {
                                         $line_tax = WC_Tax::round($amount_per_unit[$rate_key] * $item_qty);
                                         $item_subtotal_tax += $line_tax;
                                     }
                                     if (!empty($this->tax_rates)) {
                                         foreach ($this->tax_rates as $rate_id => $rate) {
                                             if ($rate->tax_rate_name == $tax_rate_code) {
                                                 $line_taxes[$rate->tax_rate_id] = $line_tax;
                                                 break;
                                             }
                                         }
                                     }
                                     break;
                                     // Look up tax rate code
                                 // Look up tax rate code
                                 default:
                                     $found_rates = WC_Tax::get_rates_for_tax_class($tax_rate_code);
                                     if (!empty($found_rates)) {
                                         $found_priority = array();
                                         foreach ($found_rates as $found_rate) {
                                             $matched_tax_rates = array();
                                             if (in_array($found_rate->tax_rate_priority, $found_priority)) {
                                                 continue;
                                             }
                                             $matched_tax_rates[$found_rate->tax_rate_id] = array('rate' => $found_rate->tax_rate, 'label' => $found_rate->tax_rate_name, 'shipping' => $found_rate->tax_rate_shipping ? 'yes' : 'no', 'compound' => $found_rate->tax_rate_compound ? 'yes' : 'no');
                                             $line_tax = array_sum(WC_Tax::calc_tax($item_subtotal, $matched_tax_rates, $this->prices_include_tax));
                                             $item_subtotal_tax += $line_tax;
                                             $line_taxes[$found_rate->tax_rate_id] = $line_tax;
                                             $found_priority[] = $found_rate->tax_rate_priority;
                                         }
                                     }
                                     break;
                             }
                         }
                     }
                     $variation = array();
                     $variation_str = '';
                     if ($product instanceof WC_Product_Variation) {
                         $variation = $product->get_variation_attributes();
                         if (!empty($variation)) {
                             foreach ($variation as $key => $value) {
                                 $variation_str .= $key . '-' . $value;
                             }
                         }
                     }
                     $product_item = new PMXI_Post_Record();
                     $product_item->getBy(array('import_id' => $this->import->id, 'post_id' => $order_id, 'unique_key' => 'line-item-' . $product->id . '-' . $variation_str));
                     if ($product_item->isEmpty()) {
                         $item_id = false;
                         // in case when this is new order just add new line items
                         if (!$item_id) {
                             $item_id = $order->add_product($product, $item_qty, array('variation' => $variation, 'totals' => array('subtotal' => $item_subtotal, 'subtotal_tax' => $item_subtotal_tax, 'total' => $item_subtotal, 'tax' => $item_subtotal_tax, 'tax_data' => array('total' => $line_taxes, 'subtotal' => array()))));
                         }
                         if (!$item_id) {
                             $this->logger and call_user_func($this->logger, __('- <b>WARNING</b> Unable to create order line product.', 'wp_all_import_plugin'));
                         } else {
                             $product_item->set(array('import_id' => $this->import->id, 'post_id' => $order_id, 'unique_key' => 'line-item-' . $product->id . '-' . $variation_str, 'product_key' => 'line-item-' . $item_id, 'iteration' => $this->import->iteration))->save();
                         }
                     } else {
                         $item_id = str_replace('line-item-', '', $product_item->product_key);
                         $is_updated = $order->update_product($item_id, $product, array('qty' => $item_qty, 'tax_class' => $product->get_tax_class(), 'totals' => array('subtotal' => $item_subtotal, 'subtotal_tax' => $item_subtotal_tax, 'total' => $item_subtotal, 'tax' => $item_subtotal_tax, 'tax_data' => array('total' => $line_taxes, 'subtotal' => array())), 'variation' => $variation));
                         if ($is_updated) {
                             $product_item->set(array('iteration' => $this->import->iteration))->save();
                         }
                     }
                 }
             }
             break;
             // Manually import product order data and do not try to match to existing products
         // Manually import product order data and do not try to match to existing products
         default:
             $is_product_founded = true;
             foreach ($this->data['pmwi_order']['manual_products'][$index] as $productIndex => $productItem) {
                 $item_price = $productItem['price_per_unit'];
                 $item_qty = empty($productItem['qty']) ? 1 : $productItem['qty'];
                 $item_subtotal = $item_price * $item_qty;
                 $item_subtotal_tax = 0;
                 $line_taxes = array();
                 foreach ($productItem['tax_rates'] as $key => $tax_rate) {
                     if (empty($tax_rate['code'])) {
                         continue;
                     }
                     $line_tax = 0;
                     switch ($tax_rate['calculate_logic']) {
                         case 'percentage':
                             if (!empty($tax_rate['percentage_value']) and is_numeric($tax_rate['percentage_value'])) {
                                 $line_tax = WC_Tax::round($item_subtotal / 100 * $tax_rate['percentage_value']);
                                 $item_subtotal_tax += $line_tax;
                             }
                             break;
                         case 'per_unit':
                             if (!empty($tax_rate['amount_per_unit']) and is_numeric($tax_rate['amount_per_unit'])) {
                                 $line_tax = WC_Tax::round($tax_rate['amount_per_unit'] * $item_qty);
                                 $item_subtotal_tax += $line_tax;
                             }
                             break;
                             // Look up tax rate code
                         // Look up tax rate code
                         default:
                             $found_rates = WC_Tax::get_rates_for_tax_class($tax_rate['code']);
                             if (!empty($found_rates)) {
                                 $matched_tax_rates = array();
                                 $found_priority = array();
                                 foreach ($found_rates as $found_rate) {
                                     if (in_array($found_rate->tax_rate_priority, $found_priority)) {
                                         continue;
                                     }
                                     $matched_tax_rates[$found_rate->tax_rate_id] = array('rate' => $found_rate->tax_rate, 'label' => $found_rate->tax_rate_name, 'shipping' => $found_rate->tax_rate_shipping ? 'yes' : 'no', 'compound' => $found_rate->tax_rate_compound ? 'yes' : 'no');
                                     $found_priority[] = $found_rate->tax_rate_priority;
                                 }
                                 $line_tax = array_sum(WC_Tax::calc_tax($item_subtotal, $matched_tax_rates, true));
                                 $item_subtotal_tax += $line_tax;
                             }
                             break;
                     }
                     if (!empty($this->tax_rates)) {
                         foreach ($this->tax_rates as $rate_id => $rate) {
                             $line_taxes[$rate->tax_rate_id] = $line_tax;
                             break;
                         }
                     }
                 }
                 $variation = array();
                 $product_item = new PMXI_Post_Record();
                 $product_item->getBy(array('import_id' => $this->import->id, 'post_id' => $order_id, 'unique_key' => 'manual-line-item-' . $productIndex . '-' . $productItem['sku']));
                 if ($product_item->isEmpty()) {
                     $item_id = wc_add_order_item($order_id, array('order_item_name' => $productItem['sku'], 'order_item_type' => 'line_item'));
                     if (!$item_id) {
                         $this->logger and call_user_func($this->logger, __('- <b>WARNING</b> Unable to create order line product.', 'wp_all_import_plugin'));
                     } else {
                         wc_add_order_item_meta($item_id, '_qty', wc_stock_amount($item_qty));
                         wc_add_order_item_meta($item_id, '_tax_class', '');
                         wc_add_order_item_meta($item_id, '_line_subtotal', wc_format_decimal($item_subtotal));
                         wc_add_order_item_meta($item_id, '_line_total', wc_format_decimal($item_subtotal));
                         wc_add_order_item_meta($item_id, '_line_subtotal_tax', wc_format_decimal($item_subtotal_tax));
                         wc_add_order_item_meta($item_id, '_line_tax', wc_format_decimal($item_subtotal_tax));
                         wc_add_order_item_meta($item_id, '_line_tax_data', array('total' => $line_taxes, 'subtotal' => array()));
                         if (!empty($productItem['meta_name'])) {
                             foreach ($productItem['meta_name'] as $key => $meta_name) {
                                 wc_add_order_item_meta($item_id, $meta_name, isset($productItem['meta_value'][$key]) ? $productItem['meta_value'][$key] : '');
                             }
                         }
                         $product_item->set(array('import_id' => $this->import->id, 'post_id' => $order_id, 'unique_key' => 'manual-line-item-' . $productIndex . '-' . $productItem['sku'], 'product_key' => 'manual-line-item-' . $item_id, 'iteration' => $this->import->iteration))->save();
                     }
                 } else {
                     $item_id = str_replace('manual-line-item-', '', $product_item->product_key);
                     if (is_numeric($item_id)) {
                         wc_update_order_item($item_id, array('order_item_name' => $productItem['sku'], 'order_item_type' => 'line_item'));
                         wc_update_order_item_meta($item_id, '_qty', wc_stock_amount($item_qty));
                         wc_update_order_item_meta($item_id, '_tax_class', '');
                         wc_update_order_item_meta($item_id, '_line_subtotal', wc_format_decimal($item_subtotal));
                         wc_update_order_item_meta($item_id, '_line_total', wc_format_decimal($item_subtotal));
                         wc_update_order_item_meta($item_id, '_line_subtotal_tax', wc_format_decimal($item_subtotal_tax));
                         wc_update_order_item_meta($item_id, '_line_tax', wc_format_decimal($item_subtotal_tax));
                         wc_update_order_item_meta($item_id, '_line_tax_data', array('total' => $line_taxes, 'subtotal' => array()));
                         if (!empty($productItem['meta_name'])) {
                             foreach ($productItem['meta_name'] as $key => $meta_name) {
                                 wc_update_order_item_meta($item_id, $meta_name, isset($productItem['meta_value'][$key]) ? $productItem['meta_value'][$key] : '');
                             }
                         }
                         $product_item->set(array('iteration' => $this->import->iteration))->save();
                     }
                 }
             }
             break;
     }
     return $is_product_founded;
 }
コード例 #13
0
/**
 * Function to create an order from a subscription. It can be used for a renewal or for a resubscribe
 * order creation. It is the common in both of those instances.
 *
 * @param  WC_Subscription|int $subscription Subscription we're basing the order off of
 * @param  string $type        Type of new order. Default values are 'renewal_order'|'resubscribe_order'
 * @return WC_Order            New order
 */
function wcs_create_order_from_subscription($subscription, $type)
{
    $type = wcs_validate_new_order_type($type);
    if (is_wp_error($type)) {
        return $type;
    }
    global $wpdb;
    try {
        $wpdb->query('START TRANSACTION');
        if (!is_object($subscription)) {
            $subscription = wcs_get_subscription($subscription);
        }
        $new_order = wc_create_order(array('customer_id' => $subscription->get_user_id(), 'customer_note' => $subscription->customer_note));
        $new_order->post->post_title = wcs_get_new_order_title($type);
        wcs_copy_order_meta($subscription, $new_order, $type);
        // Copy over line items and allow extensions to add/remove items or item meta
        $items = apply_filters('wcs_new_order_items', $subscription->get_items(array('line_item', 'fee', 'shipping', 'tax')), $new_order, $subscription);
        $items = apply_filters('wcs_' . $type . '_items', $items, $new_order, $subscription);
        foreach ($items as $item_index => $item) {
            $item_name = apply_filters('wcs_new_order_item_name', $item['name'], $item, $subscription);
            $item_name = apply_filters('wcs_' . $type . '_item_name', $item_name, $item, $subscription);
            // Create order line item on the renewal order
            $recurring_item_id = wc_add_order_item($new_order->id, array('order_item_name' => $item_name, 'order_item_type' => $item['type']));
            // Remove recurring line items and set item totals based on recurring line totals
            foreach ($item['item_meta'] as $meta_key => $meta_values) {
                foreach ($meta_values as $meta_value) {
                    wc_add_order_item_meta($recurring_item_id, $meta_key, maybe_unserialize($meta_value));
                }
            }
        }
        // If we got here, the subscription was created without problems
        $wpdb->query('COMMIT');
        return apply_filters('wcs_new_order_created', $new_order, $subscription);
    } catch (Exception $e) {
        // There was an error adding the subscription
        $wpdb->query('ROLLBACK');
        return new WP_Error('new-order-error', $e->getMessage());
    }
}
コード例 #14
0
 public function update_cart_by_xml($order_id, $orderdetail)
 {
     global $wpdb, $woocommerce;
     $AmazonOrderID = (string) $orderdetail->OrderReport->AmazonOrderID;
     $order = new WC_Order($order_id);
     $billing_address = array('first_name' => (string) $orderdetail->OrderReport->BillingData->BuyerName, 'last_name' => '', 'company' => '', 'email' => (string) $orderdetail->OrderReport->BillingData->BuyerEmailAddress, 'phone' => (string) $orderdetail->OrderReport->BillingData->BuyerPhoneNumber, 'address_1' => '', 'address_2' => '', 'city' => '', 'state' => '', 'postcode' => '', 'country' => '');
     $shipping_address = array('first_name' => (string) $orderdetail->OrderReport->FulfillmentData->Address->Name, 'last_name' => '', 'company' => '', 'email' => '', 'phone' => (string) $orderdetail->OrderReport->FulfillmentData->Address->PhoneNumber, 'address_1' => (string) $orderdetail->OrderReport->FulfillmentData->Address->AddressFieldOne, 'address_2' => (string) $orderdetail->OrderReport->FulfillmentData->Address->AddressFieldTwo, 'city' => (string) $orderdetail->OrderReport->FulfillmentData->Address->City, 'state' => (string) $orderdetail->OrderReport->FulfillmentData->Address->State, 'postcode' => (string) $orderdetail->OrderReport->FulfillmentData->Address->PostalCode, 'country' => (string) $orderdetail->OrderReport->FulfillmentData->Address->CountryCode);
     $order->set_address($shipping_address, 'shipping');
     add_post_meta($order_id, '_payment_method', 'pwa');
     add_post_meta($order_id, '_payment_method_title', 'Pay with Amazon');
     $total_amount = 0;
     $shipping_amount = 0;
     $total_promo = 0;
     foreach ($orderdetail->OrderReport->Item as $item) {
         $SKU = (string) $item->SKU;
         $Title = (string) $item->Title;
         $Quantity = (int) $item->Quantity;
         foreach ($item->ItemPrice->Component as $amount_type) {
             $item_charge_type = (string) $amount_type->Type;
             if ($item_charge_type == 'Principal') {
                 $Principal = (double) $amount_type->Amount;
             }
             if ($item_charge_type == 'Shipping') {
                 $Shipping = (double) $amount_type->Amount;
             }
             if ($item_charge_type == 'Tax') {
                 $Tax = (double) $amount_type->Amount;
             }
             if ($item_charge_type == 'ShippingTax') {
                 $ShippingTax = (double) $amount_type->Amount;
             }
         }
         if (!empty($item->Promotion)) {
             foreach ($item->Promotion->Component as $promotion_amount_type) {
                 $promotion_type = (string) $promotion_amount_type->Type;
                 if ($promotion_type == 'Shipping') {
                     $Shipping_Promotions = (double) $promotion_amount_type->Amount;
                 }
                 if ($promotion_type == 'Principal') {
                     $Principal_Promotions = (double) $promotion_amount_type->Amount;
                 }
             }
         }
         $product = array();
         $product['order_item_name'] = $Title;
         $product['order_item_type'] = 'line_item';
         $order_item_id = wc_add_order_item($order_id, $product);
         wc_add_order_item_meta($order_item_id, '_qty', $Quantity);
         wc_add_order_item_meta($order_item_id, '_line_total', $Principal + $Shipping_Promotions + $Principal_Promotions);
         wc_add_order_item_meta($order_item_id, '_line_subtotal', $Principal);
         wc_add_order_item_meta($order_item_id, '_line_subtotal_tax', 0);
         wc_add_order_item_meta($order_item_id, '_line_tax', 0);
         /*
          * Total Item Charge = (Principal - PrincipalPromo) + (Shipping - ShippingPromo) + Tax + ShippingTax
          */
         $total_amount += $Principal + $Principal_Promotions + ($Shipping + $Shipping_Promotions);
         $shipping_amount += $Shipping + $Shipping_Promotions;
         $total_promo += $Principal_Promotions + $Shipping_Promotions;
         $ClientRequestId = 0;
         foreach ($item->CustomizationInfo as $info) {
             $info_type = (string) $info->Type;
             if ($info_type == 'url') {
                 $info_array = explode(',', $info->Data);
                 $customerId_array = explode('=', $info_array[0]);
                 $ClientRequestId = $customerId_array[1];
             }
         }
         if ($ClientRequestId == 0) {
             $order->set_address($billing_address, 'billing');
         } else {
             if (UPDATE_ODER_FROM == 'xmlcart') {
                 unset($billing_address['email']);
                 $order->set_address($billing_address, 'billing');
                 update_post_meta($order_id, '_customer_user', $ClientRequestId);
             }
             //update_post_meta($order_id, '_customer_user' , $ClientRequestId);
         }
         $product = $wpdb->get_results("select post_id from {$wpdb->postmeta} where meta_key = '_sku' and meta_value = '{$SKU}' ");
         if (!empty($product)) {
             $product_id = $product[0]->post_id;
             if ($product_id != '') {
                 wc_add_order_item_meta($order_item_id, '_product_id', $product_id);
                 $this->reduce_order_stock($product_id, $Quantity);
             }
         }
     }
     add_post_meta($order_id, '_order_total', $total_amount);
     add_post_meta($order_id, '_order_shipping', $shipping_amount);
     add_post_meta($order_id, '_cart_discount', abs($total_promo));
     $shipitem = array();
     $shipitem['order_item_name'] = (string) $orderdetail->OrderReport->FulfillmentData->FulfillmentServiceLevel;
     $shipitem['order_item_type'] = 'shipping';
     $order_shipping_id = wc_add_order_item($order_id, $shipitem);
     wc_add_order_item_meta($order_shipping_id, 'method_id', str_replace(' ', '_', strtolower((string) $orderdetail->OrderReport->FulfillmentData->FulfillmentServiceLevel)));
     wc_add_order_item_meta($order_shipping_id, 'cost', $shipping_amount);
     // Send notification mails to seller and customer for order
     //$mail_class = new WC_Emails();
     //$mail_class->emails['WC_Email_New_Order']->trigger($order_id);
     // Acknowledge the order in seller central using MWS FEED API
     $param['AmazonOrderID'] = $AmazonOrderID;
     $param['MerchantOrderID'] = $order_id;
     $param['StatusCode'] = 'Success';
     $this->submit_acknowledge_feed($param);
 }
コード例 #15
0
ファイル: wc-functions.php プロジェクト: nuwe1/dokan-lite
/**
 * Creates a sub order
 *
 * @param int $parent_order
 * @param int $seller_id
 * @param array $seller_products
 */
function dokan_create_seller_order($parent_order, $seller_id, $seller_products)
{
    $order_data = apply_filters('woocommerce_new_order_data', array('post_type' => 'shop_order', 'post_title' => sprintf(__('Order &ndash; %s', 'woocommerce'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'woocommerce'))), 'post_status' => 'wc-pending', 'ping_status' => 'closed', 'post_excerpt' => isset($posted['order_comments']) ? $posted['order_comments'] : '', 'post_author' => $seller_id, 'post_parent' => $parent_order->id, 'post_password' => uniqid('order_')));
    $order_id = wp_insert_post($order_data);
    if ($order_id && !is_wp_error($order_id)) {
        $order_total = $order_tax = 0;
        $product_ids = array();
        do_action('woocommerce_new_order', $order_id);
        // now insert line items
        foreach ($seller_products as $item) {
            $order_total += (double) $item['line_total'];
            $order_tax += (double) $item['line_tax'];
            $product_ids[] = $item['product_id'];
            $item_id = wc_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'line_item'));
            if ($item_id) {
                wc_add_order_item_meta($item_id, '_qty', $item['qty']);
                wc_add_order_item_meta($item_id, '_tax_class', $item['tax_class']);
                wc_add_order_item_meta($item_id, '_product_id', $item['product_id']);
                wc_add_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
                wc_add_order_item_meta($item_id, '_line_total', $item['line_total']);
                wc_add_order_item_meta($item_id, '_line_tax', $item['line_tax']);
                wc_add_order_item_meta($item_id, '_line_subtotal_tax', $item['line_subtotal_tax']);
            }
        }
        // foreach
        $bill_ship = array('_billing_country', '_billing_first_name', '_billing_last_name', '_billing_company', '_billing_address_1', '_billing_address_2', '_billing_city', '_billing_state', '_billing_postcode', '_billing_email', '_billing_phone', '_shipping_country', '_shipping_first_name', '_shipping_last_name', '_shipping_company', '_shipping_address_1', '_shipping_address_2', '_shipping_city', '_shipping_state', '_shipping_postcode');
        // save billing and shipping address
        foreach ($bill_ship as $val) {
            $order_key = ltrim($val, '_');
            update_post_meta($order_id, $val, $parent_order->{$order_key});
        }
        // calculate the total
        $order_in_total = $order_total + $shipping_cost + $order_tax;
        // set order meta
        update_post_meta($order_id, '_payment_method', $parent_order->payment_method);
        update_post_meta($order_id, '_payment_method_title', $parent_order->payment_method_title);
        update_post_meta($order_id, '_order_shipping', woocommerce_format_decimal($shipping_cost));
        update_post_meta($order_id, '_cart_discount', '0');
        update_post_meta($order_id, '_order_tax', woocommerce_format_decimal($order_tax));
        update_post_meta($order_id, '_order_shipping_tax', '0');
        update_post_meta($order_id, '_order_total', woocommerce_format_decimal($order_in_total));
        update_post_meta($order_id, '_order_key', apply_filters('woocommerce_generate_order_key', uniqid('order_')));
        update_post_meta($order_id, '_customer_user', $parent_order->customer_user);
        update_post_meta($order_id, '_order_currency', get_post_meta($parent_order->id, '_order_currency', true));
        update_post_meta($order_id, '_prices_include_tax', $parent_order->prices_include_tax);
        update_post_meta($order_id, '_customer_ip_address', get_post_meta($parent_order->id, '_customer_ip_address', true));
        update_post_meta($order_id, '_customer_user_agent', get_post_meta($parent_order->id, '_customer_user_agent', true));
        do_action('dokan_checkout_update_order_meta', $order_id, $seller_id);
    }
    // if order
}
コード例 #16
0
 /**
  * Add order item via ajax
  */
 public static function add_order_item()
 {
     check_ajax_referer('order-item', 'security');
     if (!current_user_can('edit_shop_orders')) {
         die(-1);
     }
     $item_to_add = sanitize_text_field($_POST['item_to_add']);
     $order_id = absint($_POST['order_id']);
     if (!wp_get_post_parent_id($order_id)) {
         // Find the item
         if (!is_numeric($item_to_add)) {
             die;
         }
         $post = get_post($item_to_add);
         if (!$post || 'product' !== $post->post_type && 'product_variation' !== $post->post_type) {
             die;
         }
         $_product = wc_get_product($post->ID);
         $order = wc_get_order($order_id);
         $order_taxes = $order->get_taxes();
         $class = 'new_row';
         $suborders_id = 0;
         $vendor = yith_get_vendor($item_to_add, 'product');
         if ($vendor->is_valid()) {
             $vendor_suborder_id = $vendor->get_orders('suborder');
             $suborders_ids = self::get_suborder($order_id);
             $suborder_id = array_intersect($vendor_suborder_id, $suborders_ids);
             if (is_array($suborder_id) && count($suborder_id) == 1) {
                 $suborder_id = array_shift($suborder_id);
             }
         }
         // Set values
         $item = array();
         $item_ids = array();
         $item['product_id'] = $_product->id;
         $item['variation_id'] = isset($_product->variation_id) ? $_product->variation_id : '';
         $item['variation_data'] = $item['variation_id'] ? $_product->get_variation_attributes() : '';
         $item['name'] = $_product->get_title();
         $item['tax_class'] = $_product->get_tax_class();
         $item['qty'] = 1;
         $item['line_subtotal'] = wc_format_decimal($_product->get_price_excluding_tax());
         $item['line_subtotal_tax'] = '';
         $item['line_total'] = wc_format_decimal($_product->get_price_excluding_tax());
         $item['line_tax'] = '';
         $item['type'] = 'line_item';
         // Add line item
         foreach (array('parent_id' => $order_id, 'child_id' => $suborder_id) as $type => $id) {
             $item_ids[$type] = wc_add_order_item($id, array('order_item_name' => $item['name'], 'order_item_type' => 'line_item'));
         }
         wc_add_order_item_meta($item_ids['child_id'], '_parent_line_item_id', $item_ids['parent_id']);
         foreach ($item_ids as $key => $item_id) {
             // Add line item meta
             if ($item_id) {
                 wc_add_order_item_meta($item_id, '_qty', $item['qty']);
                 wc_add_order_item_meta($item_id, '_tax_class', $item['tax_class']);
                 wc_add_order_item_meta($item_id, '_product_id', $item['product_id']);
                 wc_add_order_item_meta($item_id, '_variation_id', $item['variation_id']);
                 wc_add_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
                 wc_add_order_item_meta($item_id, '_line_subtotal_tax', $item['line_subtotal_tax']);
                 wc_add_order_item_meta($item_id, '_line_total', $item['line_total']);
                 wc_add_order_item_meta($item_id, '_line_tax', $item['line_tax']);
                 // Since 2.2
                 wc_add_order_item_meta($item_id, '_line_tax_data', array('total' => array(), 'subtotal' => array()));
                 // Store variation data in meta
                 if ($item['variation_data'] && is_array($item['variation_data'])) {
                     foreach ($item['variation_data'] as $key => $value) {
                         wc_add_order_item_meta($item_id, str_replace('attribute_', '', $key), $value);
                     }
                 }
                 do_action('woocommerce_ajax_add_order_item_meta', $item_id, $item);
             }
         }
         $item['item_meta'] = $order->get_item_meta($item_ids['parent_id']);
         $item['item_meta_array'] = $order->get_item_meta_array($item_ids['parent_id']);
         $item = $order->expand_item_meta($item);
         $item = apply_filters('woocommerce_ajax_order_item', $item, $item_ids['parent_id']);
         /**
          * WooCommerce Template Hack:
          * Copy the parent item id into the variable $item_id
          */
         $item_id = $item_ids['parent_id'];
         include WC()->plugin_path() . '/includes/admin/meta-boxes/views/html-order-item.php';
         /**
          * Prevent call default WooCommerce add_order_item() method
          */
         die;
     } else {
         //is suborder
         //TODO: Suborder sub-routine
     }
 }
コード例 #17
0
 protected static function _add_order_item($order_id, $item)
 {
     do_action('qsot-ajax-before-add-order-item', $order_id, $item);
     // Add line item
     $item_id = wc_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'line_item'));
     // Add line item meta
     if ($item_id) {
         wc_update_order_item_meta($item_id, '_qty', $item['qty']);
         wc_update_order_item_meta($item_id, '_tax_class', $item['tax_class']);
         wc_update_order_item_meta($item_id, '_product_id', $item['product_id']);
         wc_update_order_item_meta($item_id, '_variation_id', $item['variation_id']);
         wc_update_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
         wc_update_order_item_meta($item_id, '_line_subtotal_tax', $item['line_subtotal_tax']);
         wc_update_order_item_meta($item_id, '_line_total', $item['line_total']);
         wc_update_order_item_meta($item_id, '_line_tax', $item['line_tax']);
     }
     do_action('woocommerce_ajax_add_order_item_meta', $item_id, $item, $order_id);
     return $item_id;
 }
コード例 #18
0
/**
 * @deprecated
 */
function woocommerce_add_order_item($order_id, $item)
{
    return wc_add_order_item($order_id, $item);
}
コード例 #19
0
 public function importOrderToWoocommerce($orders)
 {
     if (isset($orders) && !empty($orders)) {
         $order_status = get_option('order_vend_to_wc');
         //Order Status from order config setting
         foreach ($orders['orders'] as $order) {
             if (isset($order['id']) && !empty($order['id'])) {
                 $OrderIds = get_option("Vend_orderIDs");
                 if (isset($OrderIds) && !empty($OrderIds)) {
                     $Ids = unserialize($OrderIds);
                 } else {
                     $Ids = array();
                 }
                 if (!in_array($order['id'], $Ids)) {
                     update_option('Vend_orderIDs', serialize(array_merge($Ids, array($order['id']))));
                     $order_data = array('post_name' => 'order-' . date('M-d-Y-hi-a'), 'post_type' => 'shop_order', 'post_title' => date('M d, Y @ h:i A'), 'post_excerpt' => 'Source: ' . ucfirst($order['source']) . ' Order #' . $order['orderId'], 'post_status' => $order_status, 'ping_status' => 'closed', 'comment_status' => 'open');
                     $order_id = wp_insert_post($order_data, true);
                     // create order
                     if (is_wp_error($order_id)) {
                         $order->errors = $order_id;
                     } else {
                         if (isset($order['payment']['transactionNumber']) && !empty($order['payment']['transactionNumber'])) {
                             add_post_meta($order_id, 'transaction_id', $order['payment']['transactionNumber'], true);
                         }
                         /* ---------------------------------------Payment Mapping --------------------------------- */
                         if (isset($order['payment']['retailer_payment_type_id']) && !empty($order['payment']['retailer_payment_type_id'])) {
                             $all_payment = get_option('vend_to_wc_payments');
                             if (isset($all_payment) && !empty($all_payment)) {
                                 $explode_payment = explode(',', $all_payment);
                                 foreach ($explode_payment as $payments_method) {
                                     $payment_method = explode('|', $payments_method);
                                     if (in_array($order['payment']['retailer_payment_type_id'], $payment_method)) {
                                         $gatways = new WC_Payment_Gateways();
                                         $payment = $gatways->get_available_payment_gateways();
                                         $wocoomercepayment = $payment_method[1];
                                         foreach ($payment as $payment_method_id => $payment_method_title) {
                                             if ($payment_method_title->title == $wocoomercepayment) {
                                                 add_post_meta($order_id, '_payment_method_title', $wocoomercepayment, true);
                                                 add_post_meta($order_id, '_payment_method', $payment_method_id, true);
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                         $customer_import = get_option('vend_to_wc_customer');
                         if (isset($customer_import) && $customer_import == 'customer_data') {
                             if (isset($order['billingAddress'])) {
                                 add_post_meta($order_id, '_billing_first_name', isset($order['billingAddress']['firstName']) ? $order['billingAddress']['firstName'] : NULL, true);
                                 add_post_meta($order_id, '_billing_last_name', isset($order['billingAddress']['lastName']) ? $order['billingAddress']['lastName'] : NULL, true);
                                 add_post_meta($order_id, '_billing_company', isset($order['billingAddress']['company']) ? $order['billingAddress']['company'] : NULL, true);
                                 add_post_meta($order_id, '_billing_address_1', isset($order['billingAddress']['street1']) ? $order['billingAddress']['street1'] : NULL, true);
                                 add_post_meta($order_id, '_billing_address_2', isset($order['billingAddress']['street2']) ? $order['billingAddress']['street2'] : NULL, true);
                                 add_post_meta($order_id, '_billing_city', isset($order['billingAddress']['city']) ? $order['billingAddress']['city'] : NULL, true);
                                 add_post_meta($order_id, '_billing_postcode', isset($order['billingAddress']['postalCode']) ? $order['billingAddress']['postalCode'] : NULL, true);
                                 add_post_meta($order_id, '_billing_country', isset($order['billingAddress']['country']) ? $order['billingAddress']['country'] : NULL, true);
                                 add_post_meta($order_id, '_billing_state', isset($order['billingAddress']['state']) ? $order['billingAddress']['state'] : NULL, true);
                                 add_post_meta($order_id, '_billing_phone', isset($order['billingAddress']['phone']) ? $order['billingAddress']['phone'] : NULL, true);
                             }
                             if (isset($order['deliveryAddress'])) {
                                 add_post_meta($order_id, '_shipping_first_name', isset($order['deliveryAddress']['firstName']) ? $order['deliveryAddress']['firstName'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_last_name', isset($order['deliveryAddress']['lastName']) ? $order['deliveryAddress']['lastName'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_company', isset($order['deliveryAddress']['company']) ? $order['deliveryAddress']['company'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_address_1', isset($order['deliveryAddress']['street1']) ? $order['deliveryAddress']['street1'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_address_2', isset($order['deliveryAddress']['street2']) ? $order['deliveryAddress']['street2'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_city', isset($order['deliveryAddress']['city']) ? $order['deliveryAddress']['city'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_postcode', isset($order['deliveryAddress']['postalCode']) ? $order['deliveryAddress']['postalCode'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_country', isset($order['deliveryAddress']['country']) ? $order['deliveryAddress']['country'] : NULL, true);
                                 add_post_meta($order_id, '_shipping_state', isset($order['deliveryAddress']['state']) ? $order['deliveryAddress']['state'] : NULL, true);
                             }
                             if (isset($order['primary_email'])) {
                                 require_once ABSPATH . 'wp-includes/user.php';
                                 require_once ABSPATH . 'wp-includes/pluggable.php';
                                 $user_email = $order['primary_email'];
                                 $user_name = $order['billingAddress']['firstName'] . ' ' . $order['billingAddress']['lastName'];
                                 $user_id = email_exists($user_email);
                                 $email_password = false;
                                 if (!$user_id) {
                                     $user_password = wp_generate_password(12, false);
                                     $user_id = wp_create_user($user_name, $user_password, $user_email);
                                     update_user_option($user_id, 'default_password_nag', true, true);
                                     $email_password = true;
                                     $message = " Username: {$user_name}\n Password: {$user_password}\n " . wp_login_url();
                                     if (isset($order['billingAddress'])) {
                                         add_user_meta($user_id, 'billing_first_name', isset($order['billingAddress']['firstName']) ? $order['billingAddress']['firstName'] : NULL, true);
                                         add_user_meta($user_id, 'billing_last_name', isset($order['billingAddress']['lastName']) ? $order['billingAddress']['lastName'] : NULL, true);
                                         add_user_meta($user_id, 'billing_company', isset($order['billingAddress']['company']) ? $order['billingAddress']['company'] : NULL, true);
                                         add_user_meta($user_id, 'billing_address_1', isset($order['billingAddress']['street1']) ? $order['billingAddress']['street1'] : NULL, true);
                                         add_user_meta($user_id, 'billing_address_2', isset($order['billingAddress']['street2']) ? $order['billingAddress']['street2'] : NULL, true);
                                         add_user_meta($user_id, 'billing_city', isset($order['billingAddress']['city']) ? $order['billingAddress']['city'] : NULL, true);
                                         add_user_meta($user_id, 'billing_postcode', isset($order['billingAddress']['postalCode']) ? $order['billingAddress']['postalCode'] : NULL, true);
                                         add_user_meta($user_id, 'billing_country', isset($order['billingAddress']['country']) ? $order['billingAddress']['country'] : NULL, true);
                                         add_user_meta($user_id, 'billing_state', isset($order['billingAddress']['state']) ? $order['billingAddress']['state'] : NULL, true);
                                         add_user_meta($user_id, 'billing_phone', isset($order['billingAddress']['phone']) ? $order['billingAddress']['phone'] : NULL, true);
                                     }
                                     if (isset($order['deliveryAddress'])) {
                                         add_user_meta($user_id, 'shipping_first_name', isset($order['deliveryAddress']['firstName']) ? $order['deliveryAddress']['firstName'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_last_name', isset($order['deliveryAddress']['lastName']) ? $order['deliveryAddress']['lastName'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_company', isset($order['deliveryAddress']['company']) ? $order['deliveryAddress']['company'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_address_1', isset($order['deliveryAddress']['street1']) ? $order['deliveryAddress']['street1'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_address_2', isset($order['deliveryAddress']['street2']) ? $order['deliveryAddress']['street2'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_city', isset($order['deliveryAddress']['city']) ? $order['deliveryAddress']['city'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_postcode', isset($order['deliveryAddress']['postalCode']) ? $order['deliveryAddress']['postalCode'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_country', isset($order['deliveryAddress']['country']) ? $order['deliveryAddress']['country'] : NULL, true);
                                         add_user_meta($user_id, 'shipping_state', isset($order['deliveryAddress']['state']) ? $order['deliveryAddress']['state'] : NULL, true);
                                     }
                                     wp_mail($user_email, 'Your username and password', $message);
                                     $user = new WP_User($user_id);
                                     $user->set_role('customer');
                                 }
                                 add_post_meta($order_id, '_customer_user', $user_id);
                             }
                         }
                         if (isset($order['total']) && !empty($order['total'])) {
                             if (isset($order['total_tax'])) {
                                 $order['total'] = $order['total_tax'] + $order['total'];
                             }
                             add_post_meta($order_id, '_order_total', $order['total'], true);
                         }
                         if (isset($order['taxes_included']) && $order['taxes_included'] == true) {
                             add_post_meta($order_id, '_order_tax', $order['total_tax'], true);
                         }
                         if (isset($order['updated_at']) && !empty($order['updated_at'])) {
                             add_post_meta($order_id, '_completed_date', $order['updated_at'], true);
                         }
                         if (isset($order['id']) && !empty($order['id'])) {
                             add_post_meta($order_id, '_vend_orderid', $order['id'], true);
                         }
                         if (isset($order['currency']) && !empty($order['currency'])) {
                             add_post_meta($order_id, '_order_currency', $order['currency'], true);
                         }
                         // billing info
                         if (isset($order['user_name']) && !empty($order['user_name'])) {
                             add_post_meta($order_id, '_billing_email', $order['user_name'], true);
                         }
                         $i = 0;
                         foreach ($order['products'] as $products) {
                             $product_id = $this->isReferenceExists_order($products['sku']);
                             if ($product_id['result'] == 'success' && !empty($product_id['data'])) {
                                 $product = new WC_Product($product_id['data']);
                                 if ($product->post->post_type == 'product_variation') {
                                     $variant_id = $product->id;
                                     $product->id = $product->post->post_parent;
                                 }
                                 $wcproduct = $product->post;
                                 if ($product) {
                                     // add item
                                     $item_id = wc_add_order_item($order_id, array('order_item_name' => $wcproduct->post_title, 'order_item_type' => 'line_item'));
                                     if ($item_id) {
                                         $line_tax = array();
                                         $line_subtax = array();
                                         // add item meta data
                                         if (isset($products['price']) && !empty($products['price'])) {
                                             $products['price'] = (double) ($products['price'] * $products['quantity']);
                                         }
                                         $line_total = (double) $products['price'];
                                         wc_add_order_item_meta($item_id, '_qty', $products['quantity']);
                                         //Product Order Quantity From Vend
                                         wc_add_order_item_meta($item_id, '_product_id', $product->id);
                                         wc_add_order_item_meta($item_id, '_line_total', $line_total);
                                         wc_add_order_item_meta($item_id, '_variation_id', isset($variant_id) ? $variant_id : '');
                                         $result_tax_class = $this->linksync_tax_classes_vend_to_wc($products['taxId']);
                                         if ($result_tax_class['result'] == 'success') {
                                             $tax_class = $result_tax_class['tax_class'];
                                         }
                                         wc_add_order_item_meta($item_id, '_tax_class', isset($tax_class) ? $tax_class : '');
                                         wc_add_order_item_meta($item_id, '_line_tax', $products['taxValue']);
                                         wc_add_order_item_meta($item_id, '_line_subtotal', $products['price']);
                                         wc_add_order_item_meta($item_id, '_line_subtotal_tax', $products['taxValue']);
                                         $line_tax['total'][1] = $products['taxValue'];
                                         $line_subtax['subtotal'][1] = $products['taxValue'];
                                         $line_tax_data = array_merge($line_tax, $line_subtax);
                                         wc_add_order_item_meta($item_id, '_line_tax_data', $line_tax_data);
                                         if (isset($variant_id) && !empty($variant_id)) {
                                             global $wpdb;
                                             $query = mysql_query("SELECT meta_key,meta_value FROM `" . $wpdb->prefix . "postmeta` WHERE post_id='" . $variant_id . "' AND meta_key LIKE 'attribute_pa_%'");
                                             while ($result = mysql_fetch_assoc($query)) {
                                                 $meta_key = str_replace('attribute_', '', $result['meta_key']);
                                                 wc_add_order_item_meta($item_id, $meta_key, $result['meta_value']);
                                             }
                                         }
                                     }
                                 } else {
                                     $order->errors = 'Product SKU (' . $order->{$item_id} . ') not found.';
                                 }
                             } elseif ($products['sku'] == 'shipping') {
                                 $taxes = array();
                                 // add item
                                 $shipping_id = wc_add_order_item($order_id, array('order_item_name' => $products['title'], 'order_item_type' => 'shipping'));
                                 if ($shipping_id) {
                                     wc_add_order_item_meta($shipping_id, 'cost', $products['price']);
                                     wc_add_order_item_meta($shipping_id, 'method_id', '');
                                     wc_add_order_item_meta($shipping_id, 'taxes', '');
                                     add_post_meta($order_id, '_order_shipping', $products['price']);
                                     add_post_meta($order_id, '_order_shipping_tax', $products['taxValue']);
                                     $shippping_tax_amount = $products['taxValue'];
                                     $taxes[1] = $products['taxValue'];
                                     wc_add_order_item_meta($shipping_id, 'taxes', $taxes);
                                 }
                             } elseif ($products['sku'] == 'vend-discount') {
                                 add_post_meta($order_id, '_cart_discount', $products['price']);
                             }
                             /* ---------------------------------------Tax Mapping --------------------------------- */
                             if ($products['sku'] != 'shipping' || $products['sku'] != 'vend-discount') {
                                 if ($i == 0) {
                                     $tax_class_name = $this->linksync_tax_classes_vend_to_wc($products['taxId']);
                                     if ($tax_class_name['result'] == 'success') {
                                         // add item
                                         $tax_id = wc_add_order_item($order_id, array('order_item_name' => $tax_class_name['tax_class_name'] . '-' . $tax_class_name['tax_rate_id'], 'order_item_type' => 'tax'));
                                         if ($tax_id) {
                                             wc_add_order_item_meta($tax_id, 'rate_id', $tax_class_name['tax_rate_id']);
                                             wc_add_order_item_meta($tax_id, 'label', $tax_class_name['tax_class_name']);
                                             wc_add_order_item_meta($tax_id, 'compound', 0);
                                             $tax_amount = $order['total_tax'];
                                             wc_add_order_item_meta($tax_id, 'tax_amount', isset($tax_amount) ? $tax_amount : 0);
                                             wc_add_order_item_meta($tax_id, 'shipping_tax_amount', isset($shippping_tax_amount) ? $shippping_tax_amount : 0);
                                         }
                                     }
                                     $i++;
                                 }
                             }
                         }
                     }
                     linksync_class::add('Order Sync Vend to Woo', 'success', 'Vend Order no:' . $order['orderId'] . ', Woo Order no:' . $order_id, get_option('linksync_laid'));
                 }
             }
         }
     }
     return true;
 }
コード例 #20
0
 /**
  * Add a fee to the order
  *
  * @param object $fee
  * @return int|bool Item ID or false
  */
 public function add_fee($fee)
 {
     $item_id = wc_add_order_item($this->id, array('order_item_name' => $fee->name, 'order_item_type' => 'fee'));
     if (!$item_id) {
         return false;
     }
     if ($fee->taxable) {
         wc_add_order_item_meta($item_id, '_tax_class', $fee->tax_class);
     } else {
         wc_add_order_item_meta($item_id, '_tax_class', '0');
     }
     wc_add_order_item_meta($item_id, '_line_total', wc_format_decimal($fee->amount));
     wc_add_order_item_meta($item_id, '_line_tax', wc_format_decimal($fee->tax));
     // Save tax data - Since 2.2
     $tax_data = array_map('wc_format_decimal', $fee->tax_data);
     wc_add_order_item_meta($item_id, '_line_tax_data', array('total' => $tax_data));
     do_action('woocommerce_order_add_fee', $this->id, $item_id, $fee);
     return $item_id;
 }
コード例 #21
0
 /**
  * Calc line tax
  */
 public function calc_line_taxes()
 {
     global $wpdb;
     check_ajax_referer('calc-totals', 'security');
     $this->json_headers();
     $tax = new WC_Tax();
     $taxes = $tax_rows = $item_taxes = $shipping_taxes = array();
     $order_id = absint($_POST['order_id']);
     $order = new WC_Order($order_id);
     $country = strtoupper(esc_attr($_POST['country']));
     $state = strtoupper(esc_attr($_POST['state']));
     $postcode = strtoupper(esc_attr($_POST['postcode']));
     $city = sanitize_title(esc_attr($_POST['city']));
     $items = isset($_POST['items']) ? $_POST['items'] : array();
     $shipping = $_POST['shipping'];
     $item_tax = 0;
     // Calculate sales tax first
     if (sizeof($items) > 0) {
         foreach ($items as $item_id => $item) {
             $item_id = absint($item_id);
             $line_subtotal = isset($item['line_subtotal']) ? wc_format_decimal($item['line_subtotal']) : 0;
             $line_total = wc_format_decimal($item['line_total']);
             $tax_class = sanitize_text_field($item['tax_class']);
             $product_id = $order->get_item_meta($item_id, '_product_id', true);
             if (!$item_id || '0' == $tax_class) {
                 continue;
             }
             // Get product details
             if (get_post_type($product_id) == 'product') {
                 $_product = get_product($product_id);
                 $item_tax_status = $_product->get_tax_status();
             } else {
                 $item_tax_status = 'taxable';
             }
             // Only calc if taxable
             if ('taxable' == $item_tax_status) {
                 $tax_rates = $tax->find_rates(array('country' => $country, 'state' => $state, 'postcode' => $postcode, 'city' => $city, 'tax_class' => $tax_class));
                 $line_subtotal_taxes = $tax->calc_tax($line_subtotal, $tax_rates, false);
                 $line_taxes = $tax->calc_tax($line_total, $tax_rates, false);
                 $line_subtotal_tax = array_sum($line_subtotal_taxes);
                 $line_tax = array_sum($line_taxes);
                 if ($line_subtotal_tax < 0) {
                     $line_subtotal_tax = 0;
                 }
                 if ($line_tax < 0) {
                     $line_tax = 0;
                 }
                 $item_taxes[$item_id] = array('line_subtotal_tax' => wc_format_localized_price($line_subtotal_tax), 'line_tax' => wc_format_localized_price($line_tax));
                 $item_tax += $line_tax;
                 // Sum the item taxes
                 foreach (array_keys($taxes + $line_taxes) as $key) {
                     $taxes[$key] = (isset($line_taxes[$key]) ? $line_taxes[$key] : 0) + (isset($taxes[$key]) ? $taxes[$key] : 0);
                 }
             }
         }
     }
     // Now calculate shipping tax
     $matched_tax_rates = array();
     $tax_rates = $tax->find_rates(array('country' => $country, 'state' => $state, 'postcode' => $postcode, 'city' => $city, 'tax_class' => ''));
     if ($tax_rates) {
         foreach ($tax_rates as $key => $rate) {
             if (isset($rate['shipping']) && 'yes' == $rate['shipping']) {
                 $matched_tax_rates[$key] = $rate;
             }
         }
     }
     $shipping_taxes = $tax->calc_shipping_tax($shipping, $matched_tax_rates);
     $shipping_tax = $tax->round(array_sum($shipping_taxes));
     // Remove old tax rows
     $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'tax' )", $order_id));
     $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id = %d AND order_item_type = 'tax'", $order_id));
     // Get tax rates
     $rates = $wpdb->get_results("SELECT tax_rate_id, tax_rate_country, tax_rate_state, tax_rate_name, tax_rate_priority FROM {$wpdb->prefix}woocommerce_tax_rates ORDER BY tax_rate_name");
     $tax_codes = array();
     foreach ($rates as $rate) {
         $code = array();
         $code[] = $rate->tax_rate_country;
         $code[] = $rate->tax_rate_state;
         $code[] = $rate->tax_rate_name ? sanitize_title($rate->tax_rate_name) : 'TAX';
         $code[] = absint($rate->tax_rate_priority);
         $tax_codes[$rate->tax_rate_id] = strtoupper(implode('-', array_filter($code)));
     }
     // Now merge to keep tax rows
     ob_start();
     foreach (array_keys($taxes + $shipping_taxes) as $key) {
         $item = array();
         $item['rate_id'] = $key;
         $item['name'] = $tax_codes[$key];
         $item['label'] = $tax->get_rate_label($key);
         $item['compound'] = $tax->is_compound($key) ? 1 : 0;
         $item['tax_amount'] = wc_format_decimal(isset($taxes[$key]) ? $taxes[$key] : 0);
         $item['shipping_tax_amount'] = wc_format_decimal(isset($shipping_taxes[$key]) ? $shipping_taxes[$key] : 0);
         if (!$item['label']) {
             $item['label'] = WC()->countries->tax_or_vat();
         }
         // Add line item
         $item_id = wc_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'tax'));
         // Add line item meta
         if ($item_id) {
             wc_add_order_item_meta($item_id, 'rate_id', $item['rate_id']);
             wc_add_order_item_meta($item_id, 'label', $item['label']);
             wc_add_order_item_meta($item_id, 'compound', $item['compound']);
             wc_add_order_item_meta($item_id, 'tax_amount', $item['tax_amount']);
             wc_add_order_item_meta($item_id, 'shipping_tax_amount', $item['shipping_tax_amount']);
         }
         include 'admin/post-types/meta-boxes/views/html-order-tax.php';
     }
     $tax_row_html = ob_get_clean();
     // Return
     echo json_encode(array('item_tax' => $item_tax, 'item_taxes' => $item_taxes, 'shipping_tax' => $shipping_tax, 'tax_row_html' => $tax_row_html));
     // Quit out
     die;
 }
コード例 #22
0
function wc_update_200_line_items()
{
    global $wpdb;
    // Now its time for the massive update to line items - move them to the new DB tables
    // Reverse with UPDATE `wpwc_postmeta` SET meta_key = '_order_items' WHERE meta_key = '_order_items_old'
    $order_item_rows = $wpdb->get_results("\n\t\tSELECT * FROM {$wpdb->postmeta}\n\t\tWHERE meta_key = '_order_items'\n\t");
    foreach ($order_item_rows as $order_item_row) {
        $order_items = (array) maybe_unserialize($order_item_row->meta_value);
        foreach ($order_items as $order_item) {
            if (!isset($order_item['line_total']) && isset($order_item['taxrate']) && isset($order_item['cost'])) {
                $order_item['line_tax'] = number_format($order_item['cost'] * $order_item['qty'] * ($order_item['taxrate'] / 100), 2, '.', '');
                $order_item['line_total'] = $order_item['cost'] * $order_item['qty'];
                $order_item['line_subtotal_tax'] = $order_item['line_tax'];
                $order_item['line_subtotal'] = $order_item['line_total'];
            }
            $order_item['line_tax'] = isset($order_item['line_tax']) ? $order_item['line_tax'] : 0;
            $order_item['line_total'] = isset($order_item['line_total']) ? $order_item['line_total'] : 0;
            $order_item['line_subtotal_tax'] = isset($order_item['line_subtotal_tax']) ? $order_item['line_subtotal_tax'] : 0;
            $order_item['line_subtotal'] = isset($order_item['line_subtotal']) ? $order_item['line_subtotal'] : 0;
            $item_id = wc_add_order_item($order_item_row->post_id, array('order_item_name' => $order_item['name'], 'order_item_type' => 'line_item'));
            // Add line item meta
            if ($item_id) {
                wc_add_order_item_meta($item_id, '_qty', absint($order_item['qty']));
                wc_add_order_item_meta($item_id, '_tax_class', $order_item['tax_class']);
                wc_add_order_item_meta($item_id, '_product_id', $order_item['id']);
                wc_add_order_item_meta($item_id, '_variation_id', $order_item['variation_id']);
                wc_add_order_item_meta($item_id, '_line_subtotal', wc_format_decimal($order_item['line_subtotal']));
                wc_add_order_item_meta($item_id, '_line_subtotal_tax', wc_format_decimal($order_item['line_subtotal_tax']));
                wc_add_order_item_meta($item_id, '_line_total', wc_format_decimal($order_item['line_total']));
                wc_add_order_item_meta($item_id, '_line_tax', wc_format_decimal($order_item['line_tax']));
                $meta_rows = array();
                // Insert meta
                if (!empty($order_item['item_meta'])) {
                    foreach ($order_item['item_meta'] as $key => $meta) {
                        // Backwards compatibility
                        if (is_array($meta) && isset($meta['meta_name'])) {
                            $meta_rows[] = '(' . $item_id . ',"' . esc_sql($meta['meta_name']) . '","' . esc_sql($meta['meta_value']) . '")';
                        } else {
                            $meta_rows[] = '(' . $item_id . ',"' . esc_sql($key) . '","' . esc_sql($meta) . '")';
                        }
                    }
                }
                // Insert meta rows at once
                if (sizeof($meta_rows) > 0) {
                    $wpdb->query($wpdb->prepare("\n\t\t\t\t\t\tINSERT INTO {$wpdb->prefix}woocommerce_order_itemmeta ( order_item_id, meta_key, meta_value )\n\t\t\t\t\t\tVALUES " . implode(',', $meta_rows) . ";\n\t\t\t\t\t", $order_item_row->post_id));
                }
                // Delete from DB (rename)
                $wpdb->query($wpdb->prepare("\n\t\t\t\t\tUPDATE {$wpdb->postmeta}\n\t\t\t\t\tSET meta_key = '_order_items_old'\n\t\t\t\t\tWHERE meta_key = '_order_items'\n\t\t\t\t\tAND post_id = %d\n\t\t\t\t", $order_item_row->post_id));
            }
            unset($meta_rows, $item_id, $order_item);
        }
    }
    // Do the same kind of update for order_taxes - move to lines
    // Reverse with UPDATE `wpwc_postmeta` SET meta_key = '_order_taxes' WHERE meta_key = '_order_taxes_old'
    $order_tax_rows = $wpdb->get_results("\n\t\tSELECT * FROM {$wpdb->postmeta}\n\t\tWHERE meta_key = '_order_taxes'\n\t");
    foreach ($order_tax_rows as $order_tax_row) {
        $order_taxes = (array) maybe_unserialize($order_tax_row->meta_value);
        if (!empty($order_taxes)) {
            foreach ($order_taxes as $order_tax) {
                if (!isset($order_tax['label']) || !isset($order_tax['cart_tax']) || !isset($order_tax['shipping_tax'])) {
                    continue;
                }
                $item_id = wc_add_order_item($order_tax_row->post_id, array('order_item_name' => $order_tax['label'], 'order_item_type' => 'tax'));
                // Add line item meta
                if ($item_id) {
                    wc_add_order_item_meta($item_id, 'compound', absint(isset($order_tax['compound']) ? $order_tax['compound'] : 0));
                    wc_add_order_item_meta($item_id, 'tax_amount', wc_clean($order_tax['cart_tax']));
                    wc_add_order_item_meta($item_id, 'shipping_tax_amount', wc_clean($order_tax['shipping_tax']));
                }
                // Delete from DB (rename)
                $wpdb->query($wpdb->prepare("\n\t\t\t\t\tUPDATE {$wpdb->postmeta}\n\t\t\t\t\tSET meta_key = '_order_taxes_old'\n\t\t\t\t\tWHERE meta_key = '_order_taxes'\n\t\t\t\t\tAND post_id = %d\n\t\t\t\t", $order_tax_row->post_id));
                unset($tax_amount);
            }
        }
    }
}
コード例 #23
-1
 /**
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     $cashback = isset($_POST['pos-cashback']) ? wc_format_decimal($_POST['pos-cashback']) : 0;
     if ($cashback !== 0) {
         // add order meta
         update_post_meta($order_id, '_pos_card_cashback', $cashback);
         // add cashback as fee line item
         // TODO: this should be handled by $order->add_fee after WC 2.2
         $item_id = wc_add_order_item($order_id, array('order_item_name' => __('Cashback', 'woocommerce-pos'), 'order_item_type' => 'fee'));
         if ($item_id) {
             wc_add_order_item_meta($item_id, '_line_total', $cashback);
             wc_add_order_item_meta($item_id, '_line_tax', 0);
             wc_add_order_item_meta($item_id, '_line_subtotal', $cashback);
             wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
             wc_add_order_item_meta($item_id, '_tax_class', 'zero-rate');
         }
         // update the order total to include fee
         $order_total = get_post_meta($order_id, '_order_total', true);
         $order_total += $cashback;
         update_post_meta($order_id, '_order_total', $order_total);
     }
     // payment complete
     $order->payment_complete();
     // success
     return array('result' => 'success');
 }