· 6 years ago · Aug 19, 2019, 03:50 PM
1<?php
2
3include_once plugin_dir_path(__FILE__) . 'include/business_ru_api.php';
4
5class SyncBusinessRu
6{
7 protected $api;
8
9 public function __construct()
10 {
11 $this->api = $this->initial_api_settings();
12 }
13
14 /*
15 * Данные для работы с api
16 *
17 * */
18 private function initial_api_settings()
19 {
20 //params for api
21 $app_id = "943908";
22 $address = 'https://a93803.business.ru';
23 $secret_key = "cOwXG6CeDjjCad1N8cmIPNka8eBwbDpe"; // секретный ключ
24
25 $api = new Business_ru_api_lib($app_id, "", $address);
26 $api->setSecret($secret_key); // устанавливаем секретный ключ
27 $api->repair(); //устанавливаем token
28
29 return $api;
30 }
31
32 /*
33 * Синхронизация продуктов (wp_posts, wp_postmeta)
34 *
35 * @params:
36 * object $product
37 *
38 * */
39 public function sync_api_product($product)
40 {
41 if (empty($product))
42 return false;
43
44 $volume = get_post_meta($product->get_id(), "attribute_pa_volume");
45
46 if (!empty($volume))
47 $volume = preg_replace("/[^0-9\.]/", '', $volume[0]); //убираем буквы, и получаем объем (тип int)
48 else
49 $volume = null;
50
51 $image_path = explode("/", get_the_post_thumbnail_url($product->get_id()));
52
53 $current_product_params = [
54 "name" => $product->get_name(),
55 'part' => $product->get_sku() ?: null, //Артикул
56 'volume' => $volume,
57 'images' => [
58 [
59 "name" => end($image_path),
60 "url" => get_the_post_thumbnail_url($product->get_id())
61 ]
62 ]
63 ];
64
65 $price = get_post_meta($product->get_id(), "_price")[0];
66
67 if ($product->is_type('simple')) {
68
69 $product_data = $this->create_api_product($current_product_params); //создаем товар
70
71 if (!empty($product_data["result"]))
72 $product_data = $product_data["result"];
73 else
74 $product_data = $this->get_first_api_product_by_sku($current_product_params["part"]); //присваиваем существующие данные
75
76 $this->create_api_price($product_data["id"], $price); //создаем цену в смежном запросе
77
78 return true;
79
80 } elseif ($product->is_type('variable')) {
81
82 $table_api_modifications = "goodsmodifications";
83
84 $product_available_variations = $product->get_available_variations();
85
86 foreach ($product_available_variations as $variation) {
87
88 if ($variation["sku"] === "")
89 continue;
90
91 $goods_modifications = $this->api->request("get", $table_api_modifications, ["part" => $variation["sku"]]); //api
92
93 if (empty($goods_modifications["result"])) {
94
95 $product_data = $this->create_api_product($current_product_params); //создаем товар
96
97 if (!empty($product_data["result"]))
98 $product_data = $product_data["result"];
99 else
100 $product_data = $this->get_first_api_product_by_sku($current_product_params["part"]); //присваиваем существующие данные
101
102
103 if ($product_data["part"] == null)
104 break;
105
106 $variation_id = wc_get_product($variation["variation_id"]);
107
108 $variation_image_name = explode("/", $variation["image"]["url"]);
109
110 $goods_params = [
111 "name" => $variation_id->get_formatted_name(),
112 "part" => $variation["sku"],
113 "good_id" => $product_data["id"], //pay attention
114 'images' => [
115 [
116 'name' => end($variation_image_name),
117 'url' => $variation["image"]["url"]
118 ]
119 ]
120 ];
121
122 if ($product_data["part"] == $goods_params["part"])
123 continue;
124
125 $modification = $this->api->request("post", $table_api_modifications, $goods_params); //создаем модификацию
126
127 $this->create_api_price($product_data["id"], $price, $modification["result"]["id"]); //создаем цену в смежном запросе
128
129 }
130 break;
131 }
132 return true;
133 }
134 }
135
136 /*
137 * Получаем данные первого продукта
138 *
139 * @params:
140 * string $sku
141 *
142 * */
143 protected function get_first_api_product_by_sku($sku)
144 {
145 $response = $this->api->request("get", "goods", ["part" => $sku]);
146
147 if ($response["status"] == "ok")
148 return $response["result"][0];
149
150 }
151
152 /*
153 * Создание продукта
154 *
155 * @params:
156 * array $current_product_params
157 *
158 * */
159 protected function create_api_product(array $current_product_params)
160 {
161 $isCreateProduct = true;
162 $page = 1;
163 $table_api_goods = "goods"; //с какой таблицей в api работаем
164
165 do {
166 $goods = $this->api->request("get", $table_api_goods, ["page" => $page++]); //api
167
168 if ($goods["status"] == "ok") {
169
170 foreach ($goods["result"] as $good) {
171 if ($current_product_params["part"] == null) {
172 $isCreateProduct = false;
173 break;
174 }
175
176 if ($good["part"] != null) {
177 if ($good["part"] == $current_product_params["part"]) {
178 $isCreateProduct = false;
179 break;
180 }
181 }
182 }
183 } else {
184 break;
185 }
186 } while (count($goods['result']) > 0); // делаем это до тех пор пока не проверим все продукты
187
188 if ($isCreateProduct) {
189 return $this->api->request("post", $table_api_goods, $current_product_params); //создаем товар
190 }
191 return ["result" => [], "text" => "Продукт не был создан, вероятно уже существует"];
192 }
193
194
195/*
196 * Создание цены (занесения в разные таблицы по api)
197 *
198 * @params:
199 * string $product_id,
200 * int price,
201 * string $modification_id
202 * */
203 protected function create_api_price($product_id, $price, $modification_id = null)
204 {
205 $sale_price_list_goods_request = $this->api->request("get", "salepricelistgoods", ["good_id" => $product_id]);
206
207
208 if (empty($sale_price_list_goods_request["result"])) {
209
210 $sale_price_lists_request = $this->api->request("post", "salepricelists", [
211 'responsible_employee_id' => '75927',
212 'organization_id' => '75537',
213 'owner_employee_id' => '75927'
214 ]);
215
216 $sale_price_list_params = [
217 "good_id" => $product_id,
218 "measure_id" => 1, //'штуки'
219 "price_list_id" => $sale_price_lists_request["result"]["id"],
220 "modification_id" => $modification_id
221 ];
222
223 $sale_price_list_result = $this->api->request("post", "salepricelistgoods", $sale_price_list_params);
224
225
226 $price_list_good_id = $sale_price_list_result["result"]["id"];
227
228
229 $list_price_good_data = $this->api->request("get", "salepricelistgoodprices", ["price_list_good_id" => $price_list_good_id]);
230
231 if (empty($list_price_good_data["result"])) {
232 $sale_price_type_params = [
233 "price_type_id" => 75543,//Отпускные Интернет-Магазин
234 "price" => $price,
235 "price_list_good_id" => $price_list_good_id
236 ];
237 $sale_price_type_params2 = [
238 "price_type_id" => 87833, //Отпускная минимальная
239 "price" => $price,
240 "price_list_good_id" => $price_list_good_id
241 ];
242
243 $this->api->request("post", "salepricelistgoodprices", $sale_price_type_params);
244
245 $this->api->request("post", "salepricelistgoodprices", $sale_price_type_params2); //2 request
246 }
247 }
248 }
249}