· 6 years ago · Aug 18, 2019, 09:46 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 private function initial_api_settings()
15 {
16 //params for api
17 $app_id = "943908";
18 $address = 'https://a93803.business.ru';
19 $secret_key = "cOwXG6CeDjjCad1N8cmIPNka8eBwbDpe"; // секретный ключ
20
21 $api = new Business_ru_api_lib($app_id, "", $address);
22 $api->setSecret($secret_key); // устанавливаем секретный ключ
23 $api->repair(); //устанавливаем token
24
25 return $api;
26 }
27
28 public function sync_api_product($product)
29 {
30 if (empty($product))
31 return false;
32
33 $volume = get_post_meta($product->get_id(), "attribute_pa_volume");
34
35 if (!empty($volume))
36 $volume = preg_replace("/[^0-9\.]/", '', $volume[0]); //убираем буквы, и получаем объем (тип int)
37 else
38 $volume = null;
39
40 $image_path = explode("/", get_the_post_thumbnail_url($product->get_id()));
41
42 $current_product_params = [
43 "name" => $product->get_name(),
44 "cost" => get_post_meta($product->get_id(), "_price")[0],
45 'part' => $product->get_sku() ?: null, //Артикул
46 'volume' => $volume,
47 'images' => [
48 [
49 "name" => end($image_path),
50 "url" => get_the_post_thumbnail_url($product->get_id())
51 ]
52 ],
53 "type_simple" => $product->is_type('simple')
54 ];
55
56 if ($product->is_type('simple')) {
57 $this->create_api_product($current_product_params);
58
59 return true;
60 } elseif ($product->is_type('variable')) {
61
62 $table_api_modifications = "goodsmodifications";
63
64 $product_available_variations = $product->get_available_variations();
65
66 foreach ($product_available_variations as $variation) {
67
68 if ($variation["sku"] === "")
69 continue;
70
71 $goods_modifications = $this->api->request("get", $table_api_modifications, ["part" => $variation["sku"]]); //api
72
73 if (empty($goods_modifications["result"])) {
74
75 $product_data = $this->create_api_product($current_product_params); //создаем товар
76
77 if (!empty($product_data["result"]))
78 $product_data = $product_data["result"];
79 else
80 $product_data = $this->get_first_api_product_by_sku($current_product_params["part"]); //присваиваем существующие данные
81
82
83 if ($product_data["part"] == null)
84 break;
85
86 $variation_id = wc_get_product($variation["variation_id"]);
87
88 $variation_image_name = explode("/", $variation["image"]["url"]);
89
90 $goods_params = [
91 "name" => $variation_id->get_formatted_name(),
92 "part" => $variation["sku"],
93 "good_id" => $product_data["id"], //pay attention
94 'images' => [
95 [
96 'name' => end($variation_image_name),
97 'url' => $variation["image"]["url"]
98 ]
99 ]
100 ];
101
102 if ($product_data["part"] == $goods_params["part"])
103 continue;
104
105 $this->api->request("post", $table_api_modifications, $goods_params); //создаем модификацию
106 }
107 break;
108 }
109 return true;
110 }
111 }
112
113 /*
114 * Получаем данные первого продукта
115 *
116 * @params:
117 * string $sku
118 *
119 * */
120 private function get_first_api_product_by_sku($sku)
121 {
122 $response = $this->api->request("get", "goods", ["part" => $sku]);
123
124 if ($response["status"] == "ok")
125 return $response["result"][0];
126
127 }
128
129 /*
130 * Создание продукта
131 *
132 * @params:
133 * array $current_product_params
134 *
135 * */
136 private function create_api_product(array $current_product_params)
137 {
138 $isCreateProduct = true;
139 $page = 1;
140 $table_api_posts = "goods"; //с какой таблицей в api работаем
141
142 do {
143 $goods = $this->api->request("get", $table_api_posts, ["page" => $page++]); //api
144
145 if ($goods["status"] == "ok") {
146
147 foreach ($goods["result"] as $good) {
148 if ($current_product_params["part"] == null) {
149 $isCreateProduct = false;
150 break;
151 }
152
153 if ($good["part"] != null) {
154 if ($good["part"] == $current_product_params["part"]) {
155 $isCreateProduct = false;
156 break;
157 }
158 }
159 }
160 } else {
161 break;
162 }
163 } while (count($goods['result']) > 0); // делаем это до тех пор пока не проверим все продукты
164
165 if ($isCreateProduct) {
166 return $this->api->request("post", $table_api_posts, $current_product_params); //создаем товар
167 }
168 return ["result" => [], "text" => "Продукт не был создан, вероятно уже существует"];
169 }
170
171}