class-wc-api-orders.php 60 KB

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