class-wc-api-orders.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  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|WP_Error
  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. $expand = array();
  125. if ( ! empty( $filter['expand'] ) ) {
  126. $expand = explode( ',', $filter['expand'] );
  127. }
  128. $order_data = array(
  129. 'id' => $order->get_id(),
  130. 'order_number' => $order->get_order_number(),
  131. 'order_key' => $order->get_order_key(),
  132. 'created_at' => $this->server->format_datetime( $order->get_date_created() ? $order->get_date_created()->getTimestamp() : 0, false, false ), // API gives UTC times.
  133. 'updated_at' => $this->server->format_datetime( $order->get_date_modified() ? $order->get_date_modified()->getTimestamp() : 0, false, false ), // API gives UTC times.
  134. 'completed_at' => $this->server->format_datetime( $order->get_date_completed() ? $order->get_date_completed()->getTimestamp() : 0, false, false ), // API gives UTC times.
  135. 'status' => $order->get_status(),
  136. 'currency' => $order->get_currency(),
  137. 'total' => wc_format_decimal( $order->get_total(), $dp ),
  138. 'subtotal' => wc_format_decimal( $order->get_subtotal(), $dp ),
  139. 'total_line_items_quantity' => $order->get_item_count(),
  140. 'total_tax' => wc_format_decimal( $order->get_total_tax(), $dp ),
  141. 'total_shipping' => wc_format_decimal( $order->get_shipping_total(), $dp ),
  142. 'cart_tax' => wc_format_decimal( $order->get_cart_tax(), $dp ),
  143. 'shipping_tax' => wc_format_decimal( $order->get_shipping_tax(), $dp ),
  144. 'total_discount' => wc_format_decimal( $order->get_total_discount(), $dp ),
  145. 'shipping_methods' => $order->get_shipping_method(),
  146. 'payment_details' => array(
  147. 'method_id' => $order->get_payment_method(),
  148. 'method_title' => $order->get_payment_method_title(),
  149. 'paid' => ! is_null( $order->get_date_paid() ),
  150. ),
  151. 'billing_address' => array(
  152. 'first_name' => $order->get_billing_first_name(),
  153. 'last_name' => $order->get_billing_last_name(),
  154. 'company' => $order->get_billing_company(),
  155. 'address_1' => $order->get_billing_address_1(),
  156. 'address_2' => $order->get_billing_address_2(),
  157. 'city' => $order->get_billing_city(),
  158. 'state' => $order->get_billing_state(),
  159. 'postcode' => $order->get_billing_postcode(),
  160. 'country' => $order->get_billing_country(),
  161. 'email' => $order->get_billing_email(),
  162. 'phone' => $order->get_billing_phone(),
  163. ),
  164. 'shipping_address' => array(
  165. 'first_name' => $order->get_shipping_first_name(),
  166. 'last_name' => $order->get_shipping_last_name(),
  167. 'company' => $order->get_shipping_company(),
  168. 'address_1' => $order->get_shipping_address_1(),
  169. 'address_2' => $order->get_shipping_address_2(),
  170. 'city' => $order->get_shipping_city(),
  171. 'state' => $order->get_shipping_state(),
  172. 'postcode' => $order->get_shipping_postcode(),
  173. 'country' => $order->get_shipping_country(),
  174. ),
  175. 'note' => $order->get_customer_note(),
  176. 'customer_ip' => $order->get_customer_ip_address(),
  177. 'customer_user_agent' => $order->get_customer_user_agent(),
  178. 'customer_id' => $order->get_user_id(),
  179. 'view_order_url' => $order->get_view_order_url(),
  180. 'line_items' => array(),
  181. 'shipping_lines' => array(),
  182. 'tax_lines' => array(),
  183. 'fee_lines' => array(),
  184. 'coupon_lines' => array(),
  185. );
  186. // Add line items.
  187. foreach ( $order->get_items() as $item_id => $item ) {
  188. $product = $item->get_product();
  189. $hideprefix = ( isset( $filter['all_item_meta'] ) && 'true' === $filter['all_item_meta'] ) ? null : '_';
  190. $item_meta = $item->get_formatted_meta_data( $hideprefix );
  191. foreach ( $item_meta as $key => $values ) {
  192. $item_meta[ $key ]->label = $values->display_key;
  193. unset( $item_meta[ $key ]->display_key );
  194. unset( $item_meta[ $key ]->display_value );
  195. }
  196. $line_item = array(
  197. 'id' => $item_id,
  198. 'subtotal' => wc_format_decimal( $order->get_line_subtotal( $item, false, false ), $dp ),
  199. 'subtotal_tax' => wc_format_decimal( $item->get_subtotal_tax(), $dp ),
  200. 'total' => wc_format_decimal( $order->get_line_total( $item, false, false ), $dp ),
  201. 'total_tax' => wc_format_decimal( $item->get_total_tax(), $dp ),
  202. 'price' => wc_format_decimal( $order->get_item_total( $item, false, false ), $dp ),
  203. 'quantity' => $item->get_quantity(),
  204. 'tax_class' => $item->get_tax_class(),
  205. 'name' => $item->get_name(),
  206. 'product_id' => $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id(),
  207. 'sku' => is_object( $product ) ? $product->get_sku() : null,
  208. 'meta' => array_values( $item_meta ),
  209. );
  210. if ( in_array( 'products', $expand ) && is_object( $product ) ) {
  211. $_product_data = WC()->api->WC_API_Products->get_product( $product->get_id() );
  212. if ( isset( $_product_data['product'] ) ) {
  213. $line_item['product_data'] = $_product_data['product'];
  214. }
  215. }
  216. $order_data['line_items'][] = $line_item;
  217. }
  218. // Add shipping.
  219. foreach ( $order->get_shipping_methods() as $shipping_item_id => $shipping_item ) {
  220. $order_data['shipping_lines'][] = array(
  221. 'id' => $shipping_item_id,
  222. 'method_id' => $shipping_item->get_method_id(),
  223. 'method_title' => $shipping_item->get_name(),
  224. 'total' => wc_format_decimal( $shipping_item->get_total(), $dp ),
  225. );
  226. }
  227. // Add taxes.
  228. foreach ( $order->get_tax_totals() as $tax_code => $tax ) {
  229. $tax_line = array(
  230. 'id' => $tax->id,
  231. 'rate_id' => $tax->rate_id,
  232. 'code' => $tax_code,
  233. 'title' => $tax->label,
  234. 'total' => wc_format_decimal( $tax->amount, $dp ),
  235. 'compound' => (bool) $tax->is_compound,
  236. );
  237. if ( in_array( 'taxes', $expand ) ) {
  238. $_rate_data = WC()->api->WC_API_Taxes->get_tax( $tax->rate_id );
  239. if ( isset( $_rate_data['tax'] ) ) {
  240. $tax_line['rate_data'] = $_rate_data['tax'];
  241. }
  242. }
  243. $order_data['tax_lines'][] = $tax_line;
  244. }
  245. // Add fees.
  246. foreach ( $order->get_fees() as $fee_item_id => $fee_item ) {
  247. $order_data['fee_lines'][] = array(
  248. 'id' => $fee_item_id,
  249. 'title' => $fee_item->get_name(),
  250. 'tax_class' => $fee_item->get_tax_class(),
  251. 'total' => wc_format_decimal( $order->get_line_total( $fee_item ), $dp ),
  252. 'total_tax' => wc_format_decimal( $order->get_line_tax( $fee_item ), $dp ),
  253. );
  254. }
  255. // Add coupons.
  256. foreach ( $order->get_items( 'coupon' ) as $coupon_item_id => $coupon_item ) {
  257. $coupon_line = array(
  258. 'id' => $coupon_item_id,
  259. 'code' => $coupon_item->get_code(),
  260. 'amount' => wc_format_decimal( $coupon_item->get_discount(), $dp ),
  261. );
  262. if ( in_array( 'coupons', $expand ) ) {
  263. $_coupon_data = WC()->api->WC_API_Coupons->get_coupon_by_code( $coupon_item->get_code() );
  264. if ( ! is_wp_error( $_coupon_data ) && isset( $_coupon_data['coupon'] ) ) {
  265. $coupon_line['coupon_data'] = $_coupon_data['coupon'];
  266. }
  267. }
  268. $order_data['coupon_lines'][] = $coupon_line;
  269. }
  270. return array( 'order' => apply_filters( 'woocommerce_api_order_response', $order_data, $order, $fields, $this->server ) );
  271. }
  272. /**
  273. * Get the total number of orders
  274. *
  275. * @since 2.4
  276. *
  277. * @param string $status
  278. * @param array $filter
  279. *
  280. * @return array|WP_Error
  281. */
  282. public function get_orders_count( $status = null, $filter = array() ) {
  283. try {
  284. if ( ! current_user_can( 'read_private_shop_orders' ) ) {
  285. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_orders_count', __( 'You do not have permission to read the orders count', 'woocommerce' ), 401 );
  286. }
  287. if ( ! empty( $status ) ) {
  288. if ( 'any' === $status ) {
  289. $order_statuses = array();
  290. foreach ( wc_get_order_statuses() as $slug => $name ) {
  291. $filter['status'] = str_replace( 'wc-', '', $slug );
  292. $query = $this->query_orders( $filter );
  293. $order_statuses[ str_replace( 'wc-', '', $slug ) ] = (int) $query->found_posts;
  294. }
  295. return array( 'count' => $order_statuses );
  296. } else {
  297. $filter['status'] = $status;
  298. }
  299. }
  300. $query = $this->query_orders( $filter );
  301. return array( 'count' => (int) $query->found_posts );
  302. } catch ( WC_API_Exception $e ) {
  303. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  304. }
  305. }
  306. /**
  307. * Get a list of valid order statuses
  308. *
  309. * Note this requires no specific permissions other than being an authenticated
  310. * API user. Order statuses (particularly custom statuses) could be considered
  311. * private information which is why it's not in the API index.
  312. *
  313. * @since 2.1
  314. * @return array
  315. */
  316. public function get_order_statuses() {
  317. $order_statuses = array();
  318. foreach ( wc_get_order_statuses() as $slug => $name ) {
  319. $order_statuses[ str_replace( 'wc-', '', $slug ) ] = $name;
  320. }
  321. return array( 'order_statuses' => apply_filters( 'woocommerce_api_order_statuses_response', $order_statuses, $this ) );
  322. }
  323. /**
  324. * Create an order
  325. *
  326. * @since 2.2
  327. * @param array $data raw order data
  328. * @return array|WP_Error
  329. */
  330. public function create_order( $data ) {
  331. global $wpdb;
  332. try {
  333. if ( ! isset( $data['order'] ) ) {
  334. throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order' ), 400 );
  335. }
  336. $data = $data['order'];
  337. // permission check
  338. if ( ! current_user_can( 'publish_shop_orders' ) ) {
  339. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order', __( 'You do not have permission to create orders', 'woocommerce' ), 401 );
  340. }
  341. $data = apply_filters( 'woocommerce_api_create_order_data', $data, $this );
  342. // default order args, note that status is checked for validity in wc_create_order()
  343. $default_order_args = array(
  344. 'status' => isset( $data['status'] ) ? $data['status'] : '',
  345. 'customer_note' => isset( $data['note'] ) ? $data['note'] : null,
  346. );
  347. // if creating order for existing customer
  348. if ( ! empty( $data['customer_id'] ) ) {
  349. // make sure customer exists
  350. if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
  351. throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid.', 'woocommerce' ), 400 );
  352. }
  353. $default_order_args['customer_id'] = $data['customer_id'];
  354. }
  355. // create the pending order
  356. $order = $this->create_base_order( $default_order_args, $data );
  357. if ( is_wp_error( $order ) ) {
  358. throw new WC_API_Exception( 'woocommerce_api_cannot_create_order', sprintf( __( 'Cannot create order: %s', 'woocommerce' ), implode( ', ', $order->get_error_messages() ) ), 400 );
  359. }
  360. // billing/shipping addresses
  361. $this->set_order_addresses( $order, $data );
  362. $lines = array(
  363. 'line_item' => 'line_items',
  364. 'shipping' => 'shipping_lines',
  365. 'fee' => 'fee_lines',
  366. 'coupon' => 'coupon_lines',
  367. );
  368. foreach ( $lines as $line_type => $line ) {
  369. if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
  370. $set_item = "set_{$line_type}";
  371. foreach ( $data[ $line ] as $item ) {
  372. $this->$set_item( $order, $item, 'create' );
  373. }
  374. }
  375. }
  376. // set is vat exempt
  377. if ( isset( $data['is_vat_exempt'] ) ) {
  378. update_post_meta( $order->get_id(), '_is_vat_exempt', $data['is_vat_exempt'] ? 'yes' : 'no' );
  379. }
  380. // calculate totals and set them
  381. $order->calculate_totals();
  382. // payment method (and payment_complete() if `paid` == true)
  383. if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
  384. // method ID & title are required
  385. if ( empty( $data['payment_details']['method_id'] ) || empty( $data['payment_details']['method_title'] ) ) {
  386. throw new WC_API_Exception( 'woocommerce_invalid_payment_details', __( 'Payment method ID and title are required', 'woocommerce' ), 400 );
  387. }
  388. update_post_meta( $order->get_id(), '_payment_method', $data['payment_details']['method_id'] );
  389. update_post_meta( $order->get_id(), '_payment_method_title', $data['payment_details']['method_title'] );
  390. // mark as paid if set
  391. if ( isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
  392. $order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
  393. }
  394. }
  395. // set order currency
  396. if ( isset( $data['currency'] ) ) {
  397. if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
  398. throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid.', 'woocommerce' ), 400 );
  399. }
  400. update_post_meta( $order->get_id(), '_order_currency', $data['currency'] );
  401. }
  402. // set order meta
  403. if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
  404. $this->set_order_meta( $order->get_id(), $data['order_meta'] );
  405. }
  406. // HTTP 201 Created
  407. $this->server->send_status( 201 );
  408. wc_delete_shop_order_transients( $order );
  409. do_action( 'woocommerce_api_create_order', $order->get_id(), $data, $this );
  410. do_action( 'woocommerce_new_order', $order->get_id() );
  411. return $this->get_order( $order->get_id() );
  412. } catch ( WC_Data_Exception $e ) {
  413. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => 400 ) );
  414. } catch ( WC_API_Exception $e ) {
  415. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  416. }
  417. }
  418. /**
  419. * Creates new WC_Order.
  420. *
  421. * Requires a separate function for classes that extend WC_API_Orders.
  422. *
  423. * @since 2.3
  424. *
  425. * @param $args array
  426. * @param $data
  427. *
  428. * @return WC_Order
  429. */
  430. protected function create_base_order( $args, $data ) {
  431. return wc_create_order( $args );
  432. }
  433. /**
  434. * Edit an order
  435. *
  436. * @since 2.2
  437. * @param int $id the order ID
  438. * @param array $data
  439. * @return array|WP_Error
  440. */
  441. public function edit_order( $id, $data ) {
  442. try {
  443. if ( ! isset( $data['order'] ) ) {
  444. throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order' ), 400 );
  445. }
  446. $data = $data['order'];
  447. $update_totals = false;
  448. $id = $this->validate_request( $id, $this->post_type, 'edit' );
  449. if ( is_wp_error( $id ) ) {
  450. return $id;
  451. }
  452. $data = apply_filters( 'woocommerce_api_edit_order_data', $data, $id, $this );
  453. $order = wc_get_order( $id );
  454. if ( empty( $order ) ) {
  455. throw new WC_API_Exception( 'woocommerce_api_invalid_order_id', __( 'Order ID is invalid', 'woocommerce' ), 400 );
  456. }
  457. $order_args = array( 'order_id' => $order->get_id() );
  458. // Customer note.
  459. if ( isset( $data['note'] ) ) {
  460. $order_args['customer_note'] = $data['note'];
  461. }
  462. // Customer ID.
  463. if ( isset( $data['customer_id'] ) && $data['customer_id'] != $order->get_user_id() ) {
  464. // Make sure customer exists.
  465. if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
  466. throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid.', 'woocommerce' ), 400 );
  467. }
  468. update_post_meta( $order->get_id(), '_customer_user', $data['customer_id'] );
  469. }
  470. // Billing/shipping address.
  471. $this->set_order_addresses( $order, $data );
  472. $lines = array(
  473. 'line_item' => 'line_items',
  474. 'shipping' => 'shipping_lines',
  475. 'fee' => 'fee_lines',
  476. 'coupon' => 'coupon_lines',
  477. );
  478. foreach ( $lines as $line_type => $line ) {
  479. if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
  480. $update_totals = true;
  481. foreach ( $data[ $line ] as $item ) {
  482. // Item ID is always required.
  483. if ( ! array_key_exists( 'id', $item ) ) {
  484. $item['id'] = null;
  485. }
  486. // Create item.
  487. if ( is_null( $item['id'] ) ) {
  488. $this->set_item( $order, $line_type, $item, 'create' );
  489. } elseif ( $this->item_is_null( $item ) ) {
  490. // Delete item.
  491. wc_delete_order_item( $item['id'] );
  492. } else {
  493. // Update item.
  494. $this->set_item( $order, $line_type, $item, 'update' );
  495. }
  496. }
  497. }
  498. }
  499. // Payment method (and payment_complete() if `paid` == true and order needs payment).
  500. if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
  501. // Method ID.
  502. if ( isset( $data['payment_details']['method_id'] ) ) {
  503. update_post_meta( $order->get_id(), '_payment_method', $data['payment_details']['method_id'] );
  504. }
  505. // Method title.
  506. if ( isset( $data['payment_details']['method_title'] ) ) {
  507. update_post_meta( $order->get_id(), '_payment_method_title', $data['payment_details']['method_title'] );
  508. }
  509. // Mark as paid if set.
  510. if ( $order->needs_payment() && isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
  511. $order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
  512. }
  513. }
  514. // Set order currency.
  515. if ( isset( $data['currency'] ) ) {
  516. if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
  517. throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid.', 'woocommerce' ), 400 );
  518. }
  519. update_post_meta( $order->get_id(), '_order_currency', $data['currency'] );
  520. }
  521. // If items have changed, recalculate order totals.
  522. if ( $update_totals ) {
  523. $order->calculate_totals();
  524. }
  525. // Update order meta.
  526. if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
  527. $this->set_order_meta( $order->get_id(), $data['order_meta'] );
  528. }
  529. // Update the order post to set customer note/modified date.
  530. wc_update_order( $order_args );
  531. // Order status.
  532. if ( ! empty( $data['status'] ) ) {
  533. // Refresh the order instance.
  534. $order = wc_get_order( $order->get_id() );
  535. $order->update_status( $data['status'], isset( $data['status_note'] ) ? $data['status_note'] : '', true );
  536. }
  537. wc_delete_shop_order_transients( $order );
  538. do_action( 'woocommerce_api_edit_order', $order->get_id(), $data, $this );
  539. do_action( 'woocommerce_update_order', $order->get_id() );
  540. return $this->get_order( $id );
  541. } catch ( WC_Data_Exception $e ) {
  542. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => 400 ) );
  543. } catch ( WC_API_Exception $e ) {
  544. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  545. }
  546. }
  547. /**
  548. * Delete an order
  549. *
  550. * @param int $id the order ID
  551. * @param bool $force true to permanently delete order, false to move to trash
  552. * @return array|WP_Error
  553. */
  554. public function delete_order( $id, $force = false ) {
  555. $id = $this->validate_request( $id, $this->post_type, 'delete' );
  556. if ( is_wp_error( $id ) ) {
  557. return $id;
  558. }
  559. wc_delete_shop_order_transients( $id );
  560. do_action( 'woocommerce_api_delete_order', $id, $this );
  561. return $this->delete( $id, 'order', ( 'true' === $force ) );
  562. }
  563. /**
  564. * Helper method to get order post objects
  565. *
  566. * @since 2.1
  567. * @param array $args request arguments for filtering query
  568. * @return WP_Query
  569. */
  570. protected function query_orders( $args ) {
  571. // set base query arguments
  572. $query_args = array(
  573. 'fields' => 'ids',
  574. 'post_type' => $this->post_type,
  575. 'post_status' => array_keys( wc_get_order_statuses() ),
  576. );
  577. // add status argument
  578. if ( ! empty( $args['status'] ) ) {
  579. $statuses = 'wc-' . str_replace( ',', ',wc-', $args['status'] );
  580. $statuses = explode( ',', $statuses );
  581. $query_args['post_status'] = $statuses;
  582. unset( $args['status'] );
  583. }
  584. if ( ! empty( $args['customer_id'] ) ) {
  585. $query_args['meta_query'] = array(
  586. array(
  587. 'key' => '_customer_user',
  588. 'value' => absint( $args['customer_id'] ),
  589. 'compare' => '=',
  590. ),
  591. );
  592. }
  593. $query_args = $this->merge_query_args( $query_args, $args );
  594. return new WP_Query( $query_args );
  595. }
  596. /**
  597. * Helper method to set/update the billing & shipping addresses for
  598. * an order
  599. *
  600. * @since 2.1
  601. * @param \WC_Order $order
  602. * @param array $data
  603. */
  604. protected function set_order_addresses( $order, $data ) {
  605. $address_fields = array(
  606. 'first_name',
  607. 'last_name',
  608. 'company',
  609. 'email',
  610. 'phone',
  611. 'address_1',
  612. 'address_2',
  613. 'city',
  614. 'state',
  615. 'postcode',
  616. 'country',
  617. );
  618. $billing_address = $shipping_address = array();
  619. // billing address
  620. if ( isset( $data['billing_address'] ) && is_array( $data['billing_address'] ) ) {
  621. foreach ( $address_fields as $field ) {
  622. if ( isset( $data['billing_address'][ $field ] ) ) {
  623. $billing_address[ $field ] = wc_clean( $data['billing_address'][ $field ] );
  624. }
  625. }
  626. unset( $address_fields['email'] );
  627. unset( $address_fields['phone'] );
  628. }
  629. // shipping address
  630. if ( isset( $data['shipping_address'] ) && is_array( $data['shipping_address'] ) ) {
  631. foreach ( $address_fields as $field ) {
  632. if ( isset( $data['shipping_address'][ $field ] ) ) {
  633. $shipping_address[ $field ] = wc_clean( $data['shipping_address'][ $field ] );
  634. }
  635. }
  636. }
  637. $this->update_address( $order, $billing_address, 'billing' );
  638. $this->update_address( $order, $shipping_address, 'shipping' );
  639. // update user meta
  640. if ( $order->get_user_id() ) {
  641. foreach ( $billing_address as $key => $value ) {
  642. update_user_meta( $order->get_user_id(), 'billing_' . $key, $value );
  643. }
  644. foreach ( $shipping_address as $key => $value ) {
  645. update_user_meta( $order->get_user_id(), 'shipping_' . $key, $value );
  646. }
  647. }
  648. }
  649. /**
  650. * Update address.
  651. *
  652. * @param WC_Order $order
  653. * @param array $posted
  654. * @param string $type
  655. */
  656. protected function update_address( $order, $posted, $type = 'billing' ) {
  657. foreach ( $posted as $key => $value ) {
  658. if ( is_callable( array( $order, "set_{$type}_{$key}" ) ) ) {
  659. $order->{"set_{$type}_{$key}"}( $value );
  660. }
  661. }
  662. }
  663. /**
  664. * Helper method to add/update order meta, with two restrictions:
  665. *
  666. * 1) Only non-protected meta (no leading underscore) can be set
  667. * 2) Meta values must be scalar (int, string, bool)
  668. *
  669. * @since 2.2
  670. * @param int $order_id valid order ID
  671. * @param array $order_meta order meta in array( 'meta_key' => 'meta_value' ) format
  672. */
  673. protected function set_order_meta( $order_id, $order_meta ) {
  674. foreach ( $order_meta as $meta_key => $meta_value ) {
  675. if ( is_string( $meta_key ) && ! is_protected_meta( $meta_key ) && is_scalar( $meta_value ) ) {
  676. update_post_meta( $order_id, $meta_key, $meta_value );
  677. }
  678. }
  679. }
  680. /**
  681. * Helper method to check if the resource ID associated with the provided item is null
  682. *
  683. * Items can be deleted by setting the resource ID to null
  684. *
  685. * @since 2.2
  686. * @param array $item item provided in the request body
  687. * @return bool true if the item resource ID is null, false otherwise
  688. */
  689. protected function item_is_null( $item ) {
  690. $keys = array( 'product_id', 'method_id', 'title', 'code' );
  691. foreach ( $keys as $key ) {
  692. if ( array_key_exists( $key, $item ) && is_null( $item[ $key ] ) ) {
  693. return true;
  694. }
  695. }
  696. return false;
  697. }
  698. /**
  699. * Wrapper method to create/update order items
  700. *
  701. * When updating, the item ID provided is checked to ensure it is associated
  702. * with the order.
  703. *
  704. * @since 2.2
  705. * @param \WC_Order $order order
  706. * @param string $item_type
  707. * @param array $item item provided in the request body
  708. * @param string $action either 'create' or 'update'
  709. * @throws WC_API_Exception if item ID is not associated with order
  710. */
  711. protected function set_item( $order, $item_type, $item, $action ) {
  712. global $wpdb;
  713. $set_method = "set_{$item_type}";
  714. // verify provided line item ID is associated with order
  715. if ( 'update' === $action ) {
  716. $result = $wpdb->get_row(
  717. $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_id = %d AND order_id = %d",
  718. absint( $item['id'] ),
  719. absint( $order->get_id() )
  720. ) );
  721. if ( is_null( $result ) ) {
  722. throw new WC_API_Exception( 'woocommerce_invalid_item_id', __( 'Order item ID provided is not associated with order.', 'woocommerce' ), 400 );
  723. }
  724. }
  725. $this->$set_method( $order, $item, $action );
  726. }
  727. /**
  728. * Create or update a line item
  729. *
  730. * @since 2.2
  731. * @param \WC_Order $order
  732. * @param array $item line item data
  733. * @param string $action 'create' to add line item or 'update' to update it
  734. * @throws WC_API_Exception invalid data, server error
  735. */
  736. protected function set_line_item( $order, $item, $action ) {
  737. $creating = ( 'create' === $action );
  738. // product is always required
  739. if ( ! isset( $item['product_id'] ) && ! isset( $item['sku'] ) ) {
  740. throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID or SKU is required', 'woocommerce' ), 400 );
  741. }
  742. // when updating, ensure product ID provided matches
  743. if ( 'update' === $action ) {
  744. $item_product_id = wc_get_order_item_meta( $item['id'], '_product_id' );
  745. $item_variation_id = wc_get_order_item_meta( $item['id'], '_variation_id' );
  746. if ( $item['product_id'] != $item_product_id && $item['product_id'] != $item_variation_id ) {
  747. throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID provided does not match this line item', 'woocommerce' ), 400 );
  748. }
  749. }
  750. if ( isset( $item['product_id'] ) ) {
  751. $product_id = $item['product_id'];
  752. } elseif ( isset( $item['sku'] ) ) {
  753. $product_id = wc_get_product_id_by_sku( $item['sku'] );
  754. }
  755. // variations must each have a key & value
  756. $variation_id = 0;
  757. if ( isset( $item['variations'] ) && is_array( $item['variations'] ) ) {
  758. foreach ( $item['variations'] as $key => $value ) {
  759. if ( ! $key || ! $value ) {
  760. throw new WC_API_Exception( 'woocommerce_api_invalid_product_variation', __( 'The product variation is invalid', 'woocommerce' ), 400 );
  761. }
  762. }
  763. $variation_id = $this->get_variation_id( wc_get_product( $product_id ), $item['variations'] );
  764. }
  765. $product = wc_get_product( $variation_id ? $variation_id : $product_id );
  766. // must be a valid WC_Product
  767. if ( ! is_object( $product ) ) {
  768. throw new WC_API_Exception( 'woocommerce_api_invalid_product', __( 'Product is invalid.', 'woocommerce' ), 400 );
  769. }
  770. // quantity must be positive float
  771. if ( isset( $item['quantity'] ) && floatval( $item['quantity'] ) <= 0 ) {
  772. throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity must be a positive float.', 'woocommerce' ), 400 );
  773. }
  774. // quantity is required when creating
  775. if ( $creating && ! isset( $item['quantity'] ) ) {
  776. throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity is required.', 'woocommerce' ), 400 );
  777. }
  778. // quantity
  779. if ( $creating ) {
  780. $line_item = new WC_Order_Item_Product();
  781. } else {
  782. $line_item = new WC_Order_Item_Product( $item['id'] );
  783. }
  784. $line_item->set_product( $product );
  785. $line_item->set_order_id( $order->get_id() );
  786. if ( isset( $item['quantity'] ) ) {
  787. $line_item->set_quantity( $item['quantity'] );
  788. }
  789. if ( isset( $item['total'] ) ) {
  790. $line_item->set_total( floatval( $item['total'] ) );
  791. } elseif ( $creating ) {
  792. $total = wc_get_price_excluding_tax( $product, array( 'qty' => $line_item->get_quantity() ) );
  793. $line_item->set_total( $total );
  794. $line_item->set_subtotal( $total );
  795. }
  796. if ( isset( $item['total_tax'] ) ) {
  797. $line_item->set_total_tax( floatval( $item['total_tax'] ) );
  798. }
  799. if ( isset( $item['subtotal'] ) ) {
  800. $line_item->set_subtotal( floatval( $item['subtotal'] ) );
  801. }
  802. if ( isset( $item['subtotal_tax'] ) ) {
  803. $line_item->set_subtotal_tax( floatval( $item['subtotal_tax'] ) );
  804. }
  805. if ( $variation_id ) {
  806. $line_item->set_variation_id( $variation_id );
  807. $line_item->set_variation( $item['variations'] );
  808. }
  809. // Save or add to order.
  810. if ( $creating ) {
  811. $order->add_item( $line_item );
  812. } else {
  813. $item_id = $line_item->save();
  814. if ( ! $item_id ) {
  815. throw new WC_API_Exception( 'woocommerce_cannot_create_line_item', __( 'Cannot create line item, try again.', 'woocommerce' ), 500 );
  816. }
  817. }
  818. }
  819. /**
  820. * Given a product ID & API provided variations, find the correct variation ID to use for calculation
  821. * We can't just trust input from the API to pass a variation_id manually, otherwise you could pass
  822. * the cheapest variation ID but provide other information so we have to look up the variation ID.
  823. *
  824. * @param WC_Product $product Product instance
  825. * @param array $variations
  826. *
  827. * @return int Returns an ID if a valid variation was found for this product
  828. */
  829. public function get_variation_id( $product, $variations = array() ) {
  830. $variation_id = null;
  831. $variations_normalized = array();
  832. if ( $product->is_type( 'variable' ) && $product->has_child() ) {
  833. if ( isset( $variations ) && is_array( $variations ) ) {
  834. // start by normalizing the passed variations
  835. foreach ( $variations as $key => $value ) {
  836. $key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) ); // from get_attributes in class-wc-api-products.php
  837. $variations_normalized[ $key ] = strtolower( $value );
  838. }
  839. // now search through each product child and see if our passed variations match anything
  840. foreach ( $product->get_children() as $variation ) {
  841. $meta = array();
  842. foreach ( get_post_meta( $variation ) as $key => $value ) {
  843. $value = $value[0];
  844. $key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) );
  845. $meta[ $key ] = strtolower( $value );
  846. }
  847. // if the variation array is a part of the $meta array, we found our match
  848. if ( $this->array_contains( $variations_normalized, $meta ) ) {
  849. $variation_id = $variation;
  850. break;
  851. }
  852. }
  853. }
  854. }
  855. return $variation_id;
  856. }
  857. /**
  858. * Utility function to see if the meta array contains data from variations
  859. *
  860. * @param array $needles
  861. * @param array $haystack
  862. *
  863. * @return bool
  864. */
  865. protected function array_contains( $needles, $haystack ) {
  866. foreach ( $needles as $key => $value ) {
  867. if ( $haystack[ $key ] !== $value ) {
  868. return false;
  869. }
  870. }
  871. return true;
  872. }
  873. /**
  874. * Create or update an order shipping method
  875. *
  876. * @since 2.2
  877. * @param \WC_Order $order
  878. * @param array $shipping item data
  879. * @param string $action 'create' to add shipping or 'update' to update it
  880. * @throws WC_API_Exception invalid data, server error
  881. */
  882. protected function set_shipping( $order, $shipping, $action ) {
  883. // total must be a positive float
  884. if ( isset( $shipping['total'] ) && floatval( $shipping['total'] ) < 0 ) {
  885. throw new WC_API_Exception( 'woocommerce_invalid_shipping_total', __( 'Shipping total must be a positive amount.', 'woocommerce' ), 400 );
  886. }
  887. if ( 'create' === $action ) {
  888. // method ID is required
  889. if ( ! isset( $shipping['method_id'] ) ) {
  890. throw new WC_API_Exception( 'woocommerce_invalid_shipping_item', __( 'Shipping method ID is required.', 'woocommerce' ), 400 );
  891. }
  892. $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'] );
  893. $item = new WC_Order_Item_Shipping();
  894. $item->set_order_id( $order->get_id() );
  895. $item->set_shipping_rate( $rate );
  896. $order->add_item( $item );
  897. } else {
  898. $item = new WC_Order_Item_Shipping( $shipping['id'] );
  899. if ( isset( $shipping['method_id'] ) ) {
  900. $item->set_method_id( $shipping['method_id'] );
  901. }
  902. if ( isset( $shipping['method_title'] ) ) {
  903. $item->set_method_title( $shipping['method_title'] );
  904. }
  905. if ( isset( $shipping['total'] ) ) {
  906. $item->set_total( floatval( $shipping['total'] ) );
  907. }
  908. $shipping_id = $item->save();
  909. if ( ! $shipping_id ) {
  910. throw new WC_API_Exception( 'woocommerce_cannot_update_shipping', __( 'Cannot update shipping method, try again.', 'woocommerce' ), 500 );
  911. }
  912. }
  913. }
  914. /**
  915. * Create or update an order fee
  916. *
  917. * @since 2.2
  918. * @param \WC_Order $order
  919. * @param array $fee item data
  920. * @param string $action 'create' to add fee or 'update' to update it
  921. * @throws WC_API_Exception invalid data, server error
  922. */
  923. protected function set_fee( $order, $fee, $action ) {
  924. if ( 'create' === $action ) {
  925. // fee title is required
  926. if ( ! isset( $fee['title'] ) ) {
  927. throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee title is required', 'woocommerce' ), 400 );
  928. }
  929. $item = new WC_Order_Item_Fee();
  930. $item->set_order_id( $order->get_id() );
  931. $item->set_name( wc_clean( $fee['title'] ) );
  932. $item->set_total( isset( $fee['total'] ) ? floatval( $fee['total'] ) : 0 );
  933. // if taxable, tax class and total are required
  934. if ( ! empty( $fee['taxable'] ) ) {
  935. if ( ! isset( $fee['tax_class'] ) ) {
  936. throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee tax class is required when fee is taxable.', 'woocommerce' ), 400 );
  937. }
  938. $item->set_tax_status( 'taxable' );
  939. $item->set_tax_class( $fee['tax_class'] );
  940. if ( isset( $fee['total_tax'] ) ) {
  941. $item->set_total_tax( isset( $fee['total_tax'] ) ? wc_format_refund_total( $fee['total_tax'] ) : 0 );
  942. }
  943. if ( isset( $fee['tax_data'] ) ) {
  944. $item->set_total_tax( wc_format_refund_total( array_sum( $fee['tax_data'] ) ) );
  945. $item->set_taxes( array_map( 'wc_format_refund_total', $fee['tax_data'] ) );
  946. }
  947. }
  948. $order->add_item( $item );
  949. } else {
  950. $item = new WC_Order_Item_Fee( $fee['id'] );
  951. if ( isset( $fee['title'] ) ) {
  952. $item->set_name( wc_clean( $fee['title'] ) );
  953. }
  954. if ( isset( $fee['tax_class'] ) ) {
  955. $item->set_tax_class( $fee['tax_class'] );
  956. }
  957. if ( isset( $fee['total'] ) ) {
  958. $item->set_total( floatval( $fee['total'] ) );
  959. }
  960. if ( isset( $fee['total_tax'] ) ) {
  961. $item->set_total_tax( floatval( $fee['total_tax'] ) );
  962. }
  963. $fee_id = $item->save();
  964. if ( ! $fee_id ) {
  965. throw new WC_API_Exception( 'woocommerce_cannot_update_fee', __( 'Cannot update fee, try again.', 'woocommerce' ), 500 );
  966. }
  967. }
  968. }
  969. /**
  970. * Create or update an order coupon
  971. *
  972. * @since 2.2
  973. * @param \WC_Order $order
  974. * @param array $coupon item data
  975. * @param string $action 'create' to add coupon or 'update' to update it
  976. * @throws WC_API_Exception invalid data, server error
  977. */
  978. protected function set_coupon( $order, $coupon, $action ) {
  979. // coupon amount must be positive float
  980. if ( isset( $coupon['amount'] ) && floatval( $coupon['amount'] ) < 0 ) {
  981. throw new WC_API_Exception( 'woocommerce_invalid_coupon_total', __( 'Coupon discount total must be a positive amount.', 'woocommerce' ), 400 );
  982. }
  983. if ( 'create' === $action ) {
  984. // coupon code is required
  985. if ( empty( $coupon['code'] ) ) {
  986. throw new WC_API_Exception( 'woocommerce_invalid_coupon_coupon', __( 'Coupon code is required.', 'woocommerce' ), 400 );
  987. }
  988. $item = new WC_Order_Item_Coupon();
  989. $item->set_props( array(
  990. 'code' => $coupon['code'],
  991. 'discount' => isset( $coupon['amount'] ) ? floatval( $coupon['amount'] ) : 0,
  992. 'discount_tax' => 0,
  993. 'order_id' => $order->get_id(),
  994. ) );
  995. $order->add_item( $item );
  996. } else {
  997. $item = new WC_Order_Item_Coupon( $coupon['id'] );
  998. if ( isset( $coupon['code'] ) ) {
  999. $item->set_code( $coupon['code'] );
  1000. }
  1001. if ( isset( $coupon['amount'] ) ) {
  1002. $item->set_discount( floatval( $coupon['amount'] ) );
  1003. }
  1004. $coupon_id = $item->save();
  1005. if ( ! $coupon_id ) {
  1006. throw new WC_API_Exception( 'woocommerce_cannot_update_order_coupon', __( 'Cannot update coupon, try again.', 'woocommerce' ), 500 );
  1007. }
  1008. }
  1009. }
  1010. /**
  1011. * Get the admin order notes for an order
  1012. *
  1013. * @since 2.1
  1014. * @param string $order_id order ID
  1015. * @param string|null $fields fields to include in response
  1016. * @return array|WP_Error
  1017. */
  1018. public function get_order_notes( $order_id, $fields = null ) {
  1019. // ensure ID is valid order ID
  1020. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1021. if ( is_wp_error( $order_id ) ) {
  1022. return $order_id;
  1023. }
  1024. $args = array(
  1025. 'post_id' => $order_id,
  1026. 'approve' => 'approve',
  1027. 'type' => 'order_note',
  1028. );
  1029. remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  1030. $notes = get_comments( $args );
  1031. add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  1032. $order_notes = array();
  1033. foreach ( $notes as $note ) {
  1034. $order_notes[] = current( $this->get_order_note( $order_id, $note->comment_ID, $fields ) );
  1035. }
  1036. return array( 'order_notes' => apply_filters( 'woocommerce_api_order_notes_response', $order_notes, $order_id, $fields, $notes, $this->server ) );
  1037. }
  1038. /**
  1039. * Get an order note for the given order ID and ID
  1040. *
  1041. * @since 2.2
  1042. *
  1043. * @param string $order_id order ID
  1044. * @param string $id order note ID
  1045. * @param string|null $fields fields to limit response to
  1046. *
  1047. * @return array|WP_Error
  1048. */
  1049. public function get_order_note( $order_id, $id, $fields = null ) {
  1050. try {
  1051. // Validate order ID
  1052. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1053. if ( is_wp_error( $order_id ) ) {
  1054. return $order_id;
  1055. }
  1056. $id = absint( $id );
  1057. if ( empty( $id ) ) {
  1058. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1059. }
  1060. $note = get_comment( $id );
  1061. if ( is_null( $note ) ) {
  1062. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1063. }
  1064. $order_note = array(
  1065. 'id' => $note->comment_ID,
  1066. 'created_at' => $this->server->format_datetime( $note->comment_date_gmt ),
  1067. 'note' => $note->comment_content,
  1068. 'customer_note' => (bool) get_comment_meta( $note->comment_ID, 'is_customer_note', true ),
  1069. );
  1070. return array( 'order_note' => apply_filters( 'woocommerce_api_order_note_response', $order_note, $id, $fields, $note, $order_id, $this ) );
  1071. } catch ( WC_API_Exception $e ) {
  1072. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1073. }
  1074. }
  1075. /**
  1076. * Create a new order note for the given order
  1077. *
  1078. * @since 2.2
  1079. * @param string $order_id order ID
  1080. * @param array $data raw request data
  1081. * @return WP_Error|array error or created note response data
  1082. */
  1083. public function create_order_note( $order_id, $data ) {
  1084. try {
  1085. if ( ! isset( $data['order_note'] ) ) {
  1086. 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 );
  1087. }
  1088. $data = $data['order_note'];
  1089. // permission check
  1090. if ( ! current_user_can( 'publish_shop_orders' ) ) {
  1091. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order_note', __( 'You do not have permission to create order notes', 'woocommerce' ), 401 );
  1092. }
  1093. $order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
  1094. if ( is_wp_error( $order_id ) ) {
  1095. return $order_id;
  1096. }
  1097. $order = wc_get_order( $order_id );
  1098. $data = apply_filters( 'woocommerce_api_create_order_note_data', $data, $order_id, $this );
  1099. // note content is required
  1100. if ( ! isset( $data['note'] ) ) {
  1101. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note', __( 'Order note is required', 'woocommerce' ), 400 );
  1102. }
  1103. $is_customer_note = ( isset( $data['customer_note'] ) && true === $data['customer_note'] );
  1104. // create the note
  1105. $note_id = $order->add_order_note( $data['note'], $is_customer_note );
  1106. if ( ! $note_id ) {
  1107. throw new WC_API_Exception( 'woocommerce_api_cannot_create_order_note', __( 'Cannot create order note, please try again.', 'woocommerce' ), 500 );
  1108. }
  1109. // HTTP 201 Created
  1110. $this->server->send_status( 201 );
  1111. do_action( 'woocommerce_api_create_order_note', $note_id, $order_id, $this );
  1112. return $this->get_order_note( $order->get_id(), $note_id );
  1113. } catch ( WC_Data_Exception $e ) {
  1114. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => 400 ) );
  1115. } catch ( WC_API_Exception $e ) {
  1116. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1117. }
  1118. }
  1119. /**
  1120. * Edit the order note
  1121. *
  1122. * @since 2.2
  1123. * @param string $order_id order ID
  1124. * @param string $id note ID
  1125. * @param array $data parsed request data
  1126. * @return WP_Error|array error or edited note response data
  1127. */
  1128. public function edit_order_note( $order_id, $id, $data ) {
  1129. try {
  1130. if ( ! isset( $data['order_note'] ) ) {
  1131. 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 );
  1132. }
  1133. $data = $data['order_note'];
  1134. // Validate order ID
  1135. $order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
  1136. if ( is_wp_error( $order_id ) ) {
  1137. return $order_id;
  1138. }
  1139. $order = wc_get_order( $order_id );
  1140. // Validate note ID
  1141. $id = absint( $id );
  1142. if ( empty( $id ) ) {
  1143. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1144. }
  1145. // Ensure note ID is valid
  1146. $note = get_comment( $id );
  1147. if ( is_null( $note ) ) {
  1148. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1149. }
  1150. // Ensure note ID is associated with given order
  1151. if ( $note->comment_post_ID != $order->get_id() ) {
  1152. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
  1153. }
  1154. $data = apply_filters( 'woocommerce_api_edit_order_note_data', $data, $note->comment_ID, $order->get_id(), $this );
  1155. // Note content
  1156. if ( isset( $data['note'] ) ) {
  1157. wp_update_comment(
  1158. array(
  1159. 'comment_ID' => $note->comment_ID,
  1160. 'comment_content' => $data['note'],
  1161. )
  1162. );
  1163. }
  1164. // Customer note
  1165. if ( isset( $data['customer_note'] ) ) {
  1166. update_comment_meta( $note->comment_ID, 'is_customer_note', true === $data['customer_note'] ? 1 : 0 );
  1167. }
  1168. do_action( 'woocommerce_api_edit_order_note', $note->comment_ID, $order->get_id(), $this );
  1169. return $this->get_order_note( $order->get_id(), $note->comment_ID );
  1170. } catch ( WC_Data_Exception $e ) {
  1171. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => 400 ) );
  1172. } catch ( WC_API_Exception $e ) {
  1173. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1174. }
  1175. }
  1176. /**
  1177. * Delete order note
  1178. *
  1179. * @since 2.2
  1180. * @param string $order_id order ID
  1181. * @param string $id note ID
  1182. * @return WP_Error|array error or deleted message
  1183. */
  1184. public function delete_order_note( $order_id, $id ) {
  1185. try {
  1186. $order_id = $this->validate_request( $order_id, $this->post_type, 'delete' );
  1187. if ( is_wp_error( $order_id ) ) {
  1188. return $order_id;
  1189. }
  1190. // Validate note ID
  1191. $id = absint( $id );
  1192. if ( empty( $id ) ) {
  1193. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1194. }
  1195. // Ensure note ID is valid
  1196. $note = get_comment( $id );
  1197. if ( is_null( $note ) ) {
  1198. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1199. }
  1200. // Ensure note ID is associated with given order
  1201. if ( $note->comment_post_ID != $order_id ) {
  1202. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
  1203. }
  1204. // Force delete since trashed order notes could not be managed through comments list table
  1205. $result = wc_delete_order_note( $note->comment_ID );
  1206. if ( ! $result ) {
  1207. throw new WC_API_Exception( 'woocommerce_api_cannot_delete_order_note', __( 'This order note cannot be deleted', 'woocommerce' ), 500 );
  1208. }
  1209. do_action( 'woocommerce_api_delete_order_note', $note->comment_ID, $order_id, $this );
  1210. return array( 'message' => __( 'Permanently deleted order note', 'woocommerce' ) );
  1211. } catch ( WC_API_Exception $e ) {
  1212. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1213. }
  1214. }
  1215. /**
  1216. * Get the order refunds for an order
  1217. *
  1218. * @since 2.2
  1219. * @param string $order_id order ID
  1220. * @param string|null $fields fields to include in response
  1221. * @return array|WP_Error
  1222. */
  1223. public function get_order_refunds( $order_id, $fields = null ) {
  1224. // Ensure ID is valid order ID
  1225. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1226. if ( is_wp_error( $order_id ) ) {
  1227. return $order_id;
  1228. }
  1229. $refund_items = wc_get_orders( array(
  1230. 'type' => 'shop_order_refund',
  1231. 'parent' => $order_id,
  1232. 'limit' => -1,
  1233. 'return' => 'ids',
  1234. ) );
  1235. $order_refunds = array();
  1236. foreach ( $refund_items as $refund_id ) {
  1237. $order_refunds[] = current( $this->get_order_refund( $order_id, $refund_id, $fields ) );
  1238. }
  1239. return array( 'order_refunds' => apply_filters( 'woocommerce_api_order_refunds_response', $order_refunds, $order_id, $fields, $refund_items, $this ) );
  1240. }
  1241. /**
  1242. * Get an order refund for the given order ID and ID
  1243. *
  1244. * @since 2.2
  1245. *
  1246. * @param string $order_id order ID
  1247. * @param int $id
  1248. * @param string|null $fields fields to limit response to
  1249. *
  1250. * @return array|WP_Error
  1251. */
  1252. public function get_order_refund( $order_id, $id, $fields = null ) {
  1253. try {
  1254. // Validate order ID
  1255. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1256. if ( is_wp_error( $order_id ) ) {
  1257. return $order_id;
  1258. }
  1259. $id = absint( $id );
  1260. if ( empty( $id ) ) {
  1261. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID.', 'woocommerce' ), 400 );
  1262. }
  1263. $order = wc_get_order( $order_id );
  1264. $refund = wc_get_order( $id );
  1265. if ( ! $refund ) {
  1266. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found.', 'woocommerce' ), 404 );
  1267. }
  1268. $line_items = array();
  1269. // Add line items
  1270. foreach ( $refund->get_items( 'line_item' ) as $item_id => $item ) {
  1271. $product = $item->get_product();
  1272. $hideprefix = ( isset( $filter['all_item_meta'] ) && 'true' === $filter['all_item_meta'] ) ? null : '_';
  1273. $item_meta = $item->get_formatted_meta_data( $hideprefix );
  1274. foreach ( $item_meta as $key => $values ) {
  1275. $item_meta[ $key ]->label = $values->display_key;
  1276. unset( $item_meta[ $key ]->display_key );
  1277. unset( $item_meta[ $key ]->display_value );
  1278. }
  1279. $line_items[] = array(
  1280. 'id' => $item_id,
  1281. 'subtotal' => wc_format_decimal( $order->get_line_subtotal( $item ), 2 ),
  1282. 'subtotal_tax' => wc_format_decimal( $item->get_subtotal_tax(), 2 ),
  1283. 'total' => wc_format_decimal( $order->get_line_total( $item ), 2 ),
  1284. 'total_tax' => wc_format_decimal( $order->get_line_tax( $item ), 2 ),
  1285. 'price' => wc_format_decimal( $order->get_item_total( $item ), 2 ),
  1286. 'quantity' => $item->get_quantity(),
  1287. 'tax_class' => $item->get_tax_class(),
  1288. 'name' => $item->get_name(),
  1289. 'product_id' => $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id(),
  1290. 'sku' => is_object( $product ) ? $product->get_sku() : null,
  1291. 'meta' => array_values( $item_meta ),
  1292. 'refunded_item_id' => (int) $item->get_meta( 'refunded_item_id' ),
  1293. );
  1294. }
  1295. $order_refund = array(
  1296. 'id' => $refund->get_id(),
  1297. 'created_at' => $this->server->format_datetime( $refund->get_date_created() ? $refund->get_date_created()->getTimestamp() : 0, false, false ),
  1298. 'amount' => wc_format_decimal( $refund->get_amount(), 2 ),
  1299. 'reason' => $refund->get_reason(),
  1300. 'line_items' => $line_items,
  1301. );
  1302. return array( 'order_refund' => apply_filters( 'woocommerce_api_order_refund_response', $order_refund, $id, $fields, $refund, $order_id, $this ) );
  1303. } catch ( WC_API_Exception $e ) {
  1304. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1305. }
  1306. }
  1307. /**
  1308. * Create a new order refund for the given order
  1309. *
  1310. * @since 2.2
  1311. * @param string $order_id order ID
  1312. * @param array $data raw request data
  1313. * @param bool $api_refund do refund using a payment gateway API
  1314. * @return WP_Error|array error or created refund response data
  1315. */
  1316. public function create_order_refund( $order_id, $data, $api_refund = true ) {
  1317. try {
  1318. if ( ! isset( $data['order_refund'] ) ) {
  1319. throw new WC_API_Exception( 'woocommerce_api_missing_order_refund_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order_refund' ), 400 );
  1320. }
  1321. $data = $data['order_refund'];
  1322. // Permission check
  1323. if ( ! current_user_can( 'publish_shop_orders' ) ) {
  1324. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order_refund', __( 'You do not have permission to create order refunds', 'woocommerce' ), 401 );
  1325. }
  1326. $order_id = absint( $order_id );
  1327. if ( empty( $order_id ) ) {
  1328. throw new WC_API_Exception( 'woocommerce_api_invalid_order_id', __( 'Order ID is invalid', 'woocommerce' ), 400 );
  1329. }
  1330. $data = apply_filters( 'woocommerce_api_create_order_refund_data', $data, $order_id, $this );
  1331. // Refund amount is required
  1332. if ( ! isset( $data['amount'] ) ) {
  1333. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund', __( 'Refund amount is required.', 'woocommerce' ), 400 );
  1334. } elseif ( 0 > $data['amount'] ) {
  1335. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund', __( 'Refund amount must be positive.', 'woocommerce' ), 400 );
  1336. }
  1337. $data['order_id'] = $order_id;
  1338. $data['refund_id'] = 0;
  1339. // Create the refund
  1340. $refund = wc_create_refund( $data );
  1341. if ( ! $refund ) {
  1342. throw new WC_API_Exception( 'woocommerce_api_cannot_create_order_refund', __( 'Cannot create order refund, please try again.', 'woocommerce' ), 500 );
  1343. }
  1344. // Refund via API
  1345. if ( $api_refund ) {
  1346. if ( WC()->payment_gateways() ) {
  1347. $payment_gateways = WC()->payment_gateways->payment_gateways();
  1348. }
  1349. $order = wc_get_order( $order_id );
  1350. if ( isset( $payment_gateways[ $order->get_payment_method() ] ) && $payment_gateways[ $order->get_payment_method() ]->supports( 'refunds' ) ) {
  1351. $result = $payment_gateways[ $order->get_payment_method() ]->process_refund( $order_id, $refund->get_amount(), $refund->get_reason() );
  1352. if ( is_wp_error( $result ) ) {
  1353. return $result;
  1354. } elseif ( ! $result ) {
  1355. throw new WC_API_Exception( 'woocommerce_api_create_order_refund_api_failed', __( 'An error occurred while attempting to create the refund using the payment gateway API.', 'woocommerce' ), 500 );
  1356. }
  1357. }
  1358. }
  1359. // HTTP 201 Created
  1360. $this->server->send_status( 201 );
  1361. do_action( 'woocommerce_api_create_order_refund', $refund->get_id(), $order_id, $this );
  1362. return $this->get_order_refund( $order_id, $refund->get_id() );
  1363. } catch ( WC_Data_Exception $e ) {
  1364. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => 400 ) );
  1365. } catch ( WC_API_Exception $e ) {
  1366. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1367. }
  1368. }
  1369. /**
  1370. * Edit an order refund
  1371. *
  1372. * @since 2.2
  1373. * @param string $order_id order ID
  1374. * @param string $id refund ID
  1375. * @param array $data parsed request data
  1376. * @return WP_Error|array error or edited refund response data
  1377. */
  1378. public function edit_order_refund( $order_id, $id, $data ) {
  1379. try {
  1380. if ( ! isset( $data['order_refund'] ) ) {
  1381. throw new WC_API_Exception( 'woocommerce_api_missing_order_refund_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order_refund' ), 400 );
  1382. }
  1383. $data = $data['order_refund'];
  1384. // Validate order ID
  1385. $order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
  1386. if ( is_wp_error( $order_id ) ) {
  1387. return $order_id;
  1388. }
  1389. // Validate refund ID
  1390. $id = absint( $id );
  1391. if ( empty( $id ) ) {
  1392. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID.', 'woocommerce' ), 400 );
  1393. }
  1394. // Ensure order ID is valid
  1395. $refund = get_post( $id );
  1396. if ( ! $refund ) {
  1397. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found.', 'woocommerce' ), 404 );
  1398. }
  1399. // Ensure refund ID is associated with given order
  1400. if ( $refund->post_parent != $order_id ) {
  1401. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'The order refund ID provided is not associated with the order.', 'woocommerce' ), 400 );
  1402. }
  1403. $data = apply_filters( 'woocommerce_api_edit_order_refund_data', $data, $refund->ID, $order_id, $this );
  1404. // Update reason
  1405. if ( isset( $data['reason'] ) ) {
  1406. $updated_refund = wp_update_post( array( 'ID' => $refund->ID, 'post_excerpt' => $data['reason'] ) );
  1407. if ( is_wp_error( $updated_refund ) ) {
  1408. return $updated_refund;
  1409. }
  1410. }
  1411. // Update refund amount
  1412. if ( isset( $data['amount'] ) && 0 < $data['amount'] ) {
  1413. update_post_meta( $refund->ID, '_refund_amount', wc_format_decimal( $data['amount'] ) );
  1414. }
  1415. do_action( 'woocommerce_api_edit_order_refund', $refund->ID, $order_id, $this );
  1416. return $this->get_order_refund( $order_id, $refund->ID );
  1417. } catch ( WC_Data_Exception $e ) {
  1418. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => 400 ) );
  1419. } catch ( WC_API_Exception $e ) {
  1420. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1421. }
  1422. }
  1423. /**
  1424. * Delete order refund
  1425. *
  1426. * @since 2.2
  1427. * @param string $order_id order ID
  1428. * @param string $id refund ID
  1429. * @return WP_Error|array error or deleted message
  1430. */
  1431. public function delete_order_refund( $order_id, $id ) {
  1432. try {
  1433. $order_id = $this->validate_request( $order_id, $this->post_type, 'delete' );
  1434. if ( is_wp_error( $order_id ) ) {
  1435. return $order_id;
  1436. }
  1437. // Validate refund ID
  1438. $id = absint( $id );
  1439. if ( empty( $id ) ) {
  1440. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID.', 'woocommerce' ), 400 );
  1441. }
  1442. // Ensure refund ID is valid
  1443. $refund = get_post( $id );
  1444. if ( ! $refund ) {
  1445. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found.', 'woocommerce' ), 404 );
  1446. }
  1447. // Ensure refund ID is associated with given order
  1448. if ( $refund->post_parent != $order_id ) {
  1449. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'The order refund ID provided is not associated with the order.', 'woocommerce' ), 400 );
  1450. }
  1451. wc_delete_shop_order_transients( $order_id );
  1452. do_action( 'woocommerce_api_delete_order_refund', $refund->ID, $order_id, $this );
  1453. return $this->delete( $refund->ID, 'refund', true );
  1454. } catch ( WC_API_Exception $e ) {
  1455. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1456. }
  1457. }
  1458. /**
  1459. * Bulk update or insert orders
  1460. * Accepts an array with orders in the formats supported by
  1461. * WC_API_Orders->create_order() and WC_API_Orders->edit_order()
  1462. *
  1463. * @since 2.4.0
  1464. *
  1465. * @param array $data
  1466. *
  1467. * @return array|WP_Error
  1468. */
  1469. public function bulk( $data ) {
  1470. try {
  1471. if ( ! isset( $data['orders'] ) ) {
  1472. throw new WC_API_Exception( 'woocommerce_api_missing_orders_data', sprintf( __( 'No %1$s data specified to create/edit %1$s', 'woocommerce' ), 'orders' ), 400 );
  1473. }
  1474. $data = $data['orders'];
  1475. $limit = apply_filters( 'woocommerce_api_bulk_limit', 100, 'orders' );
  1476. // Limit bulk operation
  1477. if ( count( $data ) > $limit ) {
  1478. throw new WC_API_Exception( 'woocommerce_api_orders_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'woocommerce' ), $limit ), 413 );
  1479. }
  1480. $orders = array();
  1481. foreach ( $data as $_order ) {
  1482. $order_id = 0;
  1483. // Try to get the order ID
  1484. if ( isset( $_order['id'] ) ) {
  1485. $order_id = intval( $_order['id'] );
  1486. }
  1487. if ( $order_id ) {
  1488. // Order exists / edit order
  1489. $edit = $this->edit_order( $order_id, array( 'order' => $_order ) );
  1490. if ( is_wp_error( $edit ) ) {
  1491. $orders[] = array(
  1492. 'id' => $order_id,
  1493. 'error' => array( 'code' => $edit->get_error_code(), 'message' => $edit->get_error_message() ),
  1494. );
  1495. } else {
  1496. $orders[] = $edit['order'];
  1497. }
  1498. } else {
  1499. // Order don't exists / create order
  1500. $new = $this->create_order( array( 'order' => $_order ) );
  1501. if ( is_wp_error( $new ) ) {
  1502. $orders[] = array(
  1503. 'id' => $order_id,
  1504. 'error' => array( 'code' => $new->get_error_code(), 'message' => $new->get_error_message() ),
  1505. );
  1506. } else {
  1507. $orders[] = $new['order'];
  1508. }
  1509. }
  1510. }
  1511. return array( 'orders' => apply_filters( 'woocommerce_api_orders_bulk_response', $orders, $this ) );
  1512. } catch ( WC_Data_Exception $e ) {
  1513. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => 400 ) );
  1514. } catch ( WC_API_Exception $e ) {
  1515. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1516. }
  1517. }
  1518. }