1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace WC_POS;
13
14 class Ajax {
15
16 17 18
19 public function __construct() {
20
21 $ajax_events = array(
22 'toggle_legacy_server' => '\WC_POS\Status'
23 );
24
25 foreach ( $ajax_events as $ajax_event => $class ) {
26
27 add_action( 'wp_ajax_wc_pos_' . $ajax_event, array( $this, 'check_ajax_referer' ), 1 );
28
29 add_action( 'wp_ajax_wc_pos_' . $ajax_event, array( $class, $ajax_event ) );
30 }
31 }
32
33 34 35
36 static public function check_ajax_referer(){
37 $pass = check_ajax_referer( PLUGIN_NAME, 'security', false );
38 if(!$pass){
39 $result = new \WP_Error(
40 'woocommerce_pos_invalid_nonce',
41 __( 'Invalid security nonce', 'woocommerce-pos' ),
42 array( 'status' => 401 )
43 );
44 self::response($result);
45 }
46 }
47
48
49 50 51 52 53 54 55 56
57 static public function response($result){
58 header( 'Content-Type: application/json; charset=utf-8' );
59 if (is_wp_error($result)) {
60 $data = $result->get_error_data();
61 if ( is_array( $data ) && isset( $data['status'] ) ) {
62 status_header( $data['status'] );
63 }
64 $result = self::error_to_array( $result );
65 }
66 echo json_encode( $result );
67 die();
68 }
69 70 71 72 73
74 static private function error_to_array( $error ) {
75 $errors = array();
76 foreach ( (array) $error->errors as $code => $messages ) {
77 foreach ( (array) $messages as $message ) {
78 $errors[] = array( 'code' => $code, 'message' => $message );
79 }
80 }
81 return array( 'errors' => $errors );
82 }
83
84 }