BillzRest.php 11.3 KB
Newer Older
Kulya's avatar
Kulya committed
1 2
<?php namespace AloVoice;
use AloVoice\AloVoiceConnector as ALVC;
Kulya's avatar
Kulya committed
3

Kulya's avatar
Kulya committed
4 5 6 7 8 9 10 11 12
require_once (__DIR__.'/keys.php');
// define('C_REST_CLIENT_ID','local.5ffda24a2b70f7.09456768'); // LocalApp 
// define('C_REST_CLIENT_SECRET','z2FVT3DfjUrcnokbT0ogrcCRJby0C4e60MRciRcSfNpateh3FB'); //Application key

	class BillzRest
	{
		const VERSION = '1.1';
		const TYPE_TRANSPORT = 'json';

Kulya's avatar
Kulya committed
13 14 15 16 17 18 19 20 21 22 23 24 25
		
		public static function getProducts($data=false) {
			
			if(!empty($data)) {
				$sdata = $data;
			}
			else {
				$sdata = date("Y-m-d")."T".date("H").":00:00Z";
			}
			
			$getParams = [
				"LastUpdatedDate" => $sdata,
				"WithProductPhotoOnly" => 0,
Kulya's avatar
Kulya committed
26
				"IncludeEmptyStocks" => 1 //0
Kulya's avatar
Kulya committed
27 28 29
			];
			$result = static::callCurl("products.get",$getParams);
			
30
			// print_r($getParams);
Kulya's avatar
Kulya committed
31 32 33
			
			return $result;
		}
Kulya's avatar
Kulya committed
34
		
Kulya's avatar
Kulya committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
		public static function createClient($params=false) {
			/*
			{
			  "jsonrpc": "2.0",
			  "method": "client.create",
			  "params": {
				  "phone": "998931830000",
				  "firstName": "Ivanoff",
				  "lastName": "Fedor",
				  "gender": 0,
				  "birthDate":"1980-08-12T00:00:00Z"
				  },
				  "id": "1200"
				}
			*/
Kulya's avatar
Kulya committed
50 51

			$result = static::callCurl("client.create",$params);
Kulya's avatar
Kulya committed
52 53 54 55
			return $result;
			
		}
		
Kulya's avatar
Kulya committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
		public static function createOrder($params=false) {
			/*
			order_id
			paytype
			datePaid
			products
				office_id (todo select from billz)
				id
				billz_id
				name
				barcode
				sku
				quantity
				price (optional)
				discount (optional)
			*/
			
			$qPparams['subTotalPrice'] = 0;
			$arProducts = [];
Kulya's avatar
Kulya committed
75
				
Kulya's avatar
Kulya committed
76 77 78 79
			foreach($params["products"] as $prd){
				$price = (!empty($prd["price"])) ? $prd["price"] : 0;
				$dsnt = (!empty($prd["discount"])) ? $prd["discount"] : 0;
				$arProducts[] = [
Kulya's avatar
Kulya committed
80
					"billzOfficeID" => $prd["office_id"],
Kulya's avatar
Kulya committed
81 82
					"billzProductID" => $prd["billz_id"],
					"productID" => $prd["id"],
Kulya's avatar
Kulya committed
83 84 85
					// "name" => $prd["name"],
					// "barCode" => $prd["barcode"],
					// "sku" => $prd["sku"],
Kulya's avatar
Kulya committed
86 87 88 89 90 91 92
					"qty" => $prd["quantity"],
					"subTotalPrice" => $price,
					"discountAmount" => $dsnt,
					"totalPrice" => $price-$dsnt,
				];
				$qPparams['subTotalPrice'] = $qPparams['subTotalPrice']+$price;
			}
Kulya's avatar
Kulya committed
93
			if(!empty($params["client_id"])){
Kulya's avatar
Kulya committed
94
				$qPparams['clientId'] = (int)$params["client_id"];
Kulya's avatar
Kulya committed
95
			}
Kulya's avatar
Kulya committed
96
			$qPparams['parked'] = false;
Kulya's avatar
Kulya committed
97
			$qPparams['orderID'] = (int)$params["order_id"];
Kulya's avatar
Kulya committed
98
			$qPparams['dateCreated'] = date('Y-m-d').'T'.date('H:i:s').'Z';
Kulya's avatar
Kulya committed
99
			$qPparams['datePaid'] = date('Y-m-d').'T'.date('H:i:s').'Z';
Kulya's avatar
Kulya committed
100 101 102 103 104 105 106
			$qPparams['products'] = $arProducts;
			$qPparams['paymentMethod'] = "payme"; //$params["paytype"];
			// $params['datePaid'] = date('Y-m-d').'T'.date('H:i:s').'Z'; // ??
			
			if(!empty($qPparams['discount'])){
				$qPparams['discountAmount'] = $qPparams['discount'];
			}
Kulya's avatar
Kulya committed
107

Kulya's avatar
Kulya committed
108 109 110 111 112 113 114
			$qPparams['totalPrice'] = (!empty($qPparams['discountAmount'])) ? $qPparams['subTotalPrice']-$qPparams['discount'] : $qPparams['subTotalPrice'];
			
			
			$result = static::callCurl("orders.create",$qPparams);
			return $result;
		}
		
Kulya's avatar
Kulya committed
115
		public static function getCatalog($page=1,$cnt=1) {
Kulya's avatar
Kulya committed
116
			$catalogParams = [
Kulya's avatar
Kulya committed
117
				'Filter.barCode' => '4780058100438',
Kulya's avatar
Kulya committed
118 119 120 121 122 123 124
				"PerPage" => (int)$cnt,
				"Page" => (int)$page,
				"Sort" => [
					"type" => "num",
					"field" => "id",
					"order" => "desc"
				]
Kulya's avatar
Kulya committed
125
			];
Kulya's avatar
Kulya committed
126
			// $catalogParams = [ 'Filter.BarCodes' => '4780058100438' ];
Kulya's avatar
Kulya committed
127 128
			
			$result = static::callCurl("catalog.get",$catalogParams);
Kulya's avatar
Kulya committed
129 130
			return $result;
		}
Kulya's avatar
Kulya committed
131 132 133 134 135 136 137 138
		
		public static function getClient($phone) {

			$result = static::callCurl("client.search",[
				"phoneNumber" => $phone
			]);
			return $result;
		}
Kulya's avatar
Kulya committed
139 140 141 142 143 144 145 146

		public static function base64_url_encode($input) {
			return trim(strtr(base64_encode($input), '+/', '-_'), '=');
		}
		
		public static function connectionSettings(){
			
			$conf = self::getAppSettings();
Kulya's avatar
Kulya committed
147 148
			$now = time()-100;
			$exp = $now+1500000;
Kulya's avatar
Kulya committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
			
			$headerArray = array(
				'typ'=> 'JWT',
				'alg'=> 'HS256'
			);
			$payloadArray = array(
			  'iss'=> $conf["iss"],
			  'iat'=> $now,
			  'exp'=> $exp,
			  'sub'=> $conf["sub"]
			);

			$header = self::base64_url_encode(json_encode($headerArray, JSON_FORCE_OBJECT));
			$payload = self::base64_url_encode(json_encode($payloadArray, JSON_FORCE_OBJECT));

			$unsignedToken = $header .'.'. $payload;

			$signature = hash_hmac("sha256", $unsignedToken, $conf["secret"], true);
			$encodedSignature = self::base64_url_encode($signature);
			$token = $unsignedToken . '.' . $encodedSignature;
Kulya's avatar
Kulya committed
169
			
Kulya's avatar
Kulya committed
170 171 172
			// $conf["token"] = $token; //, "url"=>$conf["url"]];
			// return $conf;
			return ["token" => $token, "url"=>$conf["url"], "apiversion"=>$conf["apiversion"]];
Kulya's avatar
Kulya committed
173 174 175 176 177 178 179
		}
		


		public static function getAppSettings()
		{
			return [
Kulya's avatar
Kulya committed
180
				// "url" => "https://api.billz.uz/v4/",
Kulya's avatar
Kulya committed
181 182
				"apiversion" => "v4",
				"url" => "https://api.billz.uz/",
Kulya's avatar
Kulya committed
183 184 185 186 187 188
				"iss" => "qam.bitrix24.ru",
				"sub" => "qamar.bitrix24",
				"secret" => "iRPiwoNhnyhyyLMtADtINSuxHyVmsrXpvtejrAuERdyhhj2EPtMxUorppLUnELVhRmIpnGWsHSpwCzCWsjJLENekd9WumpLjPHvUQDwWmcuwotmhvEyIzzSVkejywICwzKrSDXucLE3SGQtyDVcmpeFBneSMmxuKMjo6Q2kGIGbfQkupBm3mMGXmPIEpwMNYNV38VcemDd6fPYQnRcyYERXctSGMTXFwdmDLoYBE6btCfNZfkdoBFmbhpQJpBkifPUScyQRGeRbkFxjEwvnXjhCSCMbpkjjfWkFeesnPupKkiKKKL8MkSKx6HuRIzbmbcGNJNWtrkx3sSM1MjPzCTiWE2wM1SZQWVYu8hDBVUVDKxBeRisKTjjeidboGWJNhWcpzQEJe4cMSjBvNNxxBiveZ0iDdMpcSYsJNfoVTT8mSkavRzmHeeSGXKSDDTmwjUwfoPsHhWJTt7BrauLIRhIrjKnsYZscNvSGYRDyVwBXaS8YfELUBUMSFjYnpjJVs"
			];
		}

Kulya's avatar
Kulya committed
189 190 191 192 193 194 195 196 197 198 199 200
		protected static function callCurl($method,$params=[])
		{
			if(!function_exists('curl_init'))
			{
				return [
					'error'             => 'error_php_lib_curl',
					'error_information' => 'need install curl lib'
				];
			}
			
			
			$arSettings = static::connectionSettings();
Kulya's avatar
Kulya committed
201
			
Kulya's avatar
Kulya committed
202 203
			// $result = [ "settings" => $arSettings ];
			$result = [];
Kulya's avatar
Kulya committed
204 205
			if(!empty($arSettings))
			{
Kulya's avatar
Kulya committed
206
				if($method=="orders.create") { $arSettings["apiversion"]="v3"; } //v2
207
				if($method=="client.create") { $arSettings["apiversion"]="v1"; }
Kulya's avatar
Kulya committed
208
				if($method=="catalog.get") { $arSettings["apiversion"]="v2"; }
Kulya's avatar
Kulya committed
209
				
Kulya's avatar
Kulya committed
210
				$url = $arSettings["url"].$arSettings["apiversion"]."/";
Kulya's avatar
Kulya committed
211 212 213 214 215 216
				
				$arData = [
					'jsonrpc' => '2.0',
					'method' => $method,
					'params' => $params,
				];
217
				
218
				$sendData = json_encode($arData);
Kulya's avatar
Kulya committed
219
				ALVC::eLog($sendData,"------ Billz :: curl req_Orig:");
220 221
				
				
Kulya's avatar
Kulya committed
222
				$result["params"] = $sendData;
Kulya's avatar
Kulya committed
223
				$result["url"] = $url;
224
				// ob_start();
Kulya's avatar
Kulya committed
225 226 227
				try
				{
					$obCurl = curl_init();
Kulya's avatar
Kulya committed
228
	
Kulya's avatar
Kulya committed
229
					curl_setopt_array($obCurl, array(
Kulya's avatar
Kulya committed
230
					  CURLOPT_URL => $url,
Kulya's avatar
Kulya committed
231
					  // CURLOPT_USERAGENT => "TugBitrix24",
Kulya's avatar
Kulya committed
232 233 234 235 236 237 238 239 240 241
					  CURLOPT_RETURNTRANSFER => true,
					  CURLOPT_ENCODING => '',
					  CURLOPT_MAXREDIRS => 10,
					  CURLOPT_TIMEOUT => 0,
					  CURLOPT_FOLLOWLOCATION => true,
					  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					  CURLOPT_CUSTOMREQUEST => 'GET',
					  CURLOPT_POSTFIELDS =>$sendData,
					  CURLOPT_SSL_VERIFYPEER =>false,
					  CURLOPT_SSL_VERIFYHOST =>false,
242
					  CURLOPT_NOPROGRESS => false ,
243
					  CURLOPT_PROGRESSFUNCTION => array("\AloVoice\BillzRest", 'curlprogress'),
Kulya's avatar
Kulya committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
					  CURLOPT_HTTPHEADER => array(
						'Authorization: Bearer '.$arSettings["token"],
						'Content-Type: application/json'
					  ),
					));
					
					
					
					// curl_setopt($obCurl, CURLOPT_URL, $url);
					// curl_setopt($obCurl, CURLOPT_RETURNTRANSFER, true);
					// curl_setopt($obCurl, CURLOPT_POSTREDIR, 10);
					// curl_setopt($obCurl, CURLOPT_USERAGENT, 'Bitrix24' . static::VERSION);
					// curl_setopt($obCurl, CURLOPT_POST, true);
					// curl_setopt($obCurl, CURLOPT_POSTFIELDS, $sendData);
					// curl_setopt($obCurl, CURLOPT_FOLLOWLOCATION, 1);
					// curl_setopt($obCurl, CURLOPT_SSL_VERIFYPEER, false);
					// curl_setopt($obCurl, CURLOPT_SSL_VERIFYHOST, false);
					
					// $headers = array();
					// $headers[] = "Content-Type: application/json; charset=UTF-8";
					// $headers[] = "Authorization: Bearer ".$arSettings["token"];
					// $headers[] = "Cache-Control: no-cache";
					// curl_setopt($obCurl, CURLOPT_HTTPHEADER, $headers);
Kulya's avatar
Kulya committed
267 268 269

					$out = curl_exec($obCurl);
					$info = curl_getinfo($obCurl);
Kulya's avatar
Kulya committed
270

Kulya's avatar
Kulya committed
271
					// static::setLog( $headers, '--==== billzCurl HEADRES:' );
Kulya's avatar
Kulya committed
272
					static::setLog( $out, '--==== billzCurl OUT:' );
Kulya's avatar
Kulya committed
273 274 275 276 277 278 279 280 281
					
					if(curl_errno($obCurl))	{
						$result[ 'curl_error' ] = curl_error($obCurl);
					}
					else {
						$result["answer"] = static::expandData($out);
					}
					curl_close($obCurl);
					
282
					// static::setLog( $result, 'billzCurl' );
Kulya's avatar
Kulya committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

				}
				catch(Exception $e)
				{
					static::setLog(
						[
							'message' => $e->getMessage(),
							'code' => $e->getCode(),
							'trace' => $e->getTrace(),
							'params' => $arData
						],
						'exceptionBillz'
					);

					return [
						'error' => 'exception',
						'error_exception_code' => $e->getCode(),
						'error_information' => $e->getMessage(),
					];
				}
303
				
Kulya's avatar
Kulya committed
304 305 306 307
			}
			

			return $result;
308
			
309 310 311
			
		}
		
312
		public static function curlprogress($resource,$download_size, $downloaded, $upload_size, $uploaded){
313
			if($download_size > 0){
314 315 316
				// echo $downloaded / $download_size  * 100;
				$percDwn = $downloaded / $download_size  * 100;
				echo "\r Загружено: \033[32m".$percDwn."% \033[0m [\033[36m".$downloaded."\033 из 0m/".$download_size."...";
317 318
				// ob_flush();
				// flush();
319
			}
Kulya's avatar
Kulya committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
		}
		/**
		 * @var $data mixed
		 * @var $encoding boolean true - encoding to utf8, false - decoding
		 *
		 * @return string json_encode with encoding
		 */
		protected static function changeEncoding($data, $encoding = true)
		{
			if(is_array($data))
			{
				$result = [];
				foreach ($data as $k => $item)
				{
					$k = static::changeEncoding($k, $encoding);
					$result[$k] = static::changeEncoding($item, $encoding);
				}
			}
			else
			{
				if($encoding)
				{
					$result = iconv(C_REST_CURRENT_ENCODING, "UTF-8//TRANSLIT", $data);
				}
				else
				{
					$result = iconv( "UTF-8",C_REST_CURRENT_ENCODING, $data);
				}
			}

			return $result;
		}

		/**
		 * @var $data mixed
		 * @var $debag boolean
		 *
		 * @return string json_encode with encoding
		 */
		protected static function wrapData($data, $debag = false)
		{
			if(defined('C_REST_CURRENT_ENCODING'))
			{
				$data = static::changeEncoding($data, true);
			}
			$return = json_encode($data, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT);

			if($debag)
			{
				$e = json_last_error();
				if ($e != JSON_ERROR_NONE)
				{
					if ($e == JSON_ERROR_UTF8)
					{
						return 'Failed encoding! Recommended \'UTF - 8\' or set define C_REST_CURRENT_ENCODING = current site encoding for function iconv()';
					}
				}
			}

			return $return;
		}

		/**
		 * @var $data mixed
		 * @var $debag boolean
		 *
		 * @return string json_decode with encoding
		 */
		protected static function expandData($data)
		{
			$return = json_decode($data, true);
			if(defined('C_REST_CURRENT_ENCODING'))
			{
				$return = static::changeEncoding($return, false);
			}
			return $return;
		}

		/**
		 * Can overridden this method to change the data storage location.
		 *
		 * @var $arSettings array settings application
		 * @return boolean is successes save data for setSettingData()
		 */

		protected static function setSettingData($arSettings)
		{
			return  (boolean)file_put_contents(__DIR__ . '/settings.json', static::wrapData($arSettings));
		}

		/**
		 * Can overridden this method to change the log data storage location.
		 *
		 * @var $arData array of logs data
		 * @var $type   string to more identification log data
		 * @return boolean is successes save log data
		 */

		public static function setLog($arData, $type = '')
		{
Kulya's avatar
Kulya committed
420
			ALVC::eLog($arData,$type,"billzRest");
Kulya's avatar
Kulya committed
421 422 423 424
		}

		
	}