PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/woocommerce/includes/api/class-wc-api-orders.php

https://gitlab.com/webkod3r/tripolis
PHP | 1558 lines | 900 code | 322 blank | 336 comment | 171 complexity | 9477f8006472cb89f9e0ca5661ba402b MD5 | raw file
  1. <?php
  2. /**
  3. * WooCommerce API Orders Class
  4. *
  5. * Handles requests to the /orders endpoint
  6. *
  7. * @author WooThemes
  8. * @category API
  9. * @package WooCommerce/API
  10. * @since 2.1
  11. */
  12. if ( ! defined( 'ABSPATH' ) ) {
  13. exit; // Exit if accessed directly
  14. }
  15. class WC_API_Orders extends WC_API_Resource {
  16. /** @var string $base the route base */
  17. protected $base = '/orders';
  18. /** @var string $post_type the custom post type */
  19. protected $post_type = 'shop_order';
  20. /**
  21. * Register the routes for this class
  22. *
  23. * GET|POST /orders
  24. * GET /orders/count
  25. * GET|PUT|DELETE /orders/<id>
  26. * GET /orders/<id>/notes
  27. *
  28. * @since 2.1
  29. * @param array $routes
  30. * @return array
  31. */
  32. public function register_routes( $routes ) {
  33. # GET|POST /orders
  34. $routes[ $this->base ] = array(
  35. array( array( $this, 'get_orders' ), WC_API_Server::READABLE ),
  36. array( array( $this, 'create_order' ), WC_API_Server::CREATABLE | WC_API_Server::ACCEPT_DATA ),
  37. );
  38. # GET /orders/count
  39. $routes[ $this->base . '/count' ] = array(
  40. array( array( $this, 'get_orders_count' ), WC_API_Server::READABLE ),
  41. );
  42. # GET /orders/statuses
  43. $routes[ $this->base . '/statuses' ] = array(
  44. array( array( $this, 'get_order_statuses' ), WC_API_Server::READABLE ),
  45. );
  46. # GET|PUT|DELETE /orders/<id>
  47. $routes[ $this->base . '/(?P<id>\d+)' ] = array(
  48. array( array( $this, 'get_order' ), WC_API_Server::READABLE ),
  49. array( array( $this, 'edit_order' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  50. array( array( $this, 'delete_order' ), WC_API_Server::DELETABLE ),
  51. );
  52. # GET|POST /orders/<id>/notes
  53. $routes[ $this->base . '/(?P<order_id>\d+)/notes' ] = array(
  54. array( array( $this, 'get_order_notes' ), WC_API_Server::READABLE ),
  55. array( array( $this, 'create_order_note' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),
  56. );
  57. # GET|PUT|DELETE /orders/<order_id>/notes/<id>
  58. $routes[ $this->base . '/(?P<order_id>\d+)/notes/(?P<id>\d+)' ] = array(
  59. array( array( $this, 'get_order_note' ), WC_API_Server::READABLE ),
  60. array( array( $this, 'edit_order_note' ), WC_API_SERVER::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  61. array( array( $this, 'delete_order_note' ), WC_API_SERVER::DELETABLE ),
  62. );
  63. # GET|POST /orders/<order_id>/refunds
  64. $routes[ $this->base . '/(?P<order_id>\d+)/refunds' ] = array(
  65. array( array( $this, 'get_order_refunds' ), WC_API_Server::READABLE ),
  66. array( array( $this, 'create_order_refund' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),
  67. );
  68. # GET|PUT|DELETE /orders/<order_id>/refunds/<id>
  69. $routes[ $this->base . '/(?P<order_id>\d+)/refunds/(?P<id>\d+)' ] = array(
  70. array( array( $this, 'get_order_refund' ), WC_API_Server::READABLE ),
  71. array( array( $this, 'edit_order_refund' ), WC_API_SERVER::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  72. array( array( $this, 'delete_order_refund' ), WC_API_SERVER::DELETABLE ),
  73. );
  74. # POST|PUT /orders/bulk
  75. $routes[ $this->base . '/bulk' ] = array(
  76. array( array( $this, 'bulk' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  77. );
  78. return $routes;
  79. }
  80. /**
  81. * Get all orders
  82. *
  83. * @since 2.1
  84. * @param string $fields
  85. * @param array $filter
  86. * @param string $status
  87. * @param int $page
  88. * @return array
  89. */
  90. public function get_orders( $fields = null, $filter = array(), $status = null, $page = 1 ) {
  91. if ( ! empty( $status ) ) {
  92. $filter['status'] = $status;
  93. }
  94. $filter['page'] = $page;
  95. $query = $this->query_orders( $filter );
  96. $orders = array();
  97. foreach ( $query->posts as $order_id ) {
  98. if ( ! $this->is_readable( $order_id ) ) {
  99. continue;
  100. }
  101. $orders[] = current( $this->get_order( $order_id, $fields, $filter ) );
  102. }
  103. $this->server->add_pagination_headers( $query );
  104. return array( 'orders' => $orders );
  105. }
  106. /**
  107. * Get the order for the given ID.
  108. *
  109. * @since 2.1
  110. * @param int $id The order ID.
  111. * @param array $fields Request fields.
  112. * @param array $filter Request filters.
  113. * @return array
  114. */
  115. public function get_order( $id, $fields = null, $filter = array() ) {
  116. // Ensure order ID is valid & user has permission to read.
  117. $id = $this->validate_request( $id, $this->post_type, 'read' );
  118. if ( is_wp_error( $id ) ) {
  119. return $id;
  120. }
  121. // Get the decimal precession.
  122. $dp = ( isset( $filter['dp'] ) ? intval( $filter['dp'] ) : 2 );
  123. $order = wc_get_order( $id );
  124. $order_post = get_post( $id );
  125. $expand = array();
  126. if ( ! empty( $filter['expand'] ) ) {
  127. $expand = explode( ',', $filter['expand'] );
  128. }
  129. $order_data = array(
  130. 'id' => $order->id,
  131. 'order_number' => $order->get_order_number(),
  132. 'order_key' => $order->order_key,
  133. 'created_at' => $this->server->format_datetime( $order_post->post_date_gmt ),
  134. 'updated_at' => $this->server->format_datetime( $order_post->post_modified_gmt ),
  135. 'completed_at' => $this->server->format_datetime( $order->completed_date, true ),
  136. 'status' => $order->get_status(),
  137. 'currency' => $order->get_order_currency(),
  138. 'total' => wc_format_decimal( $order->get_total(), $dp ),
  139. 'subtotal' => wc_format_decimal( $order->get_subtotal(), $dp ),
  140. 'total_line_items_quantity' => $order->get_item_count(),
  141. 'total_tax' => wc_format_decimal( $order->get_total_tax(), $dp ),
  142. 'total_shipping' => wc_format_decimal( $order->get_total_shipping(), $dp ),
  143. 'cart_tax' => wc_format_decimal( $order->get_cart_tax(), $dp ),
  144. 'shipping_tax' => wc_format_decimal( $order->get_shipping_tax(), $dp ),
  145. 'total_discount' => wc_format_decimal( $order->get_total_discount(), $dp ),
  146. 'shipping_methods' => $order->get_shipping_method(),
  147. 'payment_details' => array(
  148. 'method_id' => $order->payment_method,
  149. 'method_title' => $order->payment_method_title,
  150. 'paid' => isset( $order->paid_date ),
  151. ),
  152. 'billing_address' => array(
  153. 'first_name' => $order->billing_first_name,
  154. 'last_name' => $order->billing_last_name,
  155. 'company' => $order->billing_company,
  156. 'address_1' => $order->billing_address_1,
  157. 'address_2' => $order->billing_address_2,
  158. 'city' => $order->billing_city,
  159. 'state' => $order->billing_state,
  160. 'postcode' => $order->billing_postcode,
  161. 'country' => $order->billing_country,
  162. 'email' => $order->billing_email,
  163. 'phone' => $order->billing_phone,
  164. ),
  165. 'shipping_address' => array(
  166. 'first_name' => $order->shipping_first_name,
  167. 'last_name' => $order->shipping_last_name,
  168. 'company' => $order->shipping_company,
  169. 'address_1' => $order->shipping_address_1,
  170. 'address_2' => $order->shipping_address_2,
  171. 'city' => $order->shipping_city,
  172. 'state' => $order->shipping_state,
  173. 'postcode' => $order->shipping_postcode,
  174. 'country' => $order->shipping_country,
  175. ),
  176. 'note' => $order->customer_note,
  177. 'customer_ip' => $order->customer_ip_address,
  178. 'customer_user_agent' => $order->customer_user_agent,
  179. 'customer_id' => $order->get_user_id(),
  180. 'view_order_url' => $order->get_view_order_url(),
  181. 'line_items' => array(),
  182. 'shipping_lines' => array(),
  183. 'tax_lines' => array(),
  184. 'fee_lines' => array(),
  185. 'coupon_lines' => array(),
  186. );
  187. // Add line items.
  188. foreach ( $order->get_items() as $item_id => $item ) {
  189. $product = $order->get_product_from_item( $item );
  190. $product_id = null;
  191. $product_sku = null;
  192. // Check if the product exists.
  193. if ( is_object( $product ) ) {
  194. $product_id = ( isset( $product->variation_id ) ) ? $product->variation_id : $product->id;
  195. $product_sku = $product->get_sku();
  196. }
  197. $meta = new WC_Order_Item_Meta( $item, $product );
  198. $item_meta = array();
  199. $hideprefix = ( isset( $filter['all_item_meta'] ) && 'true' === $filter['all_item_meta'] ) ? null : '_';
  200. foreach ( $meta->get_formatted( $hideprefix ) as $meta_key => $formatted_meta ) {
  201. $item_meta[] = array(
  202. 'key' => $formatted_meta['key'],
  203. 'label' => $formatted_meta['label'],
  204. 'value' => $formatted_meta['value'],
  205. );
  206. }
  207. $line_item = array(
  208. 'id' => $item_id,
  209. 'subtotal' => wc_format_decimal( $order->get_line_subtotal( $item, false, false ), $dp ),
  210. 'subtotal_tax' => wc_format_decimal( $item['line_subtotal_tax'], $dp ),
  211. 'total' => wc_format_decimal( $order->get_line_total( $item, false, false ), $dp ),
  212. 'total_tax' => wc_format_decimal( $item['line_tax'], $dp ),
  213. 'price' => wc_format_decimal( $order->get_item_total( $item, false, false ), $dp ),
  214. 'quantity' => wc_stock_amount( $item['qty'] ),
  215. 'tax_class' => ( ! empty( $item['tax_class'] ) ) ? $item['tax_class'] : null,
  216. 'name' => $item['name'],
  217. 'product_id' => $product_id,
  218. 'sku' => $product_sku,
  219. 'meta' => $item_meta,
  220. );
  221. if ( in_array( 'products', $expand ) ) {
  222. $_product_data = WC()->api->WC_API_Products->get_product( $product_id );
  223. if ( isset( $_product_data['product'] ) ) {
  224. $line_item['product_data'] = $_product_data['product'];
  225. }
  226. }
  227. $order_data['line_items'][] = $line_item;
  228. }
  229. // Add shipping.
  230. foreach ( $order->get_shipping_methods() as $shipping_item_id => $shipping_item ) {
  231. $order_data['shipping_lines'][] = array(
  232. 'id' => $shipping_item_id,
  233. 'method_id' => $shipping_item['method_id'],
  234. 'method_title' => $shipping_item['name'],
  235. 'total' => wc_format_decimal( $shipping_item['cost'], $dp ),
  236. );
  237. }
  238. // Add taxes.
  239. foreach ( $order->get_tax_totals() as $tax_code => $tax ) {
  240. $tax_line = array(
  241. 'id' => $tax->id,
  242. 'rate_id' => $tax->rate_id,
  243. 'code' => $tax_code,
  244. 'title' => $tax->label,
  245. 'total' => wc_format_decimal( $tax->amount, $dp ),
  246. 'compound' => (bool) $tax->is_compound,
  247. );
  248. if ( in_array( 'taxes', $expand ) ) {
  249. $_rate_data = WC()->api->WC_API_Taxes->get_tax( $tax->rate_id );
  250. if ( isset( $_rate_data['tax'] ) ) {
  251. $tax_line['rate_data'] = $_rate_data['tax'];
  252. }
  253. }
  254. $order_data['tax_lines'][] = $tax_line;
  255. }
  256. // Add fees.
  257. foreach ( $order->get_fees() as $fee_item_id => $fee_item ) {
  258. $order_data['fee_lines'][] = array(
  259. 'id' => $fee_item_id,
  260. 'title' => $fee_item['name'],
  261. 'tax_class' => ( ! empty( $fee_item['tax_class'] ) ) ? $fee_item['tax_class'] : null,
  262. 'total' => wc_format_decimal( $order->get_line_total( $fee_item ), $dp ),
  263. 'total_tax' => wc_format_decimal( $order->get_line_tax( $fee_item ), $dp ),
  264. );
  265. }
  266. // Add coupons.
  267. foreach ( $order->get_items( 'coupon' ) as $coupon_item_id => $coupon_item ) {
  268. $coupon_line = array(
  269. 'id' => $coupon_item_id,
  270. 'code' => $coupon_item['name'],
  271. 'amount' => wc_format_decimal( $coupon_item['discount_amount'], $dp ),
  272. );
  273. if ( in_array( 'coupons', $expand ) ) {
  274. $_coupon_data = WC()->api->WC_API_Coupons->get_coupon_by_code( $coupon_item['name'] );
  275. if ( isset( $_coupon_data['coupon'] ) ) {
  276. $coupon_line['coupon_data'] = $_coupon_data['coupon'];
  277. }
  278. }
  279. $order_data['coupon_lines'][] = $coupon_line;
  280. }
  281. return array( 'order' => apply_filters( 'woocommerce_api_order_response', $order_data, $order, $fields, $this->server ) );
  282. }
  283. /**
  284. * Get the total number of orders
  285. *
  286. * @since 2.4
  287. * @param string $status
  288. * @param array $filter
  289. * @return array
  290. */
  291. public function get_orders_count( $status = null, $filter = array() ) {
  292. try {
  293. if ( ! current_user_can( 'read_private_shop_orders' ) ) {
  294. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_orders_count', __( 'You do not have permission to read the orders count', 'woocommerce' ), 401 );
  295. }
  296. if ( ! empty( $status ) ) {
  297. if ( $status == 'any' ) {
  298. $order_statuses = array();
  299. foreach ( wc_get_order_statuses() as $slug => $name ) {
  300. $filter['status'] = str_replace( 'wc-', '', $slug );
  301. $query = $this->query_orders( $filter );
  302. $order_statuses[ str_replace( 'wc-', '', $slug ) ] = (int) $query->found_posts;
  303. }
  304. return array( 'count' => $order_statuses );
  305. } else {
  306. $filter['status'] = $status;
  307. }
  308. }
  309. $query = $this->query_orders( $filter );
  310. return array( 'count' => (int) $query->found_posts );
  311. } catch ( WC_API_Exception $e ) {
  312. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  313. }
  314. }
  315. /**
  316. * Get a list of valid order statuses
  317. *
  318. * Note this requires no specific permissions other than being an authenticated
  319. * API user. Order statuses (particularly custom statuses) could be considered
  320. * private information which is why it's not in the API index.
  321. *
  322. * @since 2.1
  323. * @return array
  324. */
  325. public function get_order_statuses() {
  326. $order_statuses = array();
  327. foreach ( wc_get_order_statuses() as $slug => $name ) {
  328. $order_statuses[ str_replace( 'wc-', '', $slug ) ] = $name;
  329. }
  330. return array( 'order_statuses' => apply_filters( 'woocommerce_api_order_statuses_response', $order_statuses, $this ) );
  331. }
  332. /**
  333. * Create an order
  334. *
  335. * @since 2.2
  336. * @param array $data raw order data
  337. * @return array
  338. */
  339. public function create_order( $data ) {
  340. global $wpdb;
  341. wc_transaction_query( 'start' );
  342. try {
  343. if ( ! isset( $data['order'] ) ) {
  344. throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order' ), 400 );
  345. }
  346. $data = $data['order'];
  347. // permission check
  348. if ( ! current_user_can( 'publish_shop_orders' ) ) {
  349. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order', __( 'You do not have permission to create orders', 'woocommerce' ), 401 );
  350. }
  351. $data = apply_filters( 'woocommerce_api_create_order_data', $data, $this );
  352. // default order args, note that status is checked for validity in wc_create_order()
  353. $default_order_args = array(
  354. 'status' => isset( $data['status'] ) ? $data['status'] : '',
  355. 'customer_note' => isset( $data['note'] ) ? $data['note'] : null,
  356. );
  357. // if creating order for existing customer
  358. if ( ! empty( $data['customer_id'] ) ) {
  359. // make sure customer exists
  360. if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
  361. throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid', 'woocommerce' ), 400 );
  362. }
  363. $default_order_args['customer_id'] = $data['customer_id'];
  364. }
  365. // create the pending order
  366. $order = $this->create_base_order( $default_order_args, $data );
  367. if ( is_wp_error( $order ) ) {
  368. throw new WC_API_Exception( 'woocommerce_api_cannot_create_order', sprintf( __( 'Cannot create order: %s', 'woocommerce' ), implode( ', ', $order->get_error_messages() ) ), 400 );
  369. }
  370. // billing/shipping addresses
  371. $this->set_order_addresses( $order, $data );
  372. $lines = array(
  373. 'line_item' => 'line_items',
  374. 'shipping' => 'shipping_lines',
  375. 'fee' => 'fee_lines',
  376. 'coupon' => 'coupon_lines',
  377. );
  378. foreach ( $lines as $line_type => $line ) {
  379. if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
  380. $set_item = "set_{$line_type}";
  381. foreach ( $data[ $line ] as $item ) {
  382. $this->$set_item( $order, $item, 'create' );
  383. }
  384. }
  385. }
  386. // calculate totals and set them
  387. $order->calculate_totals();
  388. // payment method (and payment_complete() if `paid` == true)
  389. if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
  390. // method ID & title are required
  391. if ( empty( $data['payment_details']['method_id'] ) || empty( $data['payment_details']['method_title'] ) ) {
  392. throw new WC_API_Exception( 'woocommerce_invalid_payment_details', __( 'Payment method ID and title are required', 'woocommerce' ), 400 );
  393. }
  394. update_post_meta( $order->id, '_payment_method', $data['payment_details']['method_id'] );
  395. update_post_meta( $order->id, '_payment_method_title', $data['payment_details']['method_title'] );
  396. // mark as paid if set
  397. if ( isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
  398. $order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
  399. }
  400. }
  401. // set order currency
  402. if ( isset( $data['currency'] ) ) {
  403. if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
  404. throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid', 'woocommerce'), 400 );
  405. }
  406. update_post_meta( $order->id, '_order_currency', $data['currency'] );
  407. }
  408. // set order meta
  409. if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
  410. $this->set_order_meta( $order->id, $data['order_meta'] );
  411. }
  412. // HTTP 201 Created
  413. $this->server->send_status( 201 );
  414. wc_delete_shop_order_transients( $order->id );
  415. do_action( 'woocommerce_api_create_order', $order->id, $data, $this );
  416. wc_transaction_query( 'commit' );
  417. return $this->get_order( $order->id );
  418. } catch ( WC_API_Exception $e ) {
  419. wc_transaction_query( 'rollback' );
  420. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  421. }
  422. }
  423. /**
  424. * Creates new WC_Order.
  425. *
  426. * Requires a separate function for classes that extend WC_API_Orders.
  427. *
  428. * @since 2.3
  429. * @param $args array
  430. * @return WC_Order
  431. */
  432. protected function create_base_order( $args, $data ) {
  433. return wc_create_order( $args );
  434. }
  435. /**
  436. * Edit an order
  437. *
  438. * @since 2.2
  439. * @param int $id the order ID
  440. * @param array $data
  441. * @return array
  442. */
  443. public function edit_order( $id, $data ) {
  444. try {
  445. if ( ! isset( $data['order'] ) ) {
  446. throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order' ), 400 );
  447. }
  448. $data = $data['order'];
  449. $update_totals = false;
  450. $id = $this->validate_request( $id, $this->post_type, 'edit' );
  451. if ( is_wp_error( $id ) ) {
  452. return $id;
  453. }
  454. $data = apply_filters( 'woocommerce_api_edit_order_data', $data, $id, $this );
  455. $order = wc_get_order( $id );
  456. if ( empty( $order ) ) {
  457. throw new WC_API_Exception( 'woocommerce_api_invalid_order_id', __( 'Order ID is invalid', 'woocommerce' ), 400 );
  458. }
  459. $order_args = array( 'order_id' => $order->id );
  460. // Customer note.
  461. if ( isset( $data['note'] ) ) {
  462. $order_args['customer_note'] = $data['note'];
  463. }
  464. // Customer ID.
  465. if ( isset( $data['customer_id'] ) && $data['customer_id'] != $order->get_user_id() ) {
  466. // Make sure customer exists.
  467. if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
  468. throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid', 'woocommerce' ), 400 );
  469. }
  470. update_post_meta( $order->id, '_customer_user', $data['customer_id'] );
  471. }
  472. // Billing/shipping address.
  473. $this->set_order_addresses( $order, $data );
  474. $lines = array(
  475. 'line_item' => 'line_items',
  476. 'shipping' => 'shipping_lines',
  477. 'fee' => 'fee_lines',
  478. 'coupon' => 'coupon_lines',
  479. );
  480. foreach ( $lines as $line_type => $line ) {
  481. if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
  482. $update_totals = true;
  483. foreach ( $data[ $line ] as $item ) {
  484. // Item ID is always required.
  485. if ( ! array_key_exists( 'id', $item ) ) {
  486. throw new WC_API_Exception( 'woocommerce_invalid_item_id', __( 'Order item ID is required', 'woocommerce' ), 400 );
  487. }
  488. // Create item.
  489. if ( is_null( $item['id'] ) ) {
  490. $this->set_item( $order, $line_type, $item, 'create' );
  491. } elseif ( $this->item_is_null( $item ) ) {
  492. // Delete item.
  493. wc_delete_order_item( $item['id'] );
  494. } else {
  495. // Update item.
  496. $this->set_item( $order, $line_type, $item, 'update' );
  497. }
  498. }
  499. }
  500. }
  501. // Payment method (and payment_complete() if `paid` == true and order needs payment).
  502. if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
  503. // Method ID.
  504. if ( isset( $data['payment_details']['method_id'] ) ) {
  505. update_post_meta( $order->id, '_payment_method', $data['payment_details']['method_id'] );
  506. }
  507. // Method title.
  508. if ( isset( $data['payment_details']['method_title'] ) ) {
  509. update_post_meta( $order->id, '_payment_method_title', $data['payment_details']['method_title'] );
  510. }
  511. // Mark as paid if set.
  512. if ( $order->needs_payment() && isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
  513. $order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
  514. }
  515. }
  516. // Set order currency.
  517. if ( isset( $data['currency'] ) ) {
  518. if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
  519. throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid', 'woocommerce' ), 400 );
  520. }
  521. update_post_meta( $order->id, '_order_currency', $data['currency'] );
  522. }
  523. // If items have changed, recalculate order totals.
  524. if ( $update_totals ) {
  525. $order->calculate_totals();
  526. }
  527. // Update order meta.
  528. if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
  529. $this->set_order_meta( $order->id, $data['order_meta'] );
  530. }
  531. // Update the order post to set customer note/modified date.
  532. wc_update_order( $order_args );
  533. // Order status.
  534. if ( ! empty( $data['status'] ) ) {
  535. $order->update_status( $data['status'], isset( $data['status_note'] ) ? $data['status_note'] : '' );
  536. }
  537. wc_delete_shop_order_transients( $order->id );
  538. do_action( 'woocommerce_api_edit_order', $order->id, $data, $this );
  539. return $this->get_order( $id );
  540. } catch ( WC_API_Exception $e ) {
  541. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  542. }
  543. }
  544. /**
  545. * Delete an order
  546. *
  547. * @param int $id the order ID
  548. * @param bool $force true to permanently delete order, false to move to trash
  549. * @return array
  550. */
  551. public function delete_order( $id, $force = false ) {
  552. $id = $this->validate_request( $id, $this->post_type, 'delete' );
  553. if ( is_wp_error( $id ) ) {
  554. return $id;
  555. }
  556. wc_delete_shop_order_transients( $id );
  557. do_action( 'woocommerce_api_delete_order', $id, $this );
  558. return $this->delete( $id, 'order', ( 'true' === $force ) );
  559. }
  560. /**
  561. * Helper method to get order post objects
  562. *
  563. * @since 2.1
  564. * @param array $args request arguments for filtering query
  565. * @return WP_Query
  566. */
  567. protected function query_orders( $args ) {
  568. // set base query arguments
  569. $query_args = array(
  570. 'fields' => 'ids',
  571. 'post_type' => $this->post_type,
  572. 'post_status' => array_keys( wc_get_order_statuses() )
  573. );
  574. // add status argument
  575. if ( ! empty( $args['status'] ) ) {
  576. $statuses = 'wc-' . str_replace( ',', ',wc-', $args['status'] );
  577. $statuses = explode( ',', $statuses );
  578. $query_args['post_status'] = $statuses;
  579. unset( $args['status'] );
  580. }
  581. if ( ! empty( $args['customer_id'] ) ) {
  582. $query_args['meta_query'] = array(
  583. array(
  584. 'key' => '_customer_user',
  585. 'value' => absint( $args['customer_id'] ),
  586. 'compare' => '='
  587. )
  588. );
  589. }
  590. $query_args = $this->merge_query_args( $query_args, $args );
  591. return new WP_Query( $query_args );
  592. }
  593. /**
  594. * Helper method to set/update the billing & shipping addresses for
  595. * an order
  596. *
  597. * @since 2.1
  598. * @param \WC_Order $order
  599. * @param array $data
  600. */
  601. protected function set_order_addresses( $order, $data ) {
  602. $address_fields = array(
  603. 'first_name',
  604. 'last_name',
  605. 'company',
  606. 'email',
  607. 'phone',
  608. 'address_1',
  609. 'address_2',
  610. 'city',
  611. 'state',
  612. 'postcode',
  613. 'country',
  614. );
  615. $billing_address = $shipping_address = array();
  616. // billing address
  617. if ( isset( $data['billing_address'] ) && is_array( $data['billing_address'] ) ) {
  618. foreach ( $address_fields as $field ) {
  619. if ( isset( $data['billing_address'][ $field ] ) ) {
  620. $billing_address[ $field ] = wc_clean( $data['billing_address'][ $field ] );
  621. }
  622. }
  623. unset( $address_fields['email'] );
  624. unset( $address_fields['phone'] );
  625. }
  626. // shipping address
  627. if ( isset( $data['shipping_address'] ) && is_array( $data['shipping_address'] ) ) {
  628. foreach ( $address_fields as $field ) {
  629. if ( isset( $data['shipping_address'][ $field ] ) ) {
  630. $shipping_address[ $field ] = wc_clean( $data['shipping_address'][ $field ] );
  631. }
  632. }
  633. }
  634. $order->set_address( $billing_address, 'billing' );
  635. $order->set_address( $shipping_address, 'shipping' );
  636. // update user meta
  637. if ( $order->get_user_id() ) {
  638. foreach ( $billing_address as $key => $value ) {
  639. update_user_meta( $order->get_user_id(), 'billing_' . $key, $value );
  640. }
  641. foreach ( $shipping_address as $key => $value ) {
  642. update_user_meta( $order->get_user_id(), 'shipping_' . $key, $value );
  643. }
  644. }
  645. }
  646. /**
  647. * Helper method to add/update order meta, with two restrictions:
  648. *
  649. * 1) Only non-protected meta (no leading underscore) can be set
  650. * 2) Meta values must be scalar (int, string, bool)
  651. *
  652. * @since 2.2
  653. * @param int $order_id valid order ID
  654. * @param array $order_meta order meta in array( 'meta_key' => 'meta_value' ) format
  655. */
  656. protected function set_order_meta( $order_id, $order_meta ) {
  657. foreach ( $order_meta as $meta_key => $meta_value ) {
  658. if ( is_string( $meta_key) && ! is_protected_meta( $meta_key ) && is_scalar( $meta_value ) ) {
  659. update_post_meta( $order_id, $meta_key, $meta_value );
  660. }
  661. }
  662. }
  663. /**
  664. * Helper method to check if the resource ID associated with the provided item is null
  665. *
  666. * Items can be deleted by setting the resource ID to null
  667. *
  668. * @since 2.2
  669. * @param array $item item provided in the request body
  670. * @return bool true if the item resource ID is null, false otherwise
  671. */
  672. protected function item_is_null( $item ) {
  673. $keys = array( 'product_id', 'method_id', 'title', 'code' );
  674. foreach ( $keys as $key ) {
  675. if ( array_key_exists( $key, $item ) && is_null( $item[ $key ] ) ) {
  676. return true;
  677. }
  678. }
  679. return false;
  680. }
  681. /**
  682. * Wrapper method to create/update order items
  683. *
  684. * When updating, the item ID provided is checked to ensure it is associated
  685. * with the order.
  686. *
  687. * @since 2.2
  688. * @param \WC_Order $order order
  689. * @param string $item_type
  690. * @param array $item item provided in the request body
  691. * @param string $action either 'create' or 'update'
  692. * @throws WC_API_Exception if item ID is not associated with order
  693. */
  694. protected function set_item( $order, $item_type, $item, $action ) {
  695. global $wpdb;
  696. $set_method = "set_{$item_type}";
  697. // verify provided line item ID is associated with order
  698. if ( 'update' === $action ) {
  699. $result = $wpdb->get_row(
  700. $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_id = %d AND order_id = %d",
  701. absint( $item['id'] ),
  702. absint( $order->id )
  703. ) );
  704. if ( is_null( $result ) ) {
  705. throw new WC_API_Exception( 'woocommerce_invalid_item_id', __( 'Order item ID provided is not associated with order', 'woocommerce' ), 400 );
  706. }
  707. }
  708. $this->$set_method( $order, $item, $action );
  709. }
  710. /**
  711. * Create or update a line item
  712. *
  713. * @since 2.2
  714. * @param \WC_Order $order
  715. * @param array $item line item data
  716. * @param string $action 'create' to add line item or 'update' to update it
  717. * @throws WC_API_Exception invalid data, server error
  718. */
  719. protected function set_line_item( $order, $item, $action ) {
  720. $creating = ( 'create' === $action );
  721. $item_args = array();
  722. // product is always required
  723. if ( ! isset( $item['product_id'] ) && ! isset( $item['sku'] ) ) {
  724. throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID or SKU is required', 'woocommerce' ), 400 );
  725. }
  726. // when updating, ensure product ID provided matches
  727. if ( 'update' === $action ) {
  728. $item_product_id = wc_get_order_item_meta( $item['id'], '_product_id' );
  729. $item_variation_id = wc_get_order_item_meta( $item['id'], '_variation_id' );
  730. if ( $item['product_id'] != $item_product_id && $item['product_id'] != $item_variation_id ) {
  731. throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID provided does not match this line item', 'woocommerce' ), 400 );
  732. }
  733. }
  734. if ( isset( $item['product_id'] ) ) {
  735. $product_id = $item['product_id'];
  736. } elseif ( isset( $item['sku'] ) ) {
  737. $product_id = wc_get_product_id_by_sku( $item['sku'] );
  738. }
  739. // variations must each have a key & value
  740. $variation_id = 0;
  741. if ( isset( $item['variations'] ) && is_array( $item['variations'] ) ) {
  742. foreach ( $item['variations'] as $key => $value ) {
  743. if ( ! $key || ! $value ) {
  744. throw new WC_API_Exception( 'woocommerce_api_invalid_product_variation', __( 'The product variation is invalid', 'woocommerce' ), 400 );
  745. }
  746. }
  747. $item_args['variation'] = $item['variations'];
  748. $variation_id = $this->get_variation_id( wc_get_product( $product_id ), $item_args['variation'] );
  749. }
  750. $product = wc_get_product( $variation_id ? $variation_id : $product_id );
  751. // must be a valid WC_Product
  752. if ( ! is_object( $product ) ) {
  753. throw new WC_API_Exception( 'woocommerce_api_invalid_product', __( 'Product is invalid', 'woocommerce' ), 400 );
  754. }
  755. // quantity must be positive float
  756. if ( isset( $item['quantity'] ) && floatval( $item['quantity'] ) <= 0 ) {
  757. throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity must be a positive float', 'woocommerce' ), 400 );
  758. }
  759. // quantity is required when creating
  760. if ( $creating && ! isset( $item['quantity'] ) ) {
  761. throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity is required', 'woocommerce' ), 400 );
  762. }
  763. // quantity
  764. if ( isset( $item['quantity'] ) ) {
  765. $item_args['qty'] = $item['quantity'];
  766. }
  767. // total
  768. if ( isset( $item['total'] ) ) {
  769. $item_args['totals']['total'] = floatval( $item['total'] );
  770. }
  771. // total tax
  772. if ( isset( $item['total_tax'] ) ) {
  773. $item_args['totals']['tax'] = floatval( $item['total_tax'] );
  774. }
  775. // subtotal
  776. if ( isset( $item['subtotal'] ) ) {
  777. $item_args['totals']['subtotal'] = floatval( $item['subtotal'] );
  778. }
  779. // subtotal tax
  780. if ( isset( $item['subtotal_tax'] ) ) {
  781. $item_args['totals']['subtotal_tax'] = floatval( $item['subtotal_tax'] );
  782. }
  783. if ( $creating ) {
  784. $item_id = $order->add_product( $product, $item_args['qty'], $item_args );
  785. if ( ! $item_id ) {
  786. throw new WC_API_Exception( 'woocommerce_cannot_create_line_item', __( 'Cannot create line item, try again', 'woocommerce' ), 500 );
  787. }
  788. } else {
  789. $item_id = $order->update_product( $item['id'], $product, $item_args );
  790. if ( ! $item_id ) {
  791. throw new WC_API_Exception( 'woocommerce_cannot_update_line_item', __( 'Cannot update line item, try again', 'woocommerce' ), 500 );
  792. }
  793. }
  794. }
  795. /**
  796. * Given a product ID & API provided variations, find the correct variation ID to use for calculation
  797. * We can't just trust input from the API to pass a variation_id manually, otherwise you could pass
  798. * the cheapest variation ID but provide other information so we have to look up the variation ID.
  799. *
  800. * @param WC_Product $product Product instance
  801. * @return int Returns an ID if a valid variation was found for this product
  802. */
  803. public function get_variation_id( $product, $variations = array() ) {
  804. $variation_id = null;
  805. $variations_normalized = array();
  806. if ( $product->is_type( 'variable' ) && $product->has_child() ) {
  807. if ( isset( $variations ) && is_array( $variations ) ) {
  808. // start by normalizing the passed variations
  809. foreach ( $variations as $key => $value ) {
  810. $key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) ); // from get_attributes in class-wc-api-products.php
  811. $variations_normalized[ $key ] = strtolower( $value );
  812. }
  813. // now search through each product child and see if our passed variations match anything
  814. foreach ( $product->get_children() as $variation ) {
  815. $meta = array();
  816. foreach ( get_post_meta( $variation ) as $key => $value ) {
  817. $value = $value[0];
  818. $key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) );
  819. $meta[ $key ] = strtolower( $value );
  820. }
  821. // if the variation array is a part of the $meta array, we found our match
  822. if ( $this->array_contains( $variations_normalized, $meta ) ) {
  823. $variation_id = $variation;
  824. break;
  825. }
  826. }
  827. }
  828. }
  829. return $variation_id;
  830. }
  831. /**
  832. * Utility function to see if the meta array contains data from variations
  833. */
  834. protected function array_contains( $needles, $haystack ) {
  835. foreach ( $needles as $key => $value ) {
  836. if ( $haystack[ $key ] !== $value ) {
  837. return false;
  838. }
  839. }
  840. return true;
  841. }
  842. /**
  843. * Create or update an order shipping method
  844. *
  845. * @since 2.2
  846. * @param \WC_Order $order
  847. * @param array $shipping item data
  848. * @param string $action 'create' to add shipping or 'update' to update it
  849. * @throws WC_API_Exception invalid data, server error
  850. */
  851. protected function set_shipping( $order, $shipping, $action ) {
  852. // total must be a positive float
  853. if ( isset( $shipping['total'] ) && floatval( $shipping['total'] ) < 0 ) {
  854. throw new WC_API_Exception( 'woocommerce_invalid_shipping_total', __( 'Shipping total must be a positive amount', 'woocommerce' ), 400 );
  855. }
  856. if ( 'create' === $action ) {
  857. // method ID is required
  858. if ( ! isset( $shipping['method_id'] ) ) {
  859. throw new WC_API_Exception( 'woocommerce_invalid_shipping_item', __( 'Shipping method ID is required', 'woocommerce' ), 400 );
  860. }
  861. $rate = new WC_Shipping_Rate( $shipping['method_id'], isset( $shipping['method_title'] ) ? $shipping['method_title'] : '', isset( $shipping['total'] ) ? floatval( $shipping['total'] ) : 0, array(), $shipping['method_id'] );
  862. $shipping_id = $order->add_shipping( $rate );
  863. if ( ! $shipping_id ) {
  864. throw new WC_API_Exception( 'woocommerce_cannot_create_shipping', __( 'Cannot create shipping method, try again', 'woocommerce' ), 500 );
  865. }
  866. } else {
  867. $shipping_args = array();
  868. if ( isset( $shipping['method_id'] ) ) {
  869. $shipping_args['method_id'] = $shipping['method_id'];
  870. }
  871. if ( isset( $shipping['method_title'] ) ) {
  872. $shipping_args['method_title'] = $shipping['method_title'];
  873. }
  874. if ( isset( $shipping['total'] ) ) {
  875. $shipping_args['cost'] = floatval( $shipping['total'] );
  876. }
  877. $shipping_id = $order->update_shipping( $shipping['id'], $shipping_args );
  878. if ( ! $shipping_id ) {
  879. throw new WC_API_Exception( 'woocommerce_cannot_update_shipping', __( 'Cannot update shipping method, try again', 'woocommerce' ), 500 );
  880. }
  881. }
  882. }
  883. /**
  884. * Create or update an order fee
  885. *
  886. * @since 2.2
  887. * @param \WC_Order $order
  888. * @param array $fee item data
  889. * @param string $action 'create' to add fee or 'update' to update it
  890. * @throws WC_API_Exception invalid data, server error
  891. */
  892. protected function set_fee( $order, $fee, $action ) {
  893. if ( 'create' === $action ) {
  894. // fee title is required
  895. if ( ! isset( $fee['title'] ) ) {
  896. throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee title is required', 'woocommerce' ), 400 );
  897. }
  898. $order_fee = new stdClass();
  899. $order_fee->id = sanitize_title( $fee['title'] );
  900. $order_fee->name = $fee['title'];
  901. $order_fee->amount = isset( $fee['total'] ) ? floatval( $fee['total'] ) : 0;
  902. $order_fee->taxable = false;
  903. $order_fee->tax = 0;
  904. $order_fee->tax_data = array();
  905. $order_fee->tax_class = '';
  906. // if taxable, tax class and total are required
  907. if ( isset( $fee['taxable'] ) && $fee['taxable'] ) {
  908. if ( ! isset( $fee['tax_class'] ) ) {
  909. throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee tax class is required when fee is taxable', 'woocommerce' ), 400 );
  910. }
  911. $order_fee->taxable = true;
  912. $order_fee->tax_class = $fee['tax_class'];
  913. if ( isset( $fee['total_tax'] ) ) {
  914. $order_fee->tax = isset( $fee['total_tax'] ) ? wc_format_refund_total( $fee['total_tax'] ) : 0;
  915. }
  916. if ( isset( $fee['tax_data'] ) ) {
  917. $order_fee->tax = wc_format_refund_total( array_sum( $fee['tax_data'] ) );
  918. $order_fee->tax_data = array_map( 'wc_format_refund_total', $fee['tax_data'] );
  919. }
  920. }
  921. $fee_id = $order->add_fee( $order_fee );
  922. if ( ! $fee_id ) {
  923. throw new WC_API_Exception( 'woocommerce_cannot_create_fee', __( 'Cannot create fee, try again', 'woocommerce' ), 500 );
  924. }
  925. } else {
  926. $fee_args = array();
  927. if ( isset( $fee['title'] ) ) {
  928. $fee_args['name'] = $fee['title'];
  929. }
  930. if ( isset( $fee['tax_class'] ) ) {
  931. $fee_args['tax_class'] = $fee['tax_class'];
  932. }
  933. if ( isset( $fee['total'] ) ) {
  934. $fee_args['line_total'] = floatval( $fee['total'] );
  935. }
  936. if ( isset( $fee['total_tax'] ) ) {
  937. $fee_args['line_tax'] = floatval( $fee['total_tax'] );
  938. }
  939. $fee_id = $order->update_fee( $fee['id'], $fee_args );
  940. if ( ! $fee_id ) {
  941. throw new WC_API_Exception( 'woocommerce_cannot_update_fee', __( 'Cannot update fee, try again', 'woocommerce' ), 500 );
  942. }
  943. }
  944. }
  945. /**
  946. * Create or update an order coupon
  947. *
  948. * @since 2.2
  949. * @param \WC_Order $order
  950. * @param array $coupon item data
  951. * @param string $action 'create' to add coupon or 'update' to update it
  952. * @throws WC_API_Exception invalid data, server error
  953. */
  954. protected function set_coupon( $order, $coupon, $action ) {
  955. // coupon amount must be positive float
  956. if ( isset( $coupon['amount'] ) && floatval( $coupon['amount'] ) < 0 ) {
  957. throw new WC_API_Exception( 'woocommerce_invalid_coupon_total', __( 'Coupon discount total must be a positive amount', 'woocommerce' ), 400 );
  958. }
  959. if ( 'create' === $action ) {
  960. // coupon code is required
  961. if ( empty( $coupon['code'] ) ) {
  962. throw new WC_API_Exception( 'woocommerce_invalid_coupon_coupon', __( 'Coupon code is required', 'woocommerce' ), 400 );
  963. }
  964. $coupon_id = $order->add_coupon( $coupon['code'], isset( $coupon['amount'] ) ? floatval( $coupon['amount'] ) : 0 );
  965. if ( ! $coupon_id ) {
  966. throw new WC_API_Exception( 'woocommerce_cannot_create_order_coupon', __( 'Cannot create coupon, try again', 'woocommerce' ), 500 );
  967. }
  968. } else {
  969. $coupon_args = array();
  970. if ( isset( $coupon['code'] ) ) {
  971. $coupon_args['code'] = $coupon['code'];
  972. }
  973. if ( isset( $coupon['amount'] ) ) {
  974. $coupon_args['discount_amount'] = floatval( $coupon['amount'] );
  975. }
  976. $coupon_id = $order->update_coupon( $coupon['id'], $coupon_args );
  977. if ( ! $coupon_id ) {
  978. throw new WC_API_Exception( 'woocommerce_cannot_update_order_coupon', __( 'Cannot update coupon, try again', 'woocommerce' ), 500 );
  979. }
  980. }
  981. }
  982. /**
  983. * Get the admin order notes for an order
  984. *
  985. * @since 2.1
  986. * @param string $order_id order ID
  987. * @param string|null $fields fields to include in response
  988. * @return array
  989. */
  990. public function get_order_notes( $order_id, $fields = null ) {
  991. // ensure ID is valid order ID
  992. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  993. if ( is_wp_error( $order_id ) ) {
  994. return $order_id;
  995. }
  996. $args = array(
  997. 'post_id' => $order_id,
  998. 'approve' => 'approve',
  999. 'type' => 'order_note'
  1000. );
  1001. remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  1002. $notes = get_comments( $args );
  1003. add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  1004. $order_notes = array();
  1005. foreach ( $notes as $note ) {
  1006. $order_notes[] = current( $this->get_order_note( $order_id, $note->comment_ID, $fields ) );
  1007. }
  1008. return array( 'order_notes' => apply_filters( 'woocommerce_api_order_notes_response', $order_notes, $order_id, $fields, $notes, $this->server ) );
  1009. }
  1010. /**
  1011. * Get an order note for the given order ID and ID
  1012. *
  1013. * @since 2.2
  1014. * @param string $order_id order ID
  1015. * @param string $id order note ID
  1016. * @param string|null $fields fields to limit response to
  1017. * @return array
  1018. */
  1019. public function get_order_note( $order_id, $id, $fields = null ) {
  1020. try {
  1021. // Validate order ID
  1022. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1023. if ( is_wp_error( $order_id ) ) {
  1024. return $order_id;
  1025. }
  1026. $id = absint( $id );
  1027. if ( empty( $id ) ) {
  1028. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1029. }
  1030. $note = get_comment( $id );
  1031. if ( is_null( $note ) ) {
  1032. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1033. }
  1034. $order_note = array(
  1035. 'id' => $note->comment_ID,
  1036. 'created_at' => $this->server->format_datetime( $note->comment_date_gmt ),
  1037. 'note' => $note->comment_content,
  1038. 'customer_note' => get_comment_meta( $note->comment_ID, 'is_customer_note', true ) ? true : false,
  1039. );
  1040. return array( 'order_note' => apply_filters( 'woocommerce_api_order_note_response', $order_note, $id, $fields, $note, $order_id, $this ) );
  1041. } catch ( WC_API_Exception $e ) {
  1042. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1043. }
  1044. }
  1045. /**
  1046. * Create a new order note for the given order
  1047. *
  1048. * @since 2.2
  1049. * @param string $order_id order ID
  1050. * @param array $data raw request data
  1051. * @return WP_Error|array error or created note response data
  1052. */
  1053. public function create_order_note( $order_id, $data ) {
  1054. try {
  1055. if ( ! isset( $data['order_note'] ) ) {
  1056. throw new WC_API_Exception( 'woocommerce_api_missing_order_note_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order_note' ), 400 );
  1057. }
  1058. $data = $data['order_note'];
  1059. // permission check
  1060. if ( ! current_user_can( 'publish_shop_orders' ) ) {
  1061. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order_note', __( 'You do not have permission to create order notes', 'woocommerce' ), 401 );
  1062. }
  1063. $order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
  1064. if ( is_wp_error( $order_id ) ) {
  1065. return $order_id;
  1066. }
  1067. $order = wc_get_order( $order_id );
  1068. $data = apply_filters( 'woocommerce_api_create_order_note_data', $data, $order_id, $this );
  1069. // note content is required
  1070. if ( ! isset( $data['note'] ) ) {
  1071. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note', __( 'Order note is required', 'woocommerce' ), 400 );
  1072. }
  1073. $is_customer_note = ( isset( $data['customer_note'] ) && true === $data['customer_note'] );
  1074. // create the note
  1075. $note_id = $order->add_order_note( $data['note'], $is_customer_note );
  1076. if ( ! $note_id ) {
  1077. throw new WC_API_Exception( 'woocommerce_api_cannot_create_order_note', __( 'Cannot create order note, please try again', 'woocommerce' ), 500 );
  1078. }
  1079. // HTTP 201 Created
  1080. $this->server->send_status( 201 );
  1081. do_action( 'woocommerce_api_create_order_note', $note_id, $order_id, $this );
  1082. return $this->get_order_note( $order->id, $note_id );
  1083. } catch ( WC_API_Exception $e ) {
  1084. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1085. }
  1086. }
  1087. /**
  1088. * Edit the order note
  1089. *
  1090. * @since 2.2
  1091. * @param string $order_id order ID
  1092. * @param string $id note ID
  1093. * @param array $data parsed request data
  1094. * @return WP_Error|array error or edited note response data
  1095. */
  1096. public function edit_order_note( $order_id, $id, $data ) {
  1097. try {
  1098. if ( ! isset( $data['order_note'] ) ) {
  1099. throw new WC_API_Exception( 'woocommerce_api_missing_order_note_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order_note' ), 400 );
  1100. }
  1101. $data = $data['order_note'];
  1102. // Validate order ID
  1103. $order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
  1104. if ( is_wp_error( $order_id ) ) {
  1105. return $order_id;
  1106. }
  1107. $order = wc_get_order( $order_id );
  1108. // Validate note ID
  1109. $id = absint( $id );
  1110. if ( empty( $id ) ) {
  1111. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1112. }
  1113. // Ensure note ID is valid
  1114. $note = get_comment( $id );
  1115. if ( is_null( $note ) ) {
  1116. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1117. }
  1118. // Ensure note ID is associated with given order
  1119. if ( $note->comment_post_ID != $order->id ) {
  1120. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
  1121. }
  1122. $data = apply_filters( 'woocommerce_api_edit_order_note_data', $data, $note->comment_ID, $order->id, $this );
  1123. // Note content
  1124. if ( isset( $data['note'] ) ) {
  1125. wp_update_comment(
  1126. array(
  1127. 'comment_ID' => $note->comment_ID,
  1128. 'comment_content' => $data['note'],
  1129. )
  1130. );
  1131. }
  1132. // Customer note
  1133. if ( isset( $data['customer_note'] ) ) {
  1134. update_comment_meta( $note->comment_ID, 'is_customer_note', true === $data['customer_note'] ? 1 : 0 );
  1135. }
  1136. do_action( 'woocommerce_api_edit_order_note', $note->comment_ID, $order->id, $this );
  1137. return $this->get_order_note( $order->id, $note->comment_ID );
  1138. } catch ( WC_API_Exception $e ) {
  1139. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1140. }
  1141. }
  1142. /**
  1143. * Delete order note
  1144. *
  1145. * @since 2.2
  1146. * @param string $order_id order ID
  1147. * @param string $id note ID
  1148. * @return WP_Error|array error or deleted message
  1149. */
  1150. public function delete_order_note( $order_id, $id ) {
  1151. try {
  1152. $order_id = $this->validate_request( $order_id, $this->post_type, 'delete' );
  1153. if ( is_wp_error( $order_id ) ) {
  1154. return $order_id;
  1155. }
  1156. // Validate note ID
  1157. $id = absint( $id );
  1158. if ( empty( $id ) ) {
  1159. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1160. }
  1161. // Ensure note ID is valid
  1162. $note = get_comment( $id );
  1163. if ( is_null( $note ) ) {
  1164. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1165. }
  1166. // Ensure note ID is associated with given order
  1167. if ( $note->comment_post_ID != $order_id ) {
  1168. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
  1169. }
  1170. // Force delete since trashed order notes could not be managed through comments list table
  1171. $result = wp_delete_comment( $note->comment_ID, true );
  1172. if ( ! $result ) {
  1173. throw new WC_API_Exception( 'woocommerce_api_cannot_delete_order_note', __( 'This order note cannot be deleted', 'woocommerce' ), 500 );
  1174. }
  1175. do_action( 'woocommerce_api_delete_order_note', $note->comment_ID, $order_id, $this );
  1176. return array( 'message' => __( 'Permanently deleted order note', 'woocommerce' ) );
  1177. } catch ( WC_API_Exception $e ) {
  1178. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1179. }
  1180. }
  1181. /**
  1182. * Get the order refunds for an order
  1183. *
  1184. * @since 2.2
  1185. * @param string $order_id order ID
  1186. * @param string|null $fields fields to include in response
  1187. * @return array
  1188. */
  1189. public function get_order_refunds( $order_id, $fields = null ) {
  1190. // Ensure ID is valid order ID
  1191. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1192. if ( is_wp_error( $order_id ) ) {
  1193. return $order_id;
  1194. }
  1195. $refund_items = get_posts(
  1196. array(
  1197. 'post_type' => 'shop_order_refund',
  1198. 'post_parent' => $order_id,
  1199. 'posts_per_page' => -1,
  1200. 'post_status' => 'any',
  1201. 'fields' => 'ids'
  1202. )
  1203. );
  1204. $order_refunds = array();
  1205. foreach ( $refund_items as $refund_id ) {
  1206. $order_refunds[] = current( $this->get_order_refund( $order_id, $refund_id, $fields ) );
  1207. }
  1208. return array( 'order_refunds' => apply_filters( 'woocommerce_api_order_refunds_response', $order_refunds, $order_id, $fields, $refund_items, $this ) );
  1209. }
  1210. /**
  1211. * Get an order refund for the given order ID and ID
  1212. *
  1213. * @since 2.2
  1214. * @param string $order_id order ID
  1215. * @param string|null $fields fields to limit response to
  1216. * @return array
  1217. */
  1218. public function get_order_refund( $order_id, $id, $fields = null ) {
  1219. try {
  1220. // Validate order ID
  1221. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1222. if ( is_wp_error( $order_id ) ) {
  1223. return $order_id;
  1224. }
  1225. $id = absint( $id );
  1226. if ( empty( $id ) ) {
  1227. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID', 'woocommerce' ), 400 );
  1228. }
  1229. $order = wc_get_order( $id );
  1230. $refund = wc_get_order( $id );
  1231. if ( ! $refund ) {
  1232. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found', 'woocommerce' ), 404 );
  1233. }
  1234. $line_items = array();
  1235. // Add line items
  1236. foreach ( $refund->get_items( 'line_item' ) as $item_i