BillzRest.php 10.8 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 50 51 52 53 54 55 56 57 58
		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"
				}
			*/
			
			$client_params = [ "firstName" => (!empty($params["NAME"])) ? $params["NAME"] : "New Client"];
			// if(!empty())
			
			$result = static::callCurl("client.create",$client_params);
			return $result;
			
		}
		
Kulya's avatar
Kulya committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
		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
78
				
Kulya's avatar
Kulya committed
79 80 81 82 83 84 85
			foreach($params["products"] as $prd){
				$price = (!empty($prd["price"])) ? $prd["price"] : 0;
				$dsnt = (!empty($prd["discount"])) ? $prd["discount"] : 0;
				$arProducts[] = [
					"billzOfficeID" => $prd["office_id"],
					"billzProductID" => $prd["billz_id"],
					"productID" => $prd["id"],
Kulya's avatar
Kulya committed
86 87 88
					// "name" => $prd["name"],
					// "barCode" => $prd["barcode"],
					// "sku" => $prd["sku"],
Kulya's avatar
Kulya committed
89 90 91 92 93 94 95 96 97 98
					"qty" => $prd["quantity"],
					"subTotalPrice" => $price,
					"discountAmount" => $dsnt,
					"totalPrice" => $price-$dsnt,
				];
				$qPparams['subTotalPrice'] = $qPparams['subTotalPrice']+$price;
			}
			
			$qPparams['orderID'] = $params["order_id"];
			$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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
		public static function getCatalog($page=1,$cnt=1) {

			$result = static::callCurl("catalog.get",[
				"PerPage" => (int)$cnt,
				"Page" => (int)$page,
				"Sort" => [
					"type" => "num",
					"field" => "id",
					"order" => "desc"
				]
			]);
			return $result;
		}

		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
136 137
			$now = time()-100;
			$exp = $now+1500000;
Kulya's avatar
Kulya committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
			
			$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
158
			
Kulya's avatar
Kulya committed
159 160 161
			// $conf["token"] = $token; //, "url"=>$conf["url"]];
			// return $conf;
			return ["token" => $token, "url"=>$conf["url"], "apiversion"=>$conf["apiversion"]];
Kulya's avatar
Kulya committed
162 163 164 165 166 167 168
		}
		


		public static function getAppSettings()
		{
			return [
Kulya's avatar
Kulya committed
169
				// "url" => "https://api.billz.uz/v4/",
Kulya's avatar
Kulya committed
170 171
				"apiversion" => "v4",
				"url" => "https://api.billz.uz/",
Kulya's avatar
Kulya committed
172 173 174 175 176 177
				"iss" => "qam.bitrix24.ru",
				"sub" => "qamar.bitrix24",
				"secret" => "iRPiwoNhnyhyyLMtADtINSuxHyVmsrXpvtejrAuERdyhhj2EPtMxUorppLUnELVhRmIpnGWsHSpwCzCWsjJLENekd9WumpLjPHvUQDwWmcuwotmhvEyIzzSVkejywICwzKrSDXucLE3SGQtyDVcmpeFBneSMmxuKMjo6Q2kGIGbfQkupBm3mMGXmPIEpwMNYNV38VcemDd6fPYQnRcyYERXctSGMTXFwdmDLoYBE6btCfNZfkdoBFmbhpQJpBkifPUScyQRGeRbkFxjEwvnXjhCSCMbpkjjfWkFeesnPupKkiKKKL8MkSKx6HuRIzbmbcGNJNWtrkx3sSM1MjPzCTiWE2wM1SZQWVYu8hDBVUVDKxBeRisKTjjeidboGWJNhWcpzQEJe4cMSjBvNNxxBiveZ0iDdMpcSYsJNfoVTT8mSkavRzmHeeSGXKSDDTmwjUwfoPsHhWJTt7BrauLIRhIrjKnsYZscNvSGYRDyVwBXaS8YfELUBUMSFjYnpjJVs"
			];
		}

Kulya's avatar
Kulya committed
178 179 180 181 182 183 184 185 186 187 188 189
		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
190
			
Kulya's avatar
Kulya committed
191 192
			// $result = [ "settings" => $arSettings ];
			$result = [];
Kulya's avatar
Kulya committed
193 194
			if(!empty($arSettings))
			{
Kulya's avatar
Kulya committed
195
				if($method=="orders.create") { $arSettings["apiversion"]="v2"; }
Kulya's avatar
Kulya committed
196
				
Kulya's avatar
Kulya committed
197
				$url = $arSettings["url"].$arSettings["apiversion"]."/";
Kulya's avatar
Kulya committed
198 199 200 201 202 203 204 205 206 207 208
				
				$arData = [
					'jsonrpc' => '2.0',
					'method' => $method,
					'params' => $params,
				];
				
				
				
				$sendData = json_encode($arData);
				$result["params"] = $sendData;
Kulya's avatar
Kulya committed
209
				$result["url"] = $url;
210
				// ob_start();
Kulya's avatar
Kulya committed
211 212 213
				try
				{
					$obCurl = curl_init();
Kulya's avatar
Kulya committed
214
	
Kulya's avatar
Kulya committed
215
					curl_setopt_array($obCurl, array(
Kulya's avatar
Kulya committed
216
					  CURLOPT_URL => $url,
Kulya's avatar
Kulya committed
217
					  // CURLOPT_USERAGENT => "TugBitrix24",
Kulya's avatar
Kulya committed
218 219 220 221 222 223 224 225 226 227
					  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,
228
					  CURLOPT_NOPROGRESS => false ,
229
					  CURLOPT_PROGRESSFUNCTION => array("\AloVoice\BillzRest", 'curlprogress'),
Kulya's avatar
Kulya committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
					  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
253 254 255

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

257 258
					// static::setLog( $headers, '--==== billzCurl HEADRES:' );
					// static::setLog( $out, '--==== billzCurl OUT:' );
Kulya's avatar
Kulya committed
259 260 261 262 263 264 265 266 267
					
					if(curl_errno($obCurl))	{
						$result[ 'curl_error' ] = curl_error($obCurl);
					}
					else {
						$result["answer"] = static::expandData($out);
					}
					curl_close($obCurl);
					
268
					// static::setLog( $result, 'billzCurl' );
Kulya's avatar
Kulya committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

				}
				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(),
					];
				}
289
				
Kulya's avatar
Kulya committed
290 291 292 293
			}
			

			return $result;
294
			
295 296 297
			
		}
		
298
		public static function curlprogress($resource,$download_size, $downloaded, $upload_size, $uploaded){
299
			if($download_size > 0){
300 301 302
				// echo $downloaded / $download_size  * 100;
				$percDwn = $downloaded / $download_size  * 100;
				echo "\r Загружено: \033[32m".$percDwn."% \033[0m [\033[36m".$downloaded."\033 из 0m/".$download_size."...";
303 304
				// ob_flush();
				// flush();
305
			}
Kulya's avatar
Kulya committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 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
		}
		/**
		 * @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
406
			ALVC::eLog($arData,$type,"billzRest");
Kulya's avatar
Kulya committed
407 408 409 410
		}

		
	}