PageRenderTime 63ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/theshipswakecreative/psw
PHP | 1599 lines | 880 code | 368 blank | 351 comment | 170 complexity | b27401c87a1f46afca39de3dc94df598 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0

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

Large files files are truncated, but you can click here to view the full file