-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.php
executable file
·184 lines (156 loc) · 6.1 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
<?php
/**
* Обертка для вызова API Бонус+
*
* @param $endpoint variant
* @param $params array
* @param $type variant
*/
function bpwp_api_request($endpoint, $params, $type)
{
$token = get_option('bpwp_api_key');
if (empty($endpoint) || empty($type) || empty($token))
return;
$url = 'https://bonusplus.pro/api/' . $endpoint;
$token = base64_encode($token);
if ($type == 'GET'){
if (!empty($params) & is_array($params)) {
foreach ($params as $key => $value) {
$url = add_query_arg(array($key => $value), $url);
}
}
$args = array(
'method' => $type,
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'ApiKey ' . $token,
),
);
}
if ($type == 'POST') {
$args = array(
'method' => $type,
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'ApiKey ' . $token,
),
'body' => $params,
);
}
if ($type == 'PUT') {
$args = array(
'method' => $type,
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'ApiKey ' . $token,
),
'body' => $params,
);
$args['headers']['Content-Length'] = strlen( $args['body'] ?: '' ); // Добавим Content-Length. Важно, если body пустой
}
if ($type == 'PATCH') {
$args = array(
'method' => $type,
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'ApiKey ' . $token,
),
'body' => $params,
);
}
$request = wp_remote_request($url, $args);
$response_code = wp_remote_retrieve_response_code($request);
if (is_wp_error($request)) {
$response['code'] = $request->get_error_code();
$response['message'] = $request->get_error_message();
$response['request'] = $request;
$response['class'] = 'notice notice-error';
}
$response['code'] = $response_code;
$response['message'] = bpwp_api_get_error_msg($response_code);
if (!in_array($response_code, [200, 204])){
$response['request'] = $request;
$response['class'] = 'notice notice-warning';
} else {
$response['request'] = json_decode($request['body'], true);
$response['class'] = 'notice notice-success';
}
return $response;
}
/**
* Return customer billing phone
*/
function bpwp_api_get_customer_phone($customer_id = '')
{
if (empty($customer_id) && is_user_logged_in()) {
$customer_id = get_current_user_id();
}
$phone = get_user_meta($customer_id, 'billing_phone', true);
$phone = apply_filters('bpwp_api_filter_get_customer_phone', $phone);
return $phone;
}
/**
* Return customer bonus data
*
* $customer_id int ID Клиента
*
*/
function bpwp_api_get_customer_data($customer_id = '')
{
if (empty($customer_id) && is_user_logged_in()) {
$customer_id = get_current_user_id();
}
$bonusData = get_user_meta($customer_id, 'bonus-plus', true);
$data = [];
if (!empty($bonusData) && is_array($bonusData)){
foreach ($bonusData as $key => $value){
if ($key != 'person'){
$data[$key] = $value;
} else {
$_person = $value;
foreach ($_person as $pkey=>$pvalue){
$data[$pkey] = $pvalue;
}
}
}
}
return $data;
}
/**
* Get the error message for a given code.
*
* @param int $code The error code.
* @return string|false The error message, or false if not found.
*/
function bpwp_api_get_error_msg($code)
{
$errors = [
400 => __('Ошибка в структуре JSON передаваемого запроса', 'bonus-plus-wp'),
401 => __('Не удалось аутентифицировать запрос. Возможные причины: схема аутентификации или токен указаны неверно; отсутствует заголовок Authorization в запросе;', 'bonus-plus-wp'),
403 => __('Нет прав на просмотр данного объекта', 'bonus-plus-wp'),
404 => __('Запрошенный ресурс не существует', 'bonus-plus-wp'),
412 => __('В процессе обработки запроса произошла ошибка связанная с: некорректными данными в параметрах запроса; невозможностью выполнить данное действие; по каким-то другим причинам', 'bonus-plus-wp'),
500 => __('При обработке запроса возникла непредвиденная ошибка', 'bonus-plus-wp'),
204 => __('Товары и категории успешно импортированы', 'bonus-plus-wp'),
200 => __('ОК!', 'bonus-plus-wp'),
];
return $code && key_exists($code, $errors) ? $errors[$code] : false;
}
// Запишем bpwp_debit_bonuses в WC()->session
add_action( 'wp_ajax_set_bpwp_debit_bonuses', 'set_bpwp_debit_bonuses' );
add_action( 'wp_ajax_nopriv_set_bpwp_debit_bonuses', 'set_bpwp_debit_bonuses' );
function set_bpwp_debit_bonuses() {
if (!is_user_logged_in()) {
return;
}
$user_id = get_current_user_id();
$bonuses = get_user_meta($user_id, 'bpwp_debit_bonuses', true);
$max_debit_bonuses = get_user_meta($user_id, 'bpwp_max_debit_bonuses', true);
$debit_bonuses = $bonuses <= $max_debit_bonuses ? $bonuses : $max_debit_bonuses;
if( true == $_POST['bonuses'] && isset($bonuses) && isset($bonuses) > 0 ){
delete_user_meta($user_id, 'bpwp_debit_bonuses');
WC()->session->set( 'bpwp_debit_bonuses', $debit_bonuses );
echo true;
}
exit();
}