/**
  * Create a order.
  *
  * @since 2.4
  *
  * @return WC_Order Order object.
  */
 public static function create_order()
 {
     // Create product
     $product = WC_Helper_Product::create_simple_product();
     WC_Helper_Shipping::create_simple_flat_rate();
     $order_data = array('status' => 'pending', 'customer_id' => 1, 'customer_note' => '', 'total' => '');
     $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
     // Required, else wc_create_order throws an exception
     $order = wc_create_order($order_data);
     // Add order products
     $item_id = $order->add_product($product, 4);
     // Set billing address
     $billing_address = array('country' => 'US', 'first_name' => 'Jeroen', 'last_name' => 'Sormani', 'company' => 'WooCompany', 'address_1' => 'WooAddress', 'address_2' => '', 'postcode' => '123456', 'city' => 'WooCity', 'state' => 'NY', 'email' => '*****@*****.**', 'phone' => '555-32123');
     $order->set_address($billing_address, 'billing');
     // Add shipping costs
     $shipping_taxes = WC_Tax::calc_shipping_tax('10', WC_Tax::get_shipping_tax_rates());
     $order->add_shipping(new WC_Shipping_Rate('flat_rate_shipping', 'Flat rate shipping', '10', $shipping_taxes, 'flat_rate'));
     // Set payment gateway
     $payment_gateways = WC()->payment_gateways->payment_gateways();
     $order->set_payment_method($payment_gateways['bacs']);
     // Set totals
     $order->set_total(10, 'shipping');
     $order->set_total(0, 'cart_discount');
     $order->set_total(0, 'cart_discount_tax');
     $order->set_total(0, 'tax');
     $order->set_total(0, 'shipping_tax');
     $order->set_total(40, 'total');
     // 4 x $10 simple helper product
     return wc_get_order($order->id);
 }
 public function update_order($data, $iopn_record_id)
 {
     global $wpdb, $woocommerce;
     $prefix = $wpdb->prefix . 'pwa_';
     $xml = simplexml_load_string($data);
     $NotificationReferenceId = $xml->NotificationReferenceId;
     $OrderChannel = $xml->ProcessedOrder->OrderChannel;
     $AmazonOrderID = (string) $xml->ProcessedOrder->AmazonOrderID;
     $OrderDate = $xml->ProcessedOrder->OrderDate;
     $param['NotificationReferenceId'] = $NotificationReferenceId;
     $param['AmazonOrderID'] = $AmazonOrderID;
     $param['iopn_record_id'] = $iopn_record_id;
     $order_postmeta = $wpdb->get_results("select post_id from {$wpdb->postmeta} where meta_key = '_pwa_order_id' and meta_value = '{$AmazonOrderID}' ");
     if (empty($order_postmeta)) {
         $request_time = $wpdb->get_results("select * from `" . $prefix . "iopn_records` where amazon_order_id = '{$AmazonOrderID}' and notification_reference_id = '{$NotificationReferenceId}' and status = 'Rejected' ");
         if (!empty($request_time)) {
             $param['Status'] = 'Accepted';
             $this->update_request($param);
             $order = wc_create_order();
             add_post_meta($order->id, '_pwa_order_id', $AmazonOrderID);
             $this->update_order_detail($order->id, $data);
         } else {
             $param['Status'] = 'Rejected';
             $this->update_request($param);
             header('HTTP/1.1 503 SERVICE_UNAVAILABLE');
             exit;
         }
     } else {
         $param['Status'] = 'Accepted';
         $this->update_request($param);
         $order_id = $order_postmeta[0]->post_id;
         $this->update_order_detail($order_id, $data);
     }
 }
 /**
  * Create a order.
  *
  * @since 2.4
  *
  * @return WC_Order Order object.
  */
 public static function create_order($customer_id = 1)
 {
     // Create product
     $product = WC_Helper_Product::create_simple_product();
     WC_Helper_Shipping::create_simple_flat_rate();
     $order_data = array('status' => 'pending', 'customer_id' => $customer_id, 'customer_note' => '', 'total' => '');
     $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
     // Required, else wc_create_order throws an exception
     $order = wc_create_order($order_data);
     // Add order products
     $order->add_product($product, 4);
     // Set billing address
     $order->set_billing_first_name('Jeroen');
     $order->set_billing_last_name('Sormani');
     $order->set_billing_company('WooCompany');
     $order->set_billing_address_1('WooAddress');
     $order->set_billing_address_2('');
     $order->set_billing_city('WooCity');
     $order->set_billing_state('NY');
     $order->set_billing_postcode('123456');
     $order->set_billing_country('US');
     $order->set_billing_email('*****@*****.**');
     $order->set_billing_phone('555-32123');
     // Add shipping costs
     $shipping_taxes = WC_Tax::calc_shipping_tax('10', WC_Tax::get_shipping_tax_rates());
     $rate = new WC_Shipping_Rate('flat_rate_shipping', 'Flat rate shipping', '10', $shipping_taxes, 'flat_rate');
     $item = new WC_Order_Item_Shipping();
     $item->set_props(array('method_title' => $rate->label, 'method_id' => $rate->id, 'total' => wc_format_decimal($rate->cost), 'taxes' => $rate->taxes, 'meta_data' => $rate->get_meta_data()));
     $order->add_item($item);
     // Set payment gateway
     $payment_gateways = WC()->payment_gateways->payment_gateways();
     $order->set_payment_method($payment_gateways['bacs']);
     // Set totals
     $order->set_shipping_total(10);
     $order->set_discount_total(0);
     $order->set_discount_tax(0);
     $order->set_cart_tax(0);
     $order->set_shipping_tax(0);
     $order->set_total(40);
     // 4 x $10 simple helper product
     $order->save();
     return $order;
 }
 /**
  * Creates new WC_Order.
  *
  * @since 3.0.0
  * @param $args array
  * @return WC_Order
  */
 private function create_base_order($args, $data)
 {
     return wc_create_order($args);
 }
 /**
  * Create an order
  *
  * @since 2.2
  * @param array $data raw order data
  * @return array
  */
 public function create_order($data)
 {
     $data = isset($data['order']) ? $data['order'] : array();
     try {
         // permission check
         if (!current_user_can('publish_shop_orders')) {
             throw new WC_API_Exception('woocommerce_api_user_cannot_create_order', __('You do not have permission to create orders', 'woocommerce'), 401);
         }
         $data = apply_filters('woocommerce_api_create_order_data', $data, $this);
         // default order args, note that status is checked for validity in wc_create_order()
         $default_order_args = array('status' => isset($data['status']) ? $data['status'] : '', 'customer_note' => isset($data['note']) ? $data['note'] : null);
         // if creating order for existing customer
         if (!empty($data['customer_id'])) {
             // make sure customer exists
             if (false === get_user_by('id', $data['customer_id'])) {
                 throw new WC_API_Exception('woocommerce_api_invalid_customer_id', __('Customer ID is invalid', 'woocommerce'), 400);
             }
             $default_order_args['customer_id'] = $data['customer_id'];
         }
         // create the pending order
         $order = wc_create_order($default_order_args);
         if (is_wp_error($order)) {
             throw new WC_API_Exception('woocommerce_api_cannot_create_order', sprintf(__('Cannot create order: %s', 'woocommerce'), implode(', ', $order->get_error_messages())), 400);
         }
         // billing/shipping addresses
         $this->set_order_addresses($order, $data);
         $lines = array('line_item' => 'line_items', 'shipping' => 'shipping_lines', 'fee' => 'fee_lines', 'coupon' => 'coupon_lines');
         foreach ($lines as $line_type => $line) {
             if (isset($data[$line]) && is_array($data[$line])) {
                 $set_item = "set_{$line_type}";
                 foreach ($data[$line] as $item) {
                     $this->{$set_item}($order, $item, 'create');
                 }
             }
         }
         // calculate totals and set them
         $order->calculate_totals();
         // payment method (and payment_complete() if `paid` == true)
         if (isset($data['payment_details']) && is_array($data['payment_details'])) {
             // method ID & title are required
             if (empty($data['payment_details']['method_id']) || empty($data['payment_details']['method_title'])) {
                 throw new WC_API_Exception('woocommerce_invalid_payment_details', __('Payment method ID and title are required', 'woocommerce'), 400);
             }
             update_post_meta($order->id, '_payment_method', $data['payment_details']['method_id']);
             update_post_meta($order->id, '_payment_method_title', $data['payment_details']['method_title']);
             // mark as paid if set
             if (isset($data['payment_details']['paid']) && 'true' === $data['payment_details']['paid']) {
                 $order->payment_complete(isset($data['payment_details']['transaction_id']) ? $data['payment_details']['transaction_id'] : '');
             }
         }
         // set order currency
         if (isset($data['currency'])) {
             if (!array_key_exists($data['currency'], get_woocommerce_currencies())) {
                 throw new WC_API_Exception('woocommerce_invalid_order_currency', __('Provided order currency is invalid', 'woocommerce'), 400);
             }
             update_post_meta($order->id, '_order_currency', $data['currency']);
         }
         // set order number
         if (isset($data['order_number'])) {
             update_post_meta($order->id, '_order_number', $data['order_number']);
         }
         // set order meta
         if (isset($data['order_meta']) && is_array($data['order_meta'])) {
             $this->set_order_meta($order->id, $data['order_meta']);
         }
         // HTTP 201 Created
         $this->server->send_status(201);
         wc_delete_shop_order_transients($order->id);
         do_action('woocommerce_api_create_order', $order->id, $this);
         return $this->get_order($order->id);
     } catch (WC_API_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }
 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;
                 }
             }
         }
     }
 }
 /**
  * Create WC order.
  *
  * @since  2.0.0
  * @access public
  */
 public function create_order()
 {
     if ($this->klarna_debug == 'yes') {
         $this->klarna_log->add('klarna', 'Creating local order...');
     }
     global $woocommerce;
     // Customer accounts
     $customer_id = apply_filters('woocommerce_checkout_customer_id', get_current_user_id());
     // Order data
     $order_data = array('status' => apply_filters('klarna_checkout_incomplete_order_status', 'kco-incomplete'), 'customer_id' => $customer_id, 'created_via' => 'klarna_checkout');
     // Create the order
     $order = wc_create_order($order_data);
     if (is_wp_error($order)) {
         throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
     }
     if ($this->klarna_debug == 'yes') {
         $this->klarna_log->add('klarna', 'Local order created, order ID: ' . $order->id);
     }
     return $order;
 }
function fast_order_plugin_cb()
{
    global $post;
    global $woocommerce;
    global $product;
    global $wp_query;
    parse_str($_POST['formdata'], $formdata);
    $fullname = $formdata['fullname'];
    $address = $formdata['address'];
    $phone = $formdata['telephone'];
    $email = $formdata['email'];
    $pid = $formdata['pid'];
    $qty = $formdata['qty'];
    $flag = 0;
    $report = '<br/>';
    if ($is_alpha_space = ctype_alpha(str_replace(' ', '', $fullname)) && $address != NULL && is_numeric($phone) && $pid != NULL && !$qty <= 0 && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $flag = 1;
    } else {
        if (!($is_alpha_space = ctype_alpha(str_replace(' ', '', $fullname)))) {
            $report .= "Full Name field has an error: " . $fullname . "<br/>";
        }
        if (!$address != NULL) {
            $report .= "Address field has an error: " . $address . "<br/>";
        }
        if (!is_numeric($phone)) {
            $report .= "Phone field has an error: " . $phone . "<br/>";
        }
        if (!$pid != NULL) {
            $report .= "Product id is not correct: " . $pid . "<br/>";
        }
        if ($qty <= 0) {
            $report .= "Quantity field has an error: " . $qty . "<br/>";
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $report .= "Email field has an error: " . $email . "<br/>";
        }
        $flag = 0;
    }
    if ($flag == 1) {
        $address = array('first_name' => $fullname, 'email' => $email, 'phone' => '+92-' . $phone . '', 'address_1' => $address, 'country' => 'PK');
        $order = wc_create_order();
        $order->add_product(get_product($pid), $qty);
        //(get_product with id and next is for quantity)
        $order->set_address($address, 'billing');
        $order->set_address($address, 'shipping');
        $order->calculate_totals();
        $messages = "Thank you " . $fullname . " <br/>Your order has been placed. <br/>You will receive a call from our representative shortly";
    } else {
        $messages = "There is an error in the form <br/> Please correct it" . $report;
    }
    $return_data = array('flag' => $flag, 'messages' => $messages);
    echo json_encode($return_data);
    //echo "Yes! the ajax call was successful"; // this message will be displayed in our jacascript alert
    die(0);
}
 /**
  * Create order
  * @param  float $total
  * @param  int $customer_id
  * @return int
  */
 public function create_order($total, $customer_id)
 {
     if (function_exists('wc_create_order')) {
         $order = wc_create_order(array('customer_id' => absint($customer_id)));
         $order_id = $order->id;
         $order->set_total($total);
         update_post_meta($order->id, '_booking_order', '1');
     } else {
         $order_data = apply_filters('woocommerce_new_order_data', array('post_type' => 'shop_order', 'post_title' => sprintf(__('Order &ndash; %s', 'woocommerce-bookings'), strftime(_x('%b %d, %Y @ %I:%M %p', 'Order date parsed by strftime', 'woocommerce-bookings'))), 'post_status' => 'publish', 'ping_status' => 'closed', 'post_excerpt' => '', 'post_author' => 1, 'post_password' => uniqid('order_')));
         $order_id = wp_insert_post($order_data, true);
         update_post_meta($order_id, '_order_shipping', 0);
         update_post_meta($order_id, '_order_discount', 0);
         update_post_meta($order_id, '_cart_discount', 0);
         update_post_meta($order_id, '_order_tax', 0);
         update_post_meta($order_id, '_order_shipping_tax', 0);
         update_post_meta($order_id, '_order_total', $total);
         update_post_meta($order_id, '_order_key', apply_filters('woocommerce_generate_order_key', uniqid('order_')));
         update_post_meta($order_id, '_customer_user', absint($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, '_booking_order', '1');
         wp_set_object_terms($order_id, 'pending', 'shop_order_status');
     }
     do_action('woocommerce_new_booking_order', $order_id);
     return $order_id;
 }
 /**
  * Create new order for WooCommerce version 2.2+
  * @return int|WP_ERROR 
  */
 public function create_order_2_2()
 {
     global $woocommerce, $wpdb;
     $this->shipping_methods = WC()->session->get('chosen_shipping_methods');
     if (sizeof($woocommerce->cart->get_cart()) == 0) {
         wc_add_notice(sprintf(__('Sorry, your session has expired. <a href="%s">Return to homepage &rarr;</a>', 'hygglig'), home_url()), 'error');
     }
     // Recheck cart items so that they are in stock
     $result = $woocommerce->cart->check_cart_item_stock();
     if (is_wp_error($result)) {
         return $result->get_error_message();
         exit;
     }
     // Update cart totals
     $woocommerce->cart->calculate_totals();
     // Customer accounts
     $this->customer_id = apply_filters('woocommerce_checkout_customer_id', get_current_user_id());
     // Give plugins the opportunity to create an order themselves
     if ($order_id = apply_filters('woocommerce_create_order', null, $this)) {
         return $order_id;
     }
     try {
         // Start transaction if available
         $wpdb->query('START TRANSACTION');
         $order_data = array('status' => apply_filters('woocommerce_default_order_status', 'pending'), 'customer_id' => $this->customer_id, 'customer_note' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '');
         // Insert or update the post data
         $order_id = absint(WC()->session->order_awaiting_payment);
         // Resume the unpaid order if its pending
         if ($order_id > 0 && ($order = wc_get_order($order_id)) && $order->has_status(array('pending', 'failed'))) {
             $order_data['order_id'] = $order_id;
             $order = wc_update_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order->remove_order_items();
                 do_action('woocommerce_resume_order', $order_id);
             }
         } else {
             $order = wc_create_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order_id = $order->id;
                 do_action('woocommerce_new_order', $order_id);
             }
         }
         // Store the line items to the new/resumed order
         foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
             $item_id = $order->add_product($values['data'], $values['quantity'], array('variation' => $values['variation'], 'totals' => array('subtotal' => $values['line_subtotal'], 'subtotal_tax' => $values['line_subtotal_tax'], 'total' => $values['line_total'], 'tax' => $values['line_tax'], 'tax_data' => $values['line_tax_data'])));
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // 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_key => $fee) {
             $item_id = $order->add_fee($fee);
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // Allow plugins to add order item meta to fees
             do_action('woocommerce_add_order_fee_meta', $order_id, $item_id, $fee, $fee_key);
         }
         // Store shipping for all packages
         foreach (WC()->shipping->get_packages() as $package_key => $package) {
             if (isset($package['rates'][$this->shipping_methods[$package_key]])) {
                 $item_id = $order->add_shipping($package['rates'][$this->shipping_methods[$package_key]]);
                 if (!$item_id) {
                     throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
                 }
                 // Allows plugins to add order item meta to shipping
                 do_action('woocommerce_add_shipping_order_item', $order_id, $item_id, $package_key);
             }
         }
         // Store tax rows
         foreach (array_keys(WC()->cart->taxes + WC()->cart->shipping_taxes) as $tax_rate_id) {
             if (!$order->add_tax($tax_rate_id, WC()->cart->get_tax_amount($tax_rate_id), WC()->cart->get_shipping_tax_amount($tax_rate_id))) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Store coupons
         foreach (WC()->cart->get_coupons() as $code => $coupon) {
             if (!$order->add_coupon($code, WC()->cart->get_coupon_discount_amount($code))) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Payment Method
         $available_gateways = WC()->payment_gateways->payment_gateways();
         $this->payment_method = $available_gateways['hygglig_checkout'];
         $order->set_payment_method($this->payment_method);
         $order->set_total(WC()->cart->shipping_total, 'shipping');
         $order->set_total(WC()->cart->get_total_discount(), 'order_discount');
         $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
         $order->set_total(WC()->cart->tax_total, 'tax');
         $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
         $order->set_total(WC()->cart->total);
         // Let plugin add meta
         do_action('woocommerce_checkout_update_order_meta', $order_id, array());
         // If we got here, the order was created without problems!
         $wpdb->query('COMMIT');
     } catch (Exception $e) {
         // There was an error adding order data!
         $wpdb->query('ROLLBACK');
         return new WP_Error('checkout-error', $e->getMessage());
     }
     return $order_id;
 }
/**
 * 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());
    }
}
 function invokeGetReportRequestList(MarketplaceWebService_Interface $service, $request)
 {
     global $wpdb, $woocommerce;
     try {
         $response = $service->getReportRequestList($request);
         if ($response->isSetGetReportRequestListResult()) {
             $getReportRequestListResult = $response->getGetReportRequestListResult();
             $reportRequestInfoList = $getReportRequestListResult->getReportRequestInfoList();
             print_r($reportRequestInfoList);
             foreach ($reportRequestInfoList as $reportRequestInfo) {
                 if ($reportRequestInfo->isSetReportType() && $reportRequestInfo->getReportType() == '_GET_ORDERS_DATA_' && ($reportRequestInfo->isSetReportProcessingStatus() && $reportRequestInfo->getReportProcessingStatus() == '_DONE_')) {
                     if ($reportRequestInfo->isSetReportRequestId()) {
                         $ReportRequestId = $reportRequestInfo->getReportRequestId();
                     }
                     if ($reportRequestInfo->isSetGeneratedReportId()) {
                         $GeneratedReportId = $reportRequestInfo->getGeneratedReportId();
                         if ($GeneratedReportId == '' && $ReportRequestId != '') {
                             $GeneratedReportId = $this->get_report_list_api($ReportRequestId);
                             $data = $this->get_report_api($GeneratedReportId);
                         } else {
                             $data = $this->get_report_api($GeneratedReportId);
                         }
                         $xml = simplexml_load_string($data);
                         // Check and dump MWS Report API Response
                         $pwacheckkout = new Pwacheckout();
                         if ($pwacheckkout->get_option('mws_report_dump') == 'yes') {
                             $dir = $pwacheckkout->get_option('mws_report_dump_url');
                             if (!file_exists($dir) && !is_dir($dir)) {
                                 mkdir($dir, 0777);
                             }
                             $filename = $dir . $GeneratedReportId . '_mws_report';
                             $myfile = fopen($filename, "w");
                             fwrite($myfile, $data);
                             fclose($myfile);
                         }
                         foreach ($xml->Message as $orderdetail) {
                             $AmazonOrderID = (string) $orderdetail->OrderReport->AmazonOrderID;
                             $order_postmeta = $wpdb->get_results("select post_id from {$wpdb->postmeta} where meta_key = '_pwa_order_id' and meta_value = '{$AmazonOrderID}' ");
                             if (empty($order_postmeta)) {
                                 $order = wc_create_order();
                                 add_post_meta($order->id, '_pwa_order_id', $AmazonOrderID);
                                 $this->update_order_detail($order->id, $orderdetail);
                             } else {
                                 $order_id = $order_postmeta[0]->post_id;
                                 $this->update_order_detail($order_id, $orderdetail);
                             }
                         }
                     }
                 }
             }
             $dateTime = new DateTime('now', new DateTimeZone('UTC'));
             $time = $dateTime->format(DATE_ISO8601);
             $wpdb->insert($wpdb->prefix . 'pwa_mws_report_cron', array('created_before' => $time));
         }
     } catch (MarketplaceWebService_Exception $ex) {
         $message = 'MWS Report API : Caught Exception : ' . $ex->getMessage() . "\n";
         $message .= "Response Status Code: " . $ex->getStatusCode() . "\n";
         $message .= "Error Code: " . $ex->getErrorCode() . "\n";
         $message .= "Error Type: " . $ex->getErrorType() . "\n";
         $param['message'] = $message;
         $this->generate_log($param);
     }
 }
Example #13
0
function hocwp_wc_insert_order($data)
{
    $post_id = hocwp_get_value_by_key($data, 'post_id');
    if (hocwp_id_number_valid($post_id)) {
        $post = get_post($post_id);
        if (is_a($post, 'WP_Post') && 'product' == $post->post_type) {
            $product = wc_get_product($post_id);
            $variable_product = new WC_Product_Variable($product);
            $variations = $variable_product->get_available_variations();
            $variation_args = array();
            $variation_id = null;
            foreach ($variations as $variation) {
                $variation_id = $variation['variation_id'];
                $variation_args['variation'] = $variation['attributes'];
            }
            $name = hocwp_get_value_by_key($data, 'name');
            $phone = hocwp_get_value_by_key($data, 'phone');
            $email = hocwp_get_value_by_key($data, 'email');
            $address = hocwp_get_value_by_key($data, 'address');
            $message = hocwp_get_value_by_key($data, 'message');
            $name = hocwp_sanitize_first_and_last_name($name);
            $attributes = hocwp_get_value_by_key($data, 'attributes');
            $addresses = array('first_name' => $name['first_name'], 'last_name' => $name['last_name'], 'email' => $email, 'phone' => $phone, 'address_1' => $address);
            $args = array('customer_note' => $message, 'created_via' => 'programmatically');
            if (is_user_logged_in()) {
                $current = wp_get_current_user();
                $args['customer_id'] = $current->ID;
            }
            $order = wc_create_order($args);
            $gateway = WC_Payment_Gateways::instance();
            $gateways = $gateway->get_available_payment_gateways();
            if (hocwp_array_has_value($gateways)) {
                $gateway = current($gateways);
                $order->set_payment_method($gateway);
            }
            $order->set_address($addresses);
            $order->set_address($addresses, 'shipping');
            if (hocwp_array_has_value($attributes) && hocwp_id_number_valid($variation_id)) {
                foreach ($attributes as $attribute) {
                    $attribute_name = hocwp_get_value_by_key($attribute, 'name');
                    $attribute_value = hocwp_get_value_by_key($attribute, 'value');
                    if (!empty($attribute_name) && !empty($attribute_value)) {
                        if (isset($variation_args['variation'][$attribute_name])) {
                            $variation_args['variation'][$attribute_name] = $attribute_value;
                        }
                    }
                }
                $variation_product = new WC_Product_Variation($variation_id);
                $order->add_product($variation_product, 1, $variation_args);
            } else {
                $order->add_product($product);
            }
            $order->record_product_sales();
            $order->calculate_totals();
            $order->payment_complete();
            return $order;
        }
    }
    return false;
}
 public function create_order()
 {
     var_dump($_POST);
     DABBA_API_Catch_Request::get()->check_params(array('company', 'phone', 'address_1', 'address_2', 'corp', 'timeframe', 'food_delivery_accepted', 'line_items', 'method_id', 'method_title', 'paid', 'user_id'));
     //$user = wp_get_current_user();
     $user = get_userdata($_POST['user_id']);
     $address = array('first_name' => $user->user_firstname, 'last_name' => $user->user_lastname, 'company' => $_POST['company'], 'email' => $user->user_email, 'phone' => $_POST['phone'], 'address_1' => $_POST['address_1'], 'address_2' => $_POST['address_2'], 'city' => 'Mexico City', 'state' => 'Distrito Federal', 'country' => 'MX', 'postcode' => $_POST['postcode']);
     $order = wc_create_order();
     $order->set_address($address, 'billing');
     $order->set_address($address, 'shipping');
     //$order->add_coupon('Fresher','10','2'); // accepted param $couponcode, $couponamount,$coupon_tax
     update_post_meta($order->id, 'billing_corp', sanitize_text_field($_POST['corp']));
     update_post_meta($order->id, 'billing_timeframe', sanitize_text_field($_POST['timeframe']));
     update_post_meta($order->id, 'billing_food_delivery_accepted', $_POST['food_delivery_accepted']);
     update_post_meta($order->id, '_payment_method', $_POST['method_id']);
     update_post_meta($order->id, '_payment_method_title', $_POST['method_title']);
     if (isset($_POST['stripe_transaction_id']) && isset($_POST['stripe_customer_id'])) {
         // $fee = ( 3.6 * $amount + 3 ) * 0.16;
         // $net_revenue = $amount - $fee;
         update_post_meta($order->id, 'Stripe Fee', 0);
         update_post_meta($order->id, 'Net Revenue From Stripe', 0);
         update_post_meta($order->id, '_transaction_id', $_POST['stripe_transaction_id']);
         update_post_meta($order->id, '_stripe_customer_id', $_POST['stripe_customer_id']);
         update_post_meta($order->id, '_stripe_charge_id', $_POST['stripe_transaction_id']);
     }
     if (isset($_POST['paypal_address']) && isset($_POST['paypal_payment_type']) && isset($_POST['paypal_transaction_fee'])) {
     }
     update_post_meta($order->id, '_customer_user', $_POST['user_id']);
     $line_items_decode = json_decode(stripslashes($_POST['line_items']));
     //$line_items_decode = json_decode( '[{"id" : "9579","quantity" : "1"},{"id" : "2933","quantity" :"1"}]');
     foreach ($line_items_decode as $item) {
         $order->add_product(get_product($item->id), $item->quantity);
     }
     if (isset($_POST['line_coupons'])) {
         $line_coupons_decode = json_decode(stripslashes($_POST['line_coupons']));
         foreach ($line_coupons_decode as $coupon) {
             $c = $order->add_coupon($coupon->code, $coupon->discount);
         }
     }
     if (isset($_POST['order_note'])) {
         $order->add_order_note($_POST['order_note']);
     }
     $order->calculate_totals();
     $order->reduce_order_stock();
     $order->update_status('processing');
     $data = array($order);
     DABBA_API_Output::get()->output(true, 200, '', $data);
 }
 /**
  * Creates a postsale order with postsale item
  *
  * @param $original_order_id
  *
  * @return WC_Order
  */
 protected function create_postsale_order($original_order_id)
 {
     $original_order = wc_get_order($original_order_id);
     $postsale_product = $this->get_postsale_item();
     $product_order_price = get_option('wc_settings_tab_luup_price') ? get_option('wc_settings_tab_luup_price') : $postsale_product->get_regular_price();
     $order_qty = 1;
     $order_total = $product_order_price * $order_qty;
     $order_args = array('status' => '', 'customer_id' => get_current_user_id(), 'customer_note' => null, 'order_id' => 0, 'created_via' => '', 'parent' => 0);
     $order = wc_create_order($order_args);
     $order->add_product($postsale_product, $order_qty);
     $order->set_address($original_order->get_address('billing'), 'billing');
     $order->set_address($original_order->get_address('shipping'), 'shipping');
     $order->set_total($order_total);
     $order->add_order_note('Upsell order');
     $order->set_payment_method($this);
     return $order;
 }
Example #16
0
function wc1c_replace_document($document)
{
    global $wpdb;
    if ($document['ХозОперация'] != "Заказ товара" || $document['Роль'] != "Продавец") {
        return;
    }
    $order = wc_get_order($document['Номер']);
    if (!$order) {
        $args = array('status' => 'on-hold', 'customer_note' => @$document['Комментарий']);
        $contragent_name = @$document['Контрагенты'][0]['Наименование'];
        if ($contragent_name == "Гость") {
            $user_id = 0;
        } elseif (strpos($contragent_name, ' ') !== false) {
            list($first_name, $last_name) = explode(' ', $contragent_name, 2);
            $result = $wpdb->get_var($wpdb->prepare("SELECT u1.user_id FROM {$wpdb->usermeta} u1 JOIN {$wpdb->usermeta} u2 ON u1.user_id = u2.user_id WHERE (u1.meta_key = 'billing_first_name' AND u1.meta_value = %s AND u2.meta_key = 'billing_last_name' AND u2.meta_value = %s) OR (u1.meta_key = 'shipping_first_name' AND u1.meta_value = %s AND u2.meta_key = 'shipping_last_name' AND u2.meta_value = %s)", $first_name, $last_name, $first_name, $last_name));
            wc1c_check_wpdb_error();
            if ($result) {
                $user_id = $result;
            }
        }
        if (isset($user_id)) {
            $args['customer_id'] = $user_id;
        }
        $order = wc_create_order($args);
        wc1c_check_wp_error($order);
        if (!isset($user_id)) {
            update_post_meta($order->id, 'wc1c_contragent', $contragent_name);
        }
        $args = array('ID' => $order->id);
        $date = @$document['Дата'];
        if ($date && !empty($document['Время'])) {
            $date .= " {$document['Время']}";
        }
        $timestamp = strtotime($date);
        $args['post_date'] = date("Y-m-d H:i:s", $timestamp);
        $result = wp_update_post($args);
        wc1c_check_wp_error($result);
        if (!$result) {
            wc1c_error("Failed to update order post");
        }
        update_post_meta($order->id, '_wc1c_guid', $document['Ид']);
    } else {
        $args = array('order_id' => $order->id, 'status' => 'on-hold');
        $is_paid = false;
        foreach ($document['ЗначенияРеквизитов'] as $requisite) {
            if (!in_array($requisite['Наименование'], array("Дата оплаты по 1С", "Дата отгрузки по 1С"))) {
                continue;
            }
            $is_paid = true;
            break;
        }
        if ($is_paid) {
            $args['status'] = 'processing';
        }
        $is_passed = false;
        foreach ($document['ЗначенияРеквизитов'] as $requisite) {
            if ($requisite['Наименование'] != 'Проведен' || $requisite['Значение'] != 'true') {
                continue;
            }
            $is_passed = true;
            break;
        }
        if ($is_passed) {
            $args['status'] = 'completed';
        }
        $order = wc_update_order($args);
        wc1c_check_wp_error($order);
    }
    $is_deleted = false;
    foreach ($document['ЗначенияРеквизитов'] as $requisite) {
        if ($requisite['Наименование'] != 'ПометкаУдаления' || $requisite['Значение'] != 'true') {
            continue;
        }
        $is_deleted = true;
        break;
    }
    if ($is_deleted && $order->post_status != 'trash') {
        wp_trash_post($order->id);
    } elseif (!$is_deleted && $order->post_status == 'trash') {
        wp_untrash_post($order->id);
    }
    $post_meta = array();
    if (isset($document['Валюта'])) {
        $post_meta['_order_currency'] = $document['Валюта'];
    }
    if (isset($document['Сумма'])) {
        $post_meta['_order_total'] = wc1c_parse_decimal($document['Сумма']);
    }
    $document_products = array();
    $document_services = array();
    foreach ($document['Товары'] as $i => $document_product) {
        foreach ($document_product['ЗначенияРеквизитов'] as $document_product_requisite) {
            if ($document_product_requisite['Наименование'] != 'ТипНоменклатуры') {
                continue;
            }
            if ($document_product_requisite['Значение'] == 'Услуга') {
                $document_services[] = $document_product;
            } else {
                $document_products[] = $document_product;
            }
            break;
        }
    }
    wc1c_replace_document_products($order, $document_products);
    $post_meta['_order_shipping'] = wc1c_replace_document_services($order, $document_services);
    $current_post_meta = get_post_meta($order->id);
    foreach ($current_post_meta as $meta_key => $meta_value) {
        $current_post_meta[$meta_key] = $meta_value[0];
    }
    foreach ($post_meta as $meta_key => $meta_value) {
        $current_meta_value = @$current_post_meta[$meta_key];
        if ($current_meta_value == $meta_value) {
            continue;
        }
        update_post_meta($order->id, $meta_key, $meta_value);
    }
}
Example #17
0
function doc_enrollment_submission($entry, $form)
{
    global $woocommerce;
    $first_name = rgar($entry, '2');
    $last_name = rgar($entry, '65');
    $gender = rgar($entry, '4');
    $dob = rgar($entry, '5');
    $phone = rgar($entry, '6');
    $phone2 = rgar($entry, '64');
    $email = rgar($entry, '7');
    $pc = rgar($entry, '8');
    $reason_for_seeking_treatment = rgar($entry, '9');
    $height = rgar($entry, '10');
    $weight = rgar($entry, '11');
    $blood_pressure = rgar($entry, '12');
    $pulse = rgar($entry, '13');
    $tobbacco = rgar($entry, '15');
    $alcohol = rgar($entry, '16');
    $caffeine = rgar($entry, '17');
    $no_allergies = rgar($entry, '19.1');
    $penicillin = rgar($entry, '19.2');
    $sulfa_drug = rgar($entry, '19.3');
    $nitrate = rgar($entry, '19.4');
    $morphine = rgar($entry, '19.5');
    $food = rgar($entry, '19.6');
    $dye_allergies = rgar($entry, '19.7');
    $seasonal = rgar($entry, '19.8');
    $pet = rgar($entry, '19.9');
    $codeine = rgar($entry, '19.11');
    //console_log('allergies= ' . rgar( $entry, '19.1' ));
    $no_otc = rgar($entry, '21.1');
    $aspirin = rgar($entry, '21.2');
    $naproxen = rgar($entry, '21.3');
    $acid_blockers = rgar($entry, '21.4');
    $ketaprofen = rgar($entry, '21.5');
    $decongestant = rgar($entry, '21.6');
    $cough = rgar($entry, '21.7');
    $laxatives = rgar($entry, '21.8');
    $antihistamines = rgar($entry, '21.9');
    $antacids = rgar($entry, '21.11');
    $ibuprofen = rgar($entry, '21.12');
    $acetaminophen = rgar($entry, '21.13');
    $sleep_aids = rgar($entry, '21.14');
    $diet_aids = rgar($entry, '21.15');
    $antidiarrheal = rgar($entry, '21.16');
    $pain_reliever = rgar($entry, '21.17');
    //console_log($otc);
    $no_conditions = rgar($entry, '23.1');
    $lung_issues = rgar($entry, '23.2');
    $hbp = rgar($entry, '23.3');
    $ulcers = rgar($entry, '23.4');
    $migraines = rgar($entry, '23.5');
    $depression = rgar($entry, '23.6');
    $hormone_related = rgar($entry, '23.7');
    $thyroid = rgar($entry, '23.8');
    $eye_disease = rgar($entry, '23.9');
    $epilepsy = rgar($entry, '23.11');
    $blood_clotting = rgar($entry, '23.12');
    $high_cholesterol = rgar($entry, '23.13');
    //console_log($conditions);
    $medications = rgar($entry, '25');
    $heart_disease = rgar($entry, '27');
    //console_log($heart_disease);
    $heart_disease_relation = rgar($entry, '28');
    $high_blood_pressure = rgar($entry, '29');
    $high_blood_pressure_relation = rgar($entry, '30');
    $diabetes = rgar($entry, '31');
    $diabetes_relation = rgar($entry, '32');
    $arthritis = rgar($entry, '33');
    $arthritis_relation = rgar($entry, '34');
    $skin_disorders = rgar($entry, '35');
    $skin_disorders_relation = rgar($entry, '36');
    $cancer = rgar($entry, '37');
    $cancer_relation = rgar($entry, '38');
    $pregnant = rgar($entry, '40');
    $last_cycle = rgar($entry, '41');
    $abnormal_cycle = rgar($entry, '42');
    $breast_cancer = rgar($entry, '43');
    $order_user = get_user_by('email', $email);
    console_log($order_user);
    $user_id = $order_user->ID;
    $items = $woocommerce->cart->get_cart();
    //console_log($items);
    $order = wc_create_order(array('customer_id' => $user_id));
    foreach ($items as $item => $values) {
        $product_ID = $values['product_id'];
        $order->add_product(get_product($values['product_id']), $values['quantity']);
        //(get_product with id and next is for quantity)
    }
    $title = get_the_title();
    $order_id = $title;
    update_post_meta($order_id, '_patient-first-name', sanitize_text_field($first_name));
    update_post_meta($order_id, '_patient-last-name', sanitize_text_field($last_name));
    update_post_meta($order_id, '_gender', sanitize_text_field($gender));
    update_post_meta($order_id, '_dob', sanitize_text_field($dob));
    update_post_meta($order_id, '_primary-phone-number', sanitize_text_field($phone));
    update_post_meta($order_id, '_addtional-phone-number', sanitize_text_field($phone2));
    update_post_meta($order_id, '_email-address', sanitize_text_field($email));
    update_post_meta($order_id, '_primary-physician', sanitize_text_field($pc));
    update_post_meta($order_id, '_reason-for-seeking-treatment', sanitize_text_field($reason_for_seeking_treatment));
    update_post_meta($order_id, '_height', sanitize_text_field($height));
    update_post_meta($order_id, '_weight', sanitize_text_field($weight));
    update_post_meta($order_id, '_bp', sanitize_text_field($blood_pressure));
    update_post_meta($order_id, '_pulse', sanitize_text_field($pulse));
    update_post_meta($order_id, '_tobbacco', sanitize_text_field($tobbacco));
    update_post_meta($order_id, '_alcohol', sanitize_text_field($alcohol));
    update_post_meta($order_id, '_caffeine', sanitize_text_field($caffeine));
    update_post_meta($order_id, '_no-allergies', sanitize_text_field($no_allergies));
    update_post_meta($order_id, '_no_otc', sanitize_text_field($no_otc));
    update_post_meta($order_id, '_aspirin', sanitize_text_field($aspirin));
    update_post_meta($order_id, '_naproxen', sanitize_text_field($naproxen));
    update_post_meta($order_id, '_acid-blockers', sanitize_text_field($acid_blockers));
    update_post_meta($order_id, '_ketaprofen', sanitize_text_field($ketaprofen));
    update_post_meta($order_id, '_decongestant', sanitize_text_field($decongestant));
    update_post_meta($order_id, '_cough-suppressant', sanitize_text_field($cough));
    update_post_meta($order_id, '_laxatives', sanitize_text_field($laxatives));
    update_post_meta($order_id, '_antihistamines', sanitize_text_field($antihistamines));
    update_post_meta($order_id, '_antacids', sanitize_text_field($antacids));
    update_post_meta($order_id, '_ibuprofen', sanitize_text_field($ibuprofen));
    update_post_meta($order_id, '_acetaminophen', sanitize_text_field($acetaminophen));
    update_post_meta($order_id, '_sleep-aids', sanitize_text_field($sleep_aids));
    update_post_meta($order_id, '_diet-aids', sanitize_text_field($diet_aids));
    update_post_meta($order_id, '_antidiarrheal', sanitize_text_field($antidiarrheal));
    update_post_meta($order_id, '_pain-reliever', sanitize_text_field($pain_reliever));
    update_post_meta($order_id, '_no-conditions', sanitize_text_field($no_conditions));
    update_post_meta($order_id, '_lung-issues', sanitize_text_field($lung_issues));
    update_post_meta($order_id, '_high-blood-pressure-condition', sanitize_text_field($hbp));
    update_post_meta($order_id, '_ulcers', sanitize_text_field($ulcers));
    update_post_meta($order_id, '_migraines', sanitize_text_field($migraines));
    update_post_meta($order_id, '_depression', sanitize_text_field($depression));
    update_post_meta($order_id, '_hormone-related', sanitize_text_field($hormone_related));
    update_post_meta($order_id, '_thyroid', sanitize_text_field($thyroid));
    update_post_meta($order_id, '_eye-disease', sanitize_text_field($eye_disease));
    update_post_meta($order_id, '_epilepsy', sanitize_text_field($epilepsy));
    update_post_meta($order_id, '_blood-clotting-issue', sanitize_text_field($blood_clotting));
    update_post_meta($order_id, '_high-cholesterol', sanitize_text_field($high_cholesterol));
    update_post_meta($order_id, '_penicillin', sanitize_text_field($penicillin));
    update_post_meta($order_id, '_sulfa-drug', sanitize_text_field($sulfa_drug));
    update_post_meta($order_id, '_nitrate', sanitize_text_field($nitrate));
    update_post_meta($order_id, '_morphine', sanitize_text_field($morphine));
    update_post_meta($order_id, '_food', sanitize_text_field($food));
    update_post_meta($order_id, '_dye-allergies', sanitize_text_field($dye_allergies));
    update_post_meta($order_id, '_seasonal', sanitize_text_field($seasonal));
    update_post_meta($order_id, '_pet', sanitize_text_field($pet));
    update_post_meta($order_id, '_codeine', sanitize_text_field($codeine));
    update_post_meta($order_id, '_medication', sanitize_text_field($medications));
    update_post_meta($order_id, '_heart-disease', sanitize_text_field($heart_disease));
    update_post_meta($order_id, '_heart-disease-relationship', sanitize_text_field($heart_disease_relation));
    update_post_meta($order_id, '_high-blood-pressure', sanitize_text_field($high_blood_pressure));
    update_post_meta($order_id, '_high-blood-pressure-relationship', sanitize_text_field($high_blood_pressure_relation));
    update_post_meta($order_id, '_diabetes', sanitize_text_field($diabetes));
    update_post_meta($order_id, '_diabetes-relationship', sanitize_text_field($diabetes_relation));
    update_post_meta($order_id, '_arthritis', sanitize_text_field($arthritis));
    update_post_meta($order_id, '_arthritis-relationship', sanitize_text_field($arthritis_relation));
    update_post_meta($order_id, '_skin-disorders', sanitize_text_field($skin_disorders));
    update_post_meta($order_id, '_skin-disorders-relationship', sanitize_text_field($skin_disorders_relation));
    update_post_meta($order_id, '_cancer', sanitize_text_field($cancer));
    update_post_meta($order_id, '_cancer-relationship', sanitize_text_field($cancer_relation));
    update_post_meta($order_id, '_are-you-currently-pregnant', sanitize_text_field($pregnant));
    update_post_meta($order_id, '_last-menstrual-cycle', sanitize_text_field($last_cycle));
    update_post_meta($order_id, '_abnormal-period-cycle', sanitize_text_field($abnormal_cycle));
    update_post_meta($order_id, '_breast_cancer', sanitize_text_field($breast_cancer));
    // Updating User Meta
    update_user_meta($user_id, 'first_name', sanitize_text_field($first_name));
    update_user_meta($user_id, 'last_name', sanitize_text_field($last_name));
    update_user_meta($user_id, '_patient-first-name', sanitize_text_field($first_name));
    update_user_meta($user_id, '_patient-last-name', sanitize_text_field($last_name));
    update_user_meta($user_id, '_gender', sanitize_text_field($gender));
    update_user_meta($user_id, '_dob', sanitize_text_field($dob));
    update_user_meta($user_id, '_primary-phone-number', sanitize_text_field($phone));
    update_user_meta($user_id, '_addtional-phone-number', sanitize_text_field($phone2));
    update_user_meta($user_id, '_email-address', sanitize_text_field($email));
    update_user_meta($user_id, '_primary-physician', sanitize_text_field($pc));
    update_user_meta($user_id, '_reason-for-seeking-treatment', sanitize_text_field($reason_for_seeking_treatment));
    update_user_meta($user_id, '_height', sanitize_text_field($height));
    update_user_meta($user_id, '_weight', sanitize_text_field($weight));
    update_user_meta($user_id, '_bp', sanitize_text_field($blood_pressure));
    update_user_meta($user_id, '_pulse', sanitize_text_field($pulse));
    update_user_meta($user_id, '_tobbacco', sanitize_text_field($tobbacco));
    update_user_meta($user_id, '_alcohol', sanitize_text_field($alcohol));
    update_user_meta($user_id, '_caffeine', sanitize_text_field($caffeine));
    update_user_meta($user_id, '_no-allergies', sanitize_text_field($no_allergies));
    update_user_meta($user_id, '_no_otc', sanitize_text_field($no_otc));
    update_user_meta($user_id, '_aspirin', sanitize_text_field($aspirin));
    update_user_meta($user_id, '_naproxen', sanitize_text_field($naproxen));
    update_user_meta($user_id, '_acid-blockers', sanitize_text_field($acid_blockers));
    update_user_meta($user_id, '_ketaprofen', sanitize_text_field($ketaprofen));
    update_user_meta($user_id, '_decongestant', sanitize_text_field($decongestant));
    update_user_meta($user_id, '_cough-suppressant', sanitize_text_field($cough));
    update_user_meta($user_id, '_laxatives', sanitize_text_field($laxatives));
    update_user_meta($user_id, '_antihistamines', sanitize_text_field($antihistamines));
    update_user_meta($user_id, '_antacids', sanitize_text_field($antacids));
    update_user_meta($user_id, '_ibuprofen', sanitize_text_field($ibuprofen));
    update_user_meta($user_id, '_acetaminophen', sanitize_text_field($acetaminophen));
    update_user_meta($user_id, '_sleep-aids', sanitize_text_field($sleep_aids));
    update_user_meta($user_id, '_diet-aids', sanitize_text_field($diet_aids));
    update_user_meta($user_id, '_antidiarrheal', sanitize_text_field($antidiarrheal));
    update_user_meta($user_id, '_pain-reliever', sanitize_text_field($pain_reliever));
    update_user_meta($user_id, '_no-conditions', sanitize_text_field($no_conditions));
    update_user_meta($user_id, '_lung-issues', sanitize_text_field($lung_issues));
    update_user_meta($user_id, '_high-blood-pressure-condition', sanitize_text_field($hbp));
    update_user_meta($user_id, '_ulcers', sanitize_text_field($ulcers));
    update_user_meta($user_id, '_migraines', sanitize_text_field($migraines));
    update_user_meta($user_id, '_depression', sanitize_text_field($depression));
    update_user_meta($user_id, '_hormone-related', sanitize_text_field($hormone_related));
    update_user_meta($user_id, '_thyroid', sanitize_text_field($thyroid));
    update_user_meta($user_id, '_eye-disease', sanitize_text_field($eye_disease));
    update_user_meta($user_id, '_epilepsy', sanitize_text_field($epilepsy));
    update_user_meta($user_id, '_blood-clotting-issue', sanitize_text_field($blood_clotting));
    update_user_meta($user_id, '_high-cholesterol', sanitize_text_field($high_cholesterol));
    update_user_meta($user_id, '_penicillin', sanitize_text_field($penicillin));
    update_user_meta($user_id, '_sulfa-drug', sanitize_text_field($sulfa_drug));
    update_user_meta($user_id, '_nitrate', sanitize_text_field($nitrate));
    update_user_meta($user_id, '_morphine', sanitize_text_field($morphine));
    update_user_meta($user_id, '_food', sanitize_text_field($food));
    update_user_meta($user_id, '_dye-allergies', sanitize_text_field($dye_allergies));
    update_user_meta($user_id, '_seasonal', sanitize_text_field($seasonal));
    update_user_meta($user_id, '_pet', sanitize_text_field($pet));
    update_user_meta($user_id, '_codeine', sanitize_text_field($codeine));
    update_user_meta($user_id, '_medication', sanitize_text_field($medications));
    update_user_meta($user_id, '_heart-disease', sanitize_text_field($heart_disease));
    update_user_meta($user_id, '_heart-disease-relationship', sanitize_text_field($heart_disease_relation));
    update_user_meta($user_id, '_high-blood-pressure', sanitize_text_field($high_blood_pressure));
    update_user_meta($user_id, '_high-blood-pressure-relationship', sanitize_text_field($high_blood_pressure_relation));
    update_user_meta($user_id, '_diabetes', sanitize_text_field($diabetes));
    update_user_meta($user_id, '_diabetes-relationship', sanitize_text_field($diabetes_relation));
    update_user_meta($user_id, '_arthritis', sanitize_text_field($arthritis));
    update_user_meta($user_id, '_arthritis-relationship', sanitize_text_field($arthritis_relation));
    update_user_meta($user_id, '_skin-disorders', sanitize_text_field($skin_disorders));
    update_user_meta($user_id, '_skin-disorders-relationship', sanitize_text_field($skin_disorders_relation));
    update_user_meta($user_id, '_cancer', sanitize_text_field($cancer));
    update_user_meta($user_id, '_cancer-relationship', sanitize_text_field($cancer_relation));
    update_user_meta($user_id, '_are-you-currently-pregnant', sanitize_text_field($pregnant));
    update_user_meta($user_id, '_last-menstrual-cycle', sanitize_text_field($last_cycle));
    update_user_meta($user_id, '_abnormal-period-cycle', sanitize_text_field($abnormal_cycle));
    update_user_meta($user_id, '_breast_cancer', sanitize_text_field($breast_cancer));
}
 /**
  * create_order function.
  * @access public
  * @throws Exception
  * @return int|WP_ERROR
  */
 public function create_order()
 {
     global $wpdb;
     // Give plugins the opportunity to create an order themselves
     if ($order_id = apply_filters('woocommerce_create_order', null, $this)) {
         return $order_id;
     }
     try {
         // Start transaction if available
         $wpdb->query('START TRANSACTION');
         $order_data = array('status' => apply_filters('woocommerce_default_order_status', 'pending'), 'customer_id' => $this->customer_id, 'customer_note' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '');
         // Insert or update the post data
         $order_id = absint(WC()->session->order_awaiting_payment);
         // Resume the unpaid order if its pending
         if ($order_id > 0 && ($order = wc_get_order($order_id)) && $order->has_status(array('pending', 'failed'))) {
             $order_data['order_id'] = $order_id;
             $order = wc_update_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order->remove_order_items();
                 do_action('woocommerce_resume_order', $order_id);
             }
         } else {
             $order = wc_create_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order_id = $order->id;
                 do_action('woocommerce_new_order', $order_id);
             }
         }
         // Store the line items to the new/resumed order
         foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
             $item_id = $order->add_product($values['data'], $values['quantity'], array('variation' => $values['variation'], 'totals' => array('subtotal' => $values['line_subtotal'], 'subtotal_tax' => $values['line_subtotal_tax'], 'total' => $values['line_total'], 'tax' => $values['line_tax'], 'tax_data' => $values['line_tax_data'])));
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // 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_key => $fee) {
             $item_id = $order->add_fee($fee);
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // Allow plugins to add order item meta to fees
             do_action('woocommerce_add_order_fee_meta', $order_id, $item_id, $fee, $fee_key);
         }
         // Store shipping for all packages
         foreach (WC()->shipping->get_packages() as $package_key => $package) {
             if (isset($package['rates'][$this->shipping_methods[$package_key]])) {
                 $item_id = $order->add_shipping($package['rates'][$this->shipping_methods[$package_key]]);
                 if (!$item_id) {
                     throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
                 }
                 // Allows plugins to add order item meta to shipping
                 do_action('woocommerce_add_shipping_order_item', $order_id, $item_id, $package_key);
             }
         }
         // Store tax rows
         foreach (array_keys(WC()->cart->taxes + WC()->cart->shipping_taxes) as $tax_rate_id) {
             if (!$order->add_tax($tax_rate_id, WC()->cart->get_tax_amount($tax_rate_id), WC()->cart->get_shipping_tax_amount($tax_rate_id)) && 'zero-rated' !== $tax_rate_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Store coupons
         foreach (WC()->cart->get_coupons() as $code => $coupon) {
             if (!$order->add_coupon($code, WC()->cart->get_coupon_discount_amount($code))) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Billing address
         $billing_address = array();
         if ($this->checkout_fields['billing']) {
             foreach (array_keys($this->checkout_fields['billing']) as $field) {
                 $field_name = str_replace('billing_', '', $field);
                 $billing_address[$field_name] = $this->get_posted_address_data($field_name);
             }
         }
         // Shipping address.
         $shipping_address = array();
         if ($this->checkout_fields['shipping']) {
             foreach (array_keys($this->checkout_fields['shipping']) as $field) {
                 $field_name = str_replace('shipping_', '', $field);
                 $shipping_address[$field_name] = $this->get_posted_address_data($field_name, 'shipping');
             }
         }
         $order->set_address($billing_address, 'billing');
         $order->set_address($shipping_address, 'shipping');
         $order->set_payment_method($this->payment_method);
         $order->set_total(WC()->cart->shipping_total, 'shipping');
         $order->set_total(WC()->cart->get_order_discount_total(), 'order_discount');
         $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
         $order->set_total(WC()->cart->tax_total, 'tax');
         $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
         $order->set_total(WC()->cart->total);
         // Update user meta
         if ($this->customer_id) {
             if (apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                 foreach ($billing_address as $key => $value) {
                     update_user_meta($this->customer_id, 'billing_' . $key, $value);
                 }
                 foreach ($shipping_address as $key => $value) {
                     update_user_meta($this->customer_id, 'shipping_' . $key, $value);
                 }
             }
             do_action('woocommerce_checkout_update_user_meta', $this->customer_id, $this->posted);
         }
         // Let plugins add meta
         do_action('woocommerce_checkout_update_order_meta', $order_id, $this->posted);
         // If we got here, the order was created without problems!
         $wpdb->query('COMMIT');
     } catch (Exception $e) {
         // There was an error adding order data!
         $wpdb->query('ROLLBACK');
         return new WP_Error('checkout-error', $e->getMessage());
     }
     return $order_id;
 }
function dvin_qlist_create_order($data)
{
    global $dvin_qlist_products, $dvin_wcql_settings;
    if (class_exists('Product_Addon_Cart')) {
        $addon_cart_obj = new Product_Addon_Cart();
        //create object for addons
    }
    $address = array();
    //stores the billing and shipping info for creating order
    $billing_address = dvin_wcql_map_address($data, '');
    $shipping_address = dvin_wcql_map_address($data, 'ship_');
    $order = wc_create_order();
    foreach ($dvin_qlist_products as $key => $arr) {
        if (!isset($arr['variation_id']) && !isset($arr['product_id'])) {
            continue;
        }
        //simple or variable
        if (isset($arr['variation_id']) && !empty($arr['variation_id'])) {
            $product_obj = wc_get_product($arr['variation_id']);
            if (isset($arr['price'])) {
                $product_obj->set_price($arr['price']);
            }
            $item_id = $order->add_product($product_obj, $arr['quantity'], array('variation' => unserialize($arr['variation_data'])));
        } else {
            $product_obj = wc_get_product($arr['product_id']);
            $item_id = $order->add_product($product_obj, $arr['quantity']);
            //(get_product with id and next is for quantity)
        }
        // Allow plugins to add order item meta
        if (isset($addon_cart_obj) && $addon_cart_obj instanceof Product_Addon_Cart) {
            //to avoid/prevent notices
            $arr['data'] = array();
            $addon_cart_obj->order_item_meta($item_id, $arr);
        }
    }
    //end of foreach
    $order->set_address($billing_address, 'billing');
    $order->set_address($shipping_address, 'shipping');
    $order->calculate_totals();
    //update the customer data
    update_post_meta($order->id, '_customer_user', absint(get_current_user_id()));
    //update the order status to pending
    $order = new WC_Order($order->id);
    $order->update_status('pending');
    return $order->id;
}
Example #20
0
/**
 * Update an order. Uses wc_create_order.
 * @param  array $args
 * @return string | WC_Order
 */
function wc_update_order($args)
{
    if (!$args['order_id']) {
        return new WP_Error(__('Invalid order ID', 'woocommerce'));
    }
    return wc_create_order($args);
}
 /**
  * Create base WC Order object.
  *
  * @param array $data
  * @return WC_Order
  */
 protected function create_base_order($data)
 {
     return wc_create_order($data);
 }
Example #22
0
 public function pwa_order()
 {
     global $wp, $wpdb;
     global $order, $pwa_order_status, $pwa_order_id;
     global $woocommerce;
     $pwa_order_id = @$wp->query_vars['amznPmtsOrderIds'];
     $pwa_order_status = @$wp->query_vars['amznPmtsPaymentStatus'];
     if (isset($pwa_order_id) && $pwa_order_id != '') {
         $order_postmeta = $wpdb->get_results("select post_id from {$wpdb->postmeta} where meta_key = '_pwa_order_id' and meta_value = '{$pwa_order_id}' ");
         if (empty($order_postmeta)) {
             $order = wc_create_order();
             $order_id = $order->id;
             add_post_meta($order->id, '_pwa_order_id', $pwa_order_id);
             add_post_meta($order->id, '_payment_method', 'pwa');
             add_post_meta($order->id, '_payment_method_title', 'Pay with Amazon');
             $woocommerce->cart->empty_cart();
         } else {
             $order_id = $order_postmeta[0]->post_id;
             $order = new WC_Order($order_id);
             $woocommerce->cart->empty_cart();
         }
         //$url = 'www.inlifehealthcare.com/checkout?orderType=pwa&orderId='.$order_id.'&amznPmtsOrderIds='.$pwa_order_id.'&amznPmtsPaymentStatus='.$pwa_order_status.'';
         //echo '<script>window.location.href = "'.$url.'" </script>';
         //header('Location:'.$url);
         include PWA_TEMPLATE_DIR . 'pwa_order.php';
         exit;
     } else {
         include PWA_TEMPLATE_DIR . 'pwa_order_error.php';
         exit;
     }
 }
 function create_order()
 {
     global $woocommerce, $wp;
     // Security check
     check_ajax_referer('ajax_post_validation', 'security');
     //Getting Product ID
     $id = $_POST['prod_id'];
     // create order
     $address = array('first_name' => 'Iskandariya', 'last_name' => 'Solutions', 'company' => 'Iskandariya.Solutions', 'phone' => '+91-9999999999', 'address_1' => 'Chandigarh', 'address_2' => 'Mohali,Punjab', 'city' => 'Chandigarh', 'state' => 'PB', 'postcode' => '160001', 'country' => 'IN');
     $order_data = array('customer_id' => get_current_user_id());
     $order = wc_create_order($order_data);
     $order->add_product(get_product($id), 1);
     //(get_product with id and next is for quantity)
     $order->set_address($address, 'billing');
     $order->set_address($address, 'shipping');
     $order->calculate_totals();
     wp_die();
 }
 /**
  * Create a scheduled order
  * @param  string $payment_date
  * @param  int $original_order_id
  */
 public static function create_order($payment_date, $original_order_id, $payment_number, $item, $status = '')
 {
     $original_order = wc_get_order($original_order_id);
     $new_order = wc_create_order(array('status' => $status, 'customer_id' => $original_order->get_user_id(), 'customer_note' => $original_order->customer_note, 'created_via' => 'wc_deposits'));
     if (is_wp_error($new_order)) {
         $original_order->add_order_note(sprintf(__('Error: Unable to create follow up payment (%s)', 'woocommerce-deposits'), $scheduled_order->get_error_message()));
     } else {
         $new_order->set_address(array('first_name' => $original_order->billing_first_name, 'last_name' => $original_order->billing_last_name, 'company' => $original_order->billing_company, 'address_1' => $original_order->billing_address_1, 'address_2' => $original_order->billing_address_2, 'city' => $original_order->billing_city, 'state' => $original_order->billing_state, 'postcode' => $original_order->billing_postcode, 'country' => $original_order->billing_country, 'email' => $original_order->billing_email, 'phone' => $original_order->billing_phone), 'billing');
         $new_order->set_address(array('first_name' => $original_order->shipping_first_name, 'last_name' => $original_order->shipping_last_name, 'company' => $original_order->shipping_company, 'address_1' => $original_order->shipping_address_1, 'address_2' => $original_order->shipping_address_2, 'city' => $original_order->shipping_city, 'state' => $original_order->shipping_state, 'postcode' => $original_order->shipping_postcode, 'country' => $original_order->shipping_country), 'shipping');
         // Handle items
         $item_id = $new_order->add_product($item['product'], $item['qty'], array('totals' => array('subtotal' => $item['amount'], 'total' => $item['amount'], 'subtotal_tax' => 0, 'tax' => 0)));
         woocommerce_add_order_item_meta($item_id, '_original_order_id', $original_order_id);
         wc_update_order_item($item_id, array('order_item_name' => sprintf(__('Payment #%d for %s'), $payment_number, $item['product']->get_title())));
         $new_order->calculate_totals(wc_tax_enabled());
         // Set future date and parent
         $new_order_post = array('ID' => $new_order->id, 'post_date' => date('Y-m-d H:i:s', $payment_date), 'post_parent' => $original_order_id);
         wp_update_post($new_order_post);
         do_action('woocommerce_deposits_create_order', $new_order->id);
         return $new_order->id;
     }
 }
 /**
  * Create an order. Error codes:
  * 		520 - Cannot insert order into the database.
  * 		521 - Cannot get order after creation.
  * 		522 - Cannot update order.
  * 		525 - Cannot create line item.
  * 		526 - Cannot create fee item.
  * 		527 - Cannot create shipping item.
  * 		528 - Cannot create tax item.
  * 		529 - Cannot create coupon item.
  * @access public
  * @throws Exception
  * @return int|WP_ERROR
  */
 public function create_order()
 {
     global $wpdb;
     // Give plugins the opportunity to create an order themselves
     if ($order_id = apply_filters('woocommerce_create_order', null, $this)) {
         return $order_id;
     }
     try {
         // Start transaction if available
         wc_transaction_query('start');
         $order_data = array('status' => apply_filters('woocommerce_default_order_status', 'pending'), 'customer_id' => $this->customer_id, 'customer_note' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '', 'cart_hash' => md5(json_encode(WC()->cart->get_cart_for_session()) . WC()->cart->total), 'created_via' => 'checkout');
         // Insert or update the post data
         $order_id = absint(WC()->session->order_awaiting_payment);
         /**
          * If there is an order pending payment, we can resume it here so
          * long as it has not changed. If the order has changed, i.e.
          * different items or cost, create a new order. We use a hash to
          * detect changes which is based on cart items + order total.
          */
         if ($order_id && $order_data['cart_hash'] === get_post_meta($order_id, '_cart_hash', true) && ($order = wc_get_order($order_id)) && $order->has_status(array('pending', 'failed'))) {
             $order_data['order_id'] = $order_id;
             $order = wc_update_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 522));
             } else {
                 $order->remove_order_items();
                 do_action('woocommerce_resume_order', $order_id);
             }
         } else {
             $order = wc_create_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 520));
             } elseif (false === $order) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 521));
             } else {
                 $order_id = $order->id;
                 do_action('woocommerce_new_order', $order_id);
             }
         }
         // Store the line items to the new/resumed order
         foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
             $item_id = $order->add_product($values['data'], $values['quantity'], array('variation' => $values['variation'], 'totals' => array('subtotal' => $values['line_subtotal'], 'subtotal_tax' => $values['line_subtotal_tax'], 'total' => $values['line_total'], 'tax' => $values['line_tax'], 'tax_data' => $values['line_tax_data'])));
             if (!$item_id) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 525));
             }
             // 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_key => $fee) {
             $item_id = $order->add_fee($fee);
             if (!$item_id) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 526));
             }
             // Allow plugins to add order item meta to fees
             do_action('woocommerce_add_order_fee_meta', $order_id, $item_id, $fee, $fee_key);
         }
         // Store shipping for all packages
         foreach (WC()->shipping->get_packages() as $package_key => $package) {
             if (isset($package['rates'][$this->shipping_methods[$package_key]])) {
                 $item_id = $order->add_shipping($package['rates'][$this->shipping_methods[$package_key]]);
                 if (!$item_id) {
                     throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 527));
                 }
                 // Allows plugins to add order item meta to shipping
                 do_action('woocommerce_add_shipping_order_item', $order_id, $item_id, $package_key);
             }
         }
         // Store tax rows
         foreach (array_keys(WC()->cart->taxes + WC()->cart->shipping_taxes) as $tax_rate_id) {
             if ($tax_rate_id && !$order->add_tax($tax_rate_id, WC()->cart->get_tax_amount($tax_rate_id), WC()->cart->get_shipping_tax_amount($tax_rate_id)) && apply_filters('woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated') !== $tax_rate_id) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 528));
             }
         }
         // Store coupons
         foreach (WC()->cart->get_coupons() as $code => $coupon) {
             if (!$order->add_coupon($code, WC()->cart->get_coupon_discount_amount($code), WC()->cart->get_coupon_discount_tax_amount($code))) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 529));
             }
         }
         // Billing address
         $billing_address = array();
         if ($this->checkout_fields['billing']) {
             foreach (array_keys($this->checkout_fields['billing']) as $field) {
                 $field_name = str_replace('billing_', '', $field);
                 $billing_address[$field_name] = $this->get_posted_address_data($field_name);
             }
         }
         // Shipping address.
         $shipping_address = array();
         if ($this->checkout_fields['shipping']) {
             foreach (array_keys($this->checkout_fields['shipping']) as $field) {
                 $field_name = str_replace('shipping_', '', $field);
                 $shipping_address[$field_name] = $this->get_posted_address_data($field_name, 'shipping');
             }
         }
         $order->set_address($billing_address, 'billing');
         $order->set_address($shipping_address, 'shipping');
         $order->set_payment_method($this->payment_method);
         $order->set_total(WC()->cart->shipping_total, 'shipping');
         $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
         $order->set_total(WC()->cart->get_cart_discount_tax_total(), 'cart_discount_tax');
         $order->set_total(WC()->cart->tax_total, 'tax');
         $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
         $order->set_total(WC()->cart->total);
         // Update user meta
         if ($this->customer_id) {
             if (apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                 foreach ($billing_address as $key => $value) {
                     update_user_meta($this->customer_id, 'billing_' . $key, $value);
                 }
                 if (WC()->cart->needs_shipping()) {
                     foreach ($shipping_address as $key => $value) {
                         update_user_meta($this->customer_id, 'shipping_' . $key, $value);
                     }
                 }
             }
             do_action('woocommerce_checkout_update_user_meta', $this->customer_id, $this->posted);
         }
         // Let plugins add meta
         do_action('woocommerce_checkout_update_order_meta', $order_id, $this->posted);
         // If we got here, the order was created without problems!
         wc_transaction_query('commit');
     } catch (Exception $e) {
         // There was an error adding order data!
         wc_transaction_query('rollback');
         return new WP_Error('checkout-error', $e->getMessage());
     }
     return $order_id;
 }
 /**
  * Creates new WC_Order.
  *
  * @since  2.5.0
  * @param  $args array
  * @return WC_Order
  */
 protected function create_base_order($args)
 {
     return wc_create_order($args);
 }
\Ebanx\Config::set(array('integrationKey' => $ebanx->merchant_key, 'testMode' => $ebanx->test_mode, 'directMode' => true));
$data = date('d');
try {
    $conn = new PDO("mysql:host={$servername};dbname={$database}", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // echo "Connected successfully 2\n";
    $sql = "SELECT * FROM ebanx_token WHERE DATE_FORMAT(data,'%d') = {$data}";
    //$sql = "SELECT * FROM ebanx_token";
    $result = $conn->query($sql);
    //$result = $result->fetch (PDO::FETCH_ASSOC);
    while ($data = $result->fetch(PDO::FETCH_ASSOC)) {
        $args = array('status' => '', 'customer_id' => $data['customer_id'], 'customer_note' => '', 'created_via' => 'EBANX Recurring cron', 'order_id' => 0);
        $order = new WC_Order($data['order_id']);
        $streetNumber = isset($order->billing_number) ? $order->billing_number : '1';
        $newOrder = wc_create_order($args);
        update_post_meta($newOrder->id, '_order_total', $order->order_total);
        $params = array('mode' => 'full', 'operation' => 'request', 'payment' => array('merchant_payment_code' => $newOrder->id, 'order_number' => $newOrder->id, 'amount_total' => $order->order_total, 'currency_code' => $data['currency_code'], 'name' => $order->billing_first_name . ' ' . $order->billing_last_name, 'email' => $order->billing_email, 'birth_date' => $data['birth_date'], 'address' => $order->billing_address_1, 'street_number' => $streetNumber, 'city' => $order->billing_city, 'state' => $order->billing_state, 'zipcode' => $order->billing_postcode, 'country' => $order->billing_country, 'phone_number' => $order->billing_phone, 'payment_type_code' => $data['payment_type_code'], 'document' => $order->billing_cpf, 'creditcard' => array('token' => $data['token'])));
        $response = \Ebanx\Ebanx::doRequest($params);
        if (isset($response->status) && $response->status == 'SUCCESS') {
            if ($response->payment->status == 'CA') {
                $newOrder->add_order_note('Payment failed.');
                $newOrder->cancel_order();
                echo "OK: Payment {$response->hash} was cancelled via IPN\n";
            }
            if ($response->payment->status == 'CO') {
                $newOrder->add_order_note('Payment confirmed.');
                $newOrder->update_status('completed');
                echo "OK: Payment {$response->hash} was confirmed via IPN\n";
            }
        }
 /**
  * Create order.
  *
  * @param WP_REST_Request $request Full details about the request.
  * @return int|WP_Error
  */
 protected function create_order($request)
 {
     wc_transaction_query('start');
     try {
         // Make sure customer exists.
         if (0 !== $request['customer_id'] && false === get_user_by('id', $request['customer_id'])) {
             throw new WC_REST_Exception('woocommerce_rest_invalid_customer_id', __('Customer ID is invalid.', 'woocommerce'), 400);
         }
         $order = wc_create_order(array('status' => $request['status'], 'customer_id' => $request['customer_id'], 'customer_note' => $request['customer_note'], 'created_via' => 'rest-api'));
         if (is_wp_error($order)) {
             throw new WC_REST_Exception('woocommerce_rest_cannot_create_order', sprintf(__('Cannot create order: %s.', 'woocommerce'), implode(', ', $order->get_error_messages())), 400);
         }
         // Set addresses.
         if (is_array($request['billing'])) {
             $this->update_address($order, $request['billing'], 'billing');
         }
         if (is_array($request['shipping'])) {
             $this->update_address($order, $request['shipping'], 'shipping');
         }
         // Set currency.
         update_post_meta($order->id, '_order_currency', $request['currency']);
         // Set lines.
         $lines = array('line_item' => 'line_items', 'shipping' => 'shipping_lines', 'fee' => 'fee_lines', 'coupon' => 'coupon_lines');
         foreach ($lines as $line_type => $line) {
             if (is_array($request[$line])) {
                 foreach ($request[$line] as $item) {
                     $set_item = 'set_' . $line_type;
                     $new_item = $this->{$set_item}($order, $item, 'create');
                 }
             }
         }
         // Calculate totals and set them.
         $order->calculate_totals();
         // Set payment method.
         if (!empty($request['payment_method'])) {
             update_post_meta($order->id, '_payment_method', $request['payment_method']);
         }
         if (!empty($request['payment_method_title'])) {
             update_post_meta($order->id, '_payment_method_title', $request['payment_method']);
         }
         if (true === $request['set_paid']) {
             $order->payment_complete($request['transaction_id']);
         }
         // Set meta data.
         if (!empty($request['meta_data']) && is_array($request['meta_data'])) {
             $this->update_meta_data($order->id, $request['meta_data']);
         }
         wc_transaction_query('commit');
         return $order->id;
     } catch (WC_REST_Exception $e) {
         wc_transaction_query('rollback');
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }
 public static function createSimpleOrder($total = 40)
 {
     $product = self::createSimpleProduct();
     self::createSimpleShippingFlatRate();
     $order_data = array('status' => 'pending', 'customer_id' => 1, 'customer_note' => '', 'total' => '');
     // Required, else wc_create_order throws an exception
     $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
     $order = wc_create_order($order_data);
     // Add order products
     $order->add_product($product, 4);
     // Set billing address
     $shipping_address = array('country' => 'US', 'first_name' => 'Jeroen', 'last_name' => 'Sormani', 'company' => 'WooCompany', 'address_1' => 'WooAddress', 'address_2' => '', 'postcode' => '123456', 'city' => 'WooCity', 'state' => 'NY', 'email' => '*****@*****.**', 'phone' => '555-32123');
     $order->set_address($shipping_address, 'shipping');
     // Add shipping costs
     $shipping_taxes = \WC_Tax::calc_shipping_tax('10', \WC_Tax::get_shipping_tax_rates());
     $order->add_shipping(new \WC_Shipping_Rate('flagship_shipping_method|Purolator|PurolatorExpress|Purolator Express|1473811200', 'Purolator - Purolator Express', '10', $shipping_taxes, 'flagship_shipping_method'));
     // Set totals
     $order->set_total(10, 'shipping');
     $order->set_total(0, 'cart_discount');
     $order->set_total(0, 'cart_discount_tax');
     $order->set_total(0, 'tax');
     $order->set_total(0, 'shipping_tax');
     $order->set_total($total, 'total');
     // 4 x $10 simple helper product
     return wc_get_order($order->id);
 }