| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261 | <?php defined('BASEPATH') OR exit('No direct script access allowed');class Apitt extends Start_Controller {	public function __construct(){		parent::__construct();		$this->load->library('session');		$this->load->_model('Model_api','api');		$this->load->_model('Model_shop','shop');		$this->load->_model('Model_fullorder','fullorder');		$this->load->_model('Model_fullordertt','fullordertt');		$this->load->_model('Model_fullordersmt','fullordersmt');		$this->load->_model('Model_country','country');		$this->load->_model('Model_hl','hl');		$this->load->_model('Model_is','is');		$this->load->_model('Model_kdniao','kdniao');		$this->load->_model('Model_typeclass','typeclass');		$this->load->_model('Model_warehouse','warehouse');		$this->load->_model('Model_fullorderexcel','fullorderexcel');		$this->load->_model('Model_dhl','dhl');		$this->load->_model('Model_usps','usps');		$this->load->_model('Model_ups','ups');		$this->load->_model('Model_dhltest','dhltest');		$this->load->_model('Model_customer','customer');		$this->load->_model('Model_express','express');		$this->load->_model('Model_notice','notice');		$this->load->_model('Model_emaildata','emaildata');		$this->load->_model('Model_whlabel','whlabel');		$this->load->_model('Model_productdescribe','productdescribe');		$this->load->_model('Model_ljg','ljg');		$this->load->_model('Model_commodityread','commodityread');		$this->load->_model('Model_service','service');		$this->load->_model('Model_fedex','fedex');		$this->load->_model('Model_apismt','apismt');		$this->load->_model('Model_cne','cne');		$this->load->_model('Model_specialstock','specialstock');		$this->load->_model('Model_whlabellabel','whlabellabel');		$this->load->_model('Model_allocation','allocation');		$this->load->_model('Model_yswaybill','yswaybill');		$this->load->_model('Model_paypal','paypal');		$this->load->_model('Model_17track','17track');		$this->load->_model('Model_ck','ck');		$this->load->_model('Model_weight','weight');		$this->load->_model('Model_pay','pay');		$this->load->_model('Model_setting','setting');		$this->load->_model('Model_classid','classid');		$this->load->_model('Model_apitt','apitt');		$this->load->_model('Model_customertt','customertt');		$this->load->_model('Model_als','als');		$this->load->_model('Model_apiyy','apiyy');		$this->load->_model('Model_whlabel_fc','whlabel_fc');		$this->load->_model('Model_shopsku','shopsku');		$this->load->_model('Model_notice','notice');		$this->load->_model('Model_ttwebhook','ttwebhook');		$this->load->_model('Model_ttcf','ttcf');		$this->load->_model('Model_producttitle','producttitle');		$this->load->_model('Model_17track','17track');		$this->load->_model("Model_logic_ding","logic_ding");	}	//定义方法的调用规则 获取URI第二段值    public function _remap($arg,$arg_array)    {		if($arg == 'sq')        {             $this->_sq();        }		else if($arg == 'token')        {             $this->_token();        }		else if($arg == 'tb')        {             $this->_tb();        }		else if($arg == 'webhook')        {             $this->_webhook();        }		else if($arg == 'ttwebhook')        {             $this->_ttwebhook();        }		else if($arg == 'cs')        {             $this->_cs();        }		else if($arg == 'cf')        {             $this->_cf();//催付        }		else if($arg == 'csa')        {             $this->_csa($arg_array);        }		else if($arg == 'shipping')        {             $this->_shipping();//获取承运商        }		else if($arg == 'update')        {             $this->_update();//上传运输信息        }		else if($arg == 'gxbudget')        {             $this->_gxbudget();//更新预估金额        }    }		public function _cf()//获取订单列表	{		$j = '{  "type": 1,  "tts_notification_id": "7374501892938712875",  "shop_id": "7495158362826508884",  "timestamp": 1717010025,  "data": {    "is_on_hold_order": true,    "order_id": "576643322058150895",    "order_status": "UNPAID",    "update_time": 1717010025  }}';$j = json_decode($j, true);		if($j['type'] == 1 && $j['data']['order_status'] == 'UNPAID')			{				$shop = $this->shop->get_shopid($j['shop_id']);				if(!$shop)				{					exit;				}				$d = $this->apitt->get_data(array($j['data']['order_id']),$shop);				if(isset($d['data']['orders'][0]['user_id']))				{				    $post = array('orderinfo'=>$j['data']['order_id'],'user_id'=>$d['data']['orders'][0]['user_id']);				    $id = $this->ttcf->insert($post);					$post['shop'] = $shop['id'];					$post['id'] = $id;				    //$this->_znxc($post,$v,3);				}				exit;			}							/*						$time = time();$cs = array();		$shop = $this->shop->find_all("type = '1514' and tb = '1'");//TT店铺		foreach ($shop as $value) 		{			//$this->db->trans_begin();			$res = $this->get_list($value,$time-7*24*3600,$time,'UNPAID');//查询2小时数 据-等待装运=AWAITING_SHIPMENT(111) ;-等待收集=AWAITING_COLLECTION (112);在途=IN_TRANSIT (121);-已交付=DELIVERED (122);			//$cs[] = array($res,$value['id']);						foreach ($res as $v) 			{				$d = $this->apitt->get_data(array($v),$value);				if(isset($d['data']['orders'][0]['user_id']))				{				    $post = array('orderinfo'=>$v,'user_id'=>$d['data']['orders'][0]['user_id']);				    $id = $this->ttcf->insert($post);					$post['shop'] = $value['id'];					$post['id'] = $id;				    $cs[] = $this->_znxc($post,$v,3);				}			}							}		echo "<pre>";		print_r($cs);		*/	}		public function get_list($shop,$from,$to,$order_status)//获取订单列表	{		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/order/202309/orders/search';		$time = time();		$post['create_time_ge'] = $from;		$post['create_time_lt'] = $to;		$post['order_status'] = $order_status;		$queryParams['page_size'] = 100;		$queryParams['sort_order'] = 'DESC';		$queryParams['sort_field'] = 'create_time';		$queryParams['shop_cipher'] =$shop['shop_cipher'];		$queryParams['shop_id'] =$shop['codeid'];		$queryParams['app_key'] =$shop['app_key'];		$queryParams['timestamp'] =$time;		$link .= '?'.http_build_query($queryParams);		$sign = $this->apitt->sign($link,$shop['app_secret'],$post);		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->apitt->su_curl($post,$url,$headers);		$res = json_decode($res,true);		$list = array();$page_token = '';$arr = array();		if(isset($res['data']['orders']))		{			if($res['data']['total_count'] > 100)			{				$n = ceil($res['data']['total_count']/100);				for($i=0;$i<$n;$i++)				{					$net_date = $this->apitt->get_next_list($shop,$from,$to,$order_status,$page_token);					$page_token = $net_date[1];					foreach ($net_date['0'] as $val) 		        	{						$d = $this->ttcf->get_orderinfo($val['id']);				    	if(!$d)				    	{							$list[] = $val['id'];						}					}				}			}			else			{			    foreach ($res['data']['orders'] as $val) 		        {				    $d = $this->ttcf->get_orderinfo($val['id']);				    if(!$d)				    {					    $list[] = $val['id'];				    }			    }			}		}		return $list;	}				public function _csa($arg_array)	{		$shop = $this->shop->read($arg_array[0]);		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/order/202309/orders/search';		$time = time();		$post['create_time_ge'] = $time-72*3600;		$post['create_time_lt'] = $time;		$post['order_status'] = 'AWAITING_SHIPMENT';		$queryParams['page_size'] = 100;		$queryParams['sort_order'] = 'ASC';		$queryParams['sort_field'] = 'create_time';		$queryParams['shop_cipher'] =$shop['shop_cipher'];		$queryParams['shop_id'] =$shop['codeid'];		$queryParams['app_key'] =$shop['app_key'];		$queryParams['shop_cipher'] =$shop['shop_cipher'];		$queryParams['timestamp'] =$time;		$link .= '?'.http_build_query($queryParams);		$sign = $this->apitt->sign($link,$shop['app_secret'],$post);		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->apitt->su_curl($post,$url,$headers);		$res = json_decode($res,true);		echo "<pre>";		print_r($res);		exit;								$data = $this->fullordertt->get_orderinfo(576696136595051237);		$shop = $this->shop->read($data['shop']);		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/order/202309/orders';		$time = time();		$link .= '?shop_cipher='.$shop['shop_cipher'].'&app_key='.$shop['app_key'].'×tamp='.$time.'&ids='.$data['orderinfo'];		$sign = $this->apitt->sign($link,$shop['app_secret'],'');		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->apitt->su_curl('',$url,$headers,$date_type='json',$timeout=300,$httptype="GET");		$res = json_decode($res,true);		echo "<pre>";		print_r($res);		exit;						$data = $this->fullordertt->get_orderinfo(576607595986915436);		$shop = $this->shop->read($data['shop']);		$list = array($data['orderinfo']);		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/api/orders/detail/query';		$time = time();		$post = array();		$post['order_id_list'] = json_encode($list);		$sign = $link.'app_key'.$shop['app_key'].'timestamp'.$time;		$sign = $shop['app_secret'].$sign.$shop['app_secret'];		$sign = hash_hmac('sha256', $sign, $shop['app_secret']);		$url .= $link.'?access_token='.$shop['token'].'&app_key='.$shop['app_key'].'&sign='.$sign.'×tamp='.$time;		$ch = curl_init();		curl_setopt($ch, CURLOPT_URL,$url);		curl_setopt($ch, CURLOPT_POST, 1);		curl_setopt($ch, CURLOPT_HEADER, 0);		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);		curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		$res = curl_exec($ch);		curl_close($ch);		$res = json_decode($res,true);		echo "<pre>";		print_r($res);			}			public function _shipping()//获取shipping_providers(运输商)	{		$data = $this->fullordertt->find_all("delivery_type != 1 and express = 63 and waybill != '' and library = '2' and librarytime > 1723257000 and state = 207");		foreach ($data as $v) 		{			$shop = $this->shop->read($v['shop']);			$url = 'https://open-api.tiktokglobalshop.com';			$link = '/logistics/202309/delivery_options/'.$v['delivery_option_id'].'/shipping_providers';//delivery_option_id			$time = time();			$link .= '?shop_cipher='.$shop['shop_cipher'].'&app_key='.$shop['app_key'].'×tamp='.$time;			$sign = $this->apitt->sign($link,$shop['app_secret'],'');			$url .= $link.'&sign='.$sign;			$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);			$res = $this->apitt->su_curl('',$url,$headers,$date_type='json',$timeout=300,$httptype="GET");			$res = json_decode($res,true);			if(!isset($res['data']['shipping_providers']))			{				continue;			}			$uid = '';			foreach ($res['data']['shipping_providers'] as $val) 			{				if($val['name'] == 'FedEx')				{					$uid = $val['id'];				}			}			if($uid != '')			{			    $this->_update($v,$uid);			}		}	}		public function _update($data,$uid)//上传运单	{		$shop = $this->shop->read($data['shop']);		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/fulfillment/202309/orders/'.$data['orderinfo'].'/shipping_info/update';		$time = time();		$post['tracking_number'] = $data['waybill'];//运单号		$post['shipping_provider_id'] = $uid;//承运商ID		$queryParams['app_key'] =$shop['app_key'];		$queryParams['shop_cipher'] =$shop['shop_cipher'];		$queryParams['timestamp'] =$time;		$link .= '?'.http_build_query($queryParams);		$sign = $this->apitt->sign($link,$shop['app_secret'],$post);		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->apitt->su_curl($post,$url,$headers);		$res = json_decode($res,true);		if($res['message'] == 'Success')		{			$this->fullordertt->save(array('delivery_type'=>1),$data['id']);		}		else		{			$this->fullordertt->save(array('delivery_type'=>2),$data['id']);		}	}			public function _sq()	{				//授权获取app_key和code用于下一步获取token		$post = $this->input->get(NULL);		if(isset($post['app_key']))		{		    $app_key = $this->input->get('app_key');			$code = $this->input->get('code');			if($code && $app_key)			{				$shop = $this->shop->app_key($app_key);				if($shop)				{				    $url = 'https://auth.tiktok-shops.com/api/v2/token/get?app_key='.$app_key.'&auth_code='.$code.'&app_secret='.$shop['app_secret'].'&grant_type=authorized_code';				    $ch = curl_init();       		        curl_setopt($ch, CURLOPT_URL,$url);       		        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        		        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);        		        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);       		        $res = curl_exec($ch);       		        curl_close($ch);       		        $res = json_decode($res,true);				    if(isset($res['data']))				    {						$shop['token'] = $res['data']['access_token'];						$shop['refresh_token'] = $res['data']['refresh_token'];						$shop_cipher = '';						$shopcipher = $this->_shop_cipher($shop);						if(isset($shopcipher['data']['shops'][0]['cipher']))						{							$shop_cipher = $shopcipher['data']['shops'][0]['cipher'];						}					    $this->shop->save(array('token'=>$res['data']['access_token'],'tokentime'=>$res['data']['access_token_expire_in']-48*3600,'refresh_token'=>$res['data']['refresh_token'],'app_key'=>$app_key,'code'=>$code,'shop_cipher'=>$shop_cipher),$shop['id']);					    echo 'ok';						echo "<pre>";						print_r($res);				    }					else					{						echo json_encode($res);					}				}				else				{					echo "没有此店铺";				}			}		}					}		public function _token()//判断tokentime通过refresh_token刷新token	{		$shop = $this->shop->find_all("type = '1514' and tb = 1");//找TT店铺		foreach ($shop as $v) 		{			if($v['tokentime'] < time()+3*24*3600)			{				$url = 'https://auth.tiktok-shops.com/api/v2/token/refresh?app_key='.$v['app_key'].'&app_secret='.$v['app_secret'].'&grant_type=refresh_token&refresh_token='.$v['refresh_token'];		   	    $ch = curl_init();           	    curl_setopt($ch, CURLOPT_URL,$url);           	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);            	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);            	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);//等待时间 10秒           	    $res = curl_exec($ch);           	    curl_close($ch);           	    $res = json_decode($res,true);		   	    if(isset($res['data']))		   	    {					$v['token'] = $res['data']['access_token'];					$v['refresh_token'] = $res['data']['refresh_token'];					$shop_cipher = '';					$shopcipher = $this->_shop_cipher($v);					if(isset($shopcipher['data']['shops'][0]['cipher']))					{						$shop_cipher = $shopcipher['data']['shops'][0]['cipher'];					}			   	    $this->shop->save(array('token'=>$res['data']['access_token'],'tokentime'=>$res['data']['access_token_expire_in']-48*3600,'refresh_token'=>$res['data']['refresh_token']),$v['id']);		   	    }				else				{					echo json_encode($res);					exit;				}			}			}			echo "ok";	}		public function _shop_cipher($shop,$x=0)	{		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/authorization/202309/shops';		$time = time();$post = array();		$queryParams = array();		$queryParams['access_token'] = $shop['token'];		$queryParams['app_key'] = $shop['app_key'];		$queryParams['shop_id'] = $shop['codeid'];		$queryParams['timestamp'] = $time;		$queryParams['version'] = '202309';		$link .= '?'.http_build_query($queryParams);		$sign = $this->apitt->sign($link,$shop['app_secret'],$post);		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$ch = curl_init();		curl_setopt($ch, CURLOPT_URL, $url);		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);		$res = curl_exec($ch);		curl_close($ch);		$res = json_decode($res,true);		if(isset($res['data']['shops'][0]['cipher']) || $x == 5)		{			return $res;		}		else		{			$this->_shop_cipher($shop,1);		}	}		public function _tb()	{		$post = $this->input->post(NULL, TRUE);		$api = $this->input->get('api',true);		$dshop = $this->input->get('dshop',true);		$gethl = array();		/*  匹配加入  */		$dictionaries = $this->typeclass->find_all('spare!= "" and classid != 1 and classid != 2 and classid != 3 and classid != 4 and classid != 5 and classid != 11 and classid != 16 and classid != 17 and classid != 20 and classid != 21 and classid != 23 and classid != 24 and classid != 29 and classid != 30 and classid != 31 and classid != 32 and classid != 36');		// and (classid=13 or classid=22 or classid=8 or classid=15 or classid=27 or classid=25 or classid=26 or classid=18 or classid=14 or classid=9 or classid=12 or classid=10 or classid=6 or classid=100 or classid=999)		$dtc = array();		foreach ($dictionaries as $v) 		{			if(stripos($v['spare'],'|') !== false)//如果有多个值			{				$v['spare'] = explode('|',$v['spare']);				foreach ($v['spare'] as $k=>$vs) 		        {					if(stripos($v['zh'],'|') !== false)					{						$vzh = explode('|',$v['zh']);						$dtc[strtolower($vs)] = array('classid'=>$v['classid'],'zh'=>$vzh[$k],'id'=>$v['id']);					}					else					{					    $dtc[strtolower($vs)] = array('classid'=>$v['classid'],'zh'=>$v['zh'],'id'=>$v['id']);					}				}			}			else			{				$dtc[strtolower($v['spare'])] = array('classid'=>$v['classid'],'zh'=>$v['zh'],'id'=>$v['id']);			}					}		$dictionaries2 = $this->typeclass->find_all();		foreach ($dictionaries2 as $v)		{			$dtctitle[$v['id']] = $v['title'];		}		/*  匹配结束  */    		/*  价格加入  */  		$money = array();		/**		$productdescribe = $this->productdescribe->find_all('1=1','number,purchase,cost,salesprice,title');		foreach ($productdescribe as $v) 		{			$money[$v['number']] = array('purchase'=>$v['purchase'],'cost'=>$v['cost'],'salesprice'=>$v['salesprice'],'title'=>$v['title']);		}		**/		/*  价格加入  */		/*  匹配ID加入  */		$int = array();		$intdata = $this->typeclass->find_all('classid=14','id,spare');		foreach ($intdata as $v) 		{			$v['spare'] = explode('|',$v['spare']);			$int[$v['id']] = $v['spare'][0];		}		/*  匹配ID结束  */		/*  国家加入键值-k  */		$cuy = array();		$cuydata = $this->country->find_all('1=1','lb,id');		foreach ($cuydata as $v) 		{			$cuy[$v['lb']] = $v['id'];//获取到国家ID		}		/*  国家加入键值-j  */		$typeclass = array();		$tdata = $this->typeclass->find_all('classid=30','id,title');		foreach ($tdata as $v) 		{			$typeclass[$v['title']] = $v['id'];		}		$ex = array();		$express = $this->express->find_all('1=1','id,title');		foreach ($express as $v) 		{			$ex[$v['title']] = array('id'=>$v['id']);		}		/*  币种加入键值-j  */		/*  支付方式-k  */		$pay = array();$sd = array();		$tdata = $this->typeclass->find_all('classid=4','id,spare');		foreach ($tdata as $v) 		{			$paytype = $this->pay->get_typeclass($v['id']);			if(isset($paytype['estimaterate']))			{				$estimaterate = $paytype['estimaterate'];			}			else			{				$estimaterate = 0;			}			if(stripos($v['spare'],'|') !== false)//如果有多个值			{				$v['spare'] = explode('|',$v['spare']);				foreach ($v['spare'] as $k=>$vs) 		        {					$pay[$vs] = array('id'=>$v['id'],'estimaterate'=>$estimaterate);				}			}			else			{				$pay[$v['spare']] = array('id'=>$v['id'],'estimaterate'=>$estimaterate);			}		}		/*  支付方式-j  */		/*  新增SKU-k  */		$zjsku = array();		$shopsku = $this->shopsku->find_all();		foreach ($shopsku as $val) 		{			$ss = explode(',',trim($val['shop'],','));			foreach ($ss as $v) 			{				if(isset($zjsku[$v]))				{					$zjsku[$v] .= ','.trim($val['sku'],',');				}				else				{					$zjsku[$v] = trim($val['sku'],',');				}			}		}			/*  新增SKU-j  */		$time = time();		$tb = 0;		if($api = '89757')  		{			$shop = $this->shop->find_all("type = '1514' and tb = '1'");//TT店铺			foreach ($shop as $value) 		    {				if((time()-$value['tbtime']) < 1)				{					$tb = 1;//正在同步中					break;				}				$setting = $this->setting->get_settings();				$sjc = 15*3600+$setting['sctime'];//时间差				$num = $this->fullordertt->find_count('gtime = "'.date('Ymd',$time).'" and shop = "'.$value['id'].'"');				//$this->db->trans_begin();				$res = $this->apitt->get_list($value,$time-3*24*3600,$time,'AWAITING_SHIPMENT',$cuy,$num,$dtc,$money,$int,$dtctitle,$pay,$typeclass,$ex,$sjc,$zjsku);//查询2小时数 据-等待装运=AWAITING_SHIPMENT(111) ;-等待收集=AWAITING_COLLECTION (112);在途=IN_TRANSIT (121);-已交付=DELIVERED (122);				$sd[] = $res;				$res = $res[0];				if($res)				{					foreach ($res as $v) 		        	{						$this->logic_ding->sendToDing("获取TT订单".json_encode($v));						$post = $v;						$dataorder = $this->fullordertt->get_orderinfo($v['orderinfo']);						if(!isset($dataorder['id']))						{							/** 启用自动分配仓库 **/							$warehouse = $this->warehouse->find_all("fpzd = '1'",'*','fpsx desc');							if($post['cf'] == 1)							{								$post['type'] = 34;//TT仓							}							else							{							    foreach ($warehouse as $v) 		        	            {								    if($v['bdcountry'] != 0 && $v['bdcountry'] != $post['country'])								    {									    continue;								    }								    $yx = 'get_yx_'.$v['bdck'];								    $kczd = $this->ck->$yx($post['state'],$v,$post['shop'],$post['number'],$post['whlabel'],$post['fpdata']);								    if($kczd['t'] == 0)								    {									    $country = $this->country->read($post['country']);//获取国家中配置物流									    if($country['express'] != 0)									    {									    	$post['express'] = $country['express'];									    }									    if($v['express'] != 0)//优先使用仓库指定物流,替换掉上面的国家配置物流									    {									    	$post['express'] = $v['express'];									    }									    $post['type'] = $v['id'];									    $post['whlabel'] = $kczd['whlabel'];									    $post['fpdata'] = $kczd['fpdata'];									    if(stripos($kczd['whlabel'],$v['hz']) !== false)									    {									        break 1;									    }								    }							    }							    $qdw = $this->warehouse->read($post['type']);							    $fl = $this->ck->get_fl($qdw['hz'],$post['whlabel'],$post['fpdata']);							    $post['sfxh'] = $fl['sfxh'];							    $post['ckfl'] = $fl['ckfl'];								$zipcode =  substr($post['zipcode'],0,1);								if($post['type'] == 5 && $zipcode > 6)								{									$post['express'] = 63;																}							    //自动写位置 开始							   $zclp = array();$pxsl = array();							   $slpx = explode('|',$post['slpx']);//排序							  						       //解决礼物类没有slpx的数据						       if(!empty($post['slpx'])){						            foreach ($slpx as $k=>$v)     							   {    								   $v = explode('-',$v);    								   if(!isset($v[1]))    								   {    									   $v[1] == 1;    								   }    								   for($i=$v[0];$i<$v[1];$i++)    								   {    			    					   $pxsl[$i] = $k;    								   }    							   }						       }							       							 							  							   $mc = $qdw['bdck'];$zdidjl = '';$zdwzjl = '';							   if($qdw['wz'] == 1)							   {								   $pm = explode(';',trim($post['shipremarks'],';'));								   foreach ($pm as $k=>$vv) 		        				   {									   $vv = trim($vv,' ');									   $lp = $this->typeclass->find_all("zh = '$vv'");									   if(isset($lp[0]['classid']))									   {										   $zclp[] = $vv;										   unset($pm[$k]);									   }								   }								   $pm = array_values($pm);								   $w = explode('|',trim($post['whlabel'],'|'));								   foreach ($w as $k=>$val) 		        	    		   {									   $hwm = '';									   if(stripos($val,$qdw['hz']) !== false)									   {										   $num = explode('-',trim($val,'-'));										   $xq = explode('~',trim($num[2],'~'));										   $pmxq = '(';										   foreach ($xq as $v) 		        	           			   {											   $zdidjl .= '('.trim($v,$qdw['hz']).')';											   $h = $this->$mc->read(trim($v,$qdw['hz']));											   if($h['details'] != '')											   {									               $pmxq .= $qdw['title'].':'.$h['details'].(($h['cpid']>0)?'-'.$h['cpid']:'').',';											   }								           }										   $xrid = ($h['cpid']>0)?'-'.$h['cpid']:'';										   if(isset($pxsl[$k]))										   {											   if(stripos($pm[$pxsl[$k]],$qdw['title'].':'.$h['details'].$xrid) === false)											   {												   $pm[$pxsl[$k]] .= trim($pmxq,',').')';											   }										   }										   $zdwzjl .= $h['details'].(($h['cpid']>0)?'-'.$h['cpid']:'');							           }						           }								   if($zclp)								   {									   $zclp = ';'.implode(";",$zclp);								   }								   else								   {									   $zclp = '';								   }								   $post['shipremarks'] = implode(";",$pm).$zclp;								   $post['contents'] = $zdidjl.' - '.$zdwzjl;					           }							}							//自动写位置 结束							//条数及申报							$ts = 0;							$dtsbjz = 0;							$zsbjz = 0;							$w = explode('|',trim($post['whlabel'],'|'));														foreach ($w as $k=>$val) 		        	    	{								$num = explode('-',trim($val,'-'));								//判断是否是礼物  礼物不计数								$is_gift_str = substr($num[0], 0, 3);								if($is_gift_str != '131'){									$ts += $num[1];								}															}														if($ts > 0 && $ts < 6 && $post['country'] == 192)							{								$dtsbjz = ($ts==3)?sprintf("%.1f",100/$ts):100/$ts;								$zsbjz = sprintf("%.2f",$dtsbjz*$ts);							}							$post['ts'] = $ts;							$post['dtsbjz'] = $dtsbjz;							$post['zsbjz'] = $zsbjz;							/** **/							//合并重复项							$hbcfw = explode('|',trim($post['whlabel'],'|'));							$hbcff = explode(';',trim($post['fpdata'],';'));							$c = 0;							$hbw = array();							$hbf = array();							for($i=0;$i<count($hbcfw);$i++)							{								$w = explode('-',$hbcfw[$i]);								$f = explode('|',$hbcff[$i]);								$w2 = ($w[2]==0)?0:'';								if(!isset($hbw[$w[0].$w2]))								{									$hbw[$w[0].$w2] = $hbcfw[$i];									$hbf[$w[0].$w2] = $hbcff[$i];								}								else								{									$c++;									$cw = explode('-',$hbw[$w[0].$w2]);									$cf = explode('|',$hbf[$w[0].$w2]);									if($cw[2] != 0 && $w[2] != 0)									{										$cf[2] += $f[2];										$cf[9] .= '~'.$f[9];									    $hbf[$w[0].$w2] = implode("|",$cf);									    $cw[1] += $f[2];										$cw[2] .= '~'.$f[9];									    $hbw[$w[0].$w2] = implode("-",$cw);									}									else if($cw[2] == 0 && $w[2] == 0)									{									    $cf[2] += $f[2];									    $hbf[$w[0].$w2] = implode("|",$cf);									    $cw[1] += $f[2];									    $hbw[$w[0].$w2] = implode("-",$cw);									}									else									{										$hbw[] = $hbcfw[$i];									    $hbf[] = $hbcff[$i];									}								}							}							if($c > 0)							{								$post['fpdata'] = implode(";",$hbf).';';								$post['whlabel'] = '|'.implode("|",$hbw).'|';							}							//合并重复项结束							//非占单设置为禁止占单开始							$hbw = explode('|',trim($post['whlabel'],'|'));							$hbf = explode(';',trim($post['fpdata'],';'));							foreach ($hbw as $k=>$val) 		        	    	{								$w = explode('-',$val);								$f = explode('|',$hbf[$k]);								if(!isset($w[2]) || $w[2] == 0)								{									$w[2] = "DNOTO";								    $f[9] = "DNOTO";								    $hbf[$k] =  implode("|",$f);								    $hbw[$k] = implode("-",$w);								}							}							$post['fpdata'] = implode(";",$hbf).';';							$post['whlabel'] = '|'.implode("|",$hbw).'|';							//非占单设置为禁止占单结束							//查询净重开始							$post['jweight'] = $this->weight->get_weightcx($post['fpdata']);							$post['zzl'] = ($post['jweight']+100)/1000;							if($post['express'] == 2)							{								$post['zzl'] = intval(($post['jweight']+100)*0.035);							}							//查询净重结束			   		   		$tjid = $this->fullordertt->insert($post);							if($post['email'] == '')							{								$post['email'] = $post['name'].'@qq.com';							}							$adrs = $this->customertt->get_email($post['email'],$post['shop']);							preg_match_all('/[0-9]/u',$post['phone'],$result);				            $numphone = join('',$result[0]);							$hmdaddress1 = str_replace(array(' parkway',' drive',' street',' road',' avenue',' boulevard',' alley',' court',' place',' lane',' manor',' terrace',' trail',' view',' cove'),array(' pkwy',' dr',' st',' rd',' av',' blvd',' aly',' ct',' pl',' ln',' mnr',' ter',' trl',' vw',' cv'),strtolower($post['address']));			                $hmdaddress2 = str_replace(array(' pkwy',' dr',' st',' rd',' av',' blvd',' aly',' ct',' pl',' ln',' mnr',' ter',' trl',' vw',' cv'),array(' parkway',' drive',' street',' road',' avenue',' boulevard',' alley',' court',' place',' lane',' manor',' terrace',' trail',' view',' cove'),strtolower($post['address']));			                $hmdaddress3 = str_replace(array(' avenue',' ave',' av'),array(' ave',' avenue',' ave'),strtolower($post['address']));							$hmdid = '';							$post['address'] = str_replace("'","’",$post['address']);							$hmdaddress1 = str_replace("'","’",$hmdaddress1);							$hmdaddress2 = str_replace("'","’",$hmdaddress2);							$customerb = $this->customertt->find_all('type = 2 and (email = "'.$post['email'].'" or address = "'.$post['address'].'" or address = "'.$hmdaddress1.'" or address = "'.$hmdaddress2.'" or address = "'.$hmdaddress3.'" or numphone = "'.$numphone.'")','*','id desc');							$lkh = (isset($customerb[0]['id']))?2:1;//白名单1黑名单2							if($lkh == 2)							{								$hmdid = $customerb[0]['id'].'-('.$post['email'].'|'.$post['address'].'|'.$numphone.')'.'('.$customerb[0]['email'].'|'.$customerb[0]['address'].$customerb[0]['numphone'].')';							}							if($adrs)							{								$pdlkh = 1;//这个是判断是否老客户								$this->customertt->save(array('time'=>$post['dtime'],'num'=>$adrs['num']+1,'money'=>$adrs['money']+$post['shouldmoney']),$adrs['id']);								$khid = $adrs['id'];							}							else							{								$str = $post['phone'];								preg_match_all('/[0-9]/u',$str,$result);								$numphone = join('',$result[0]);								$ct['shop'] = $post['shop'];								$ct['source'] = 9;								$ct['level'] = 5;								$ct['country'] = $post['country'];								$ct['time'] = $post['dtime'];								$ct['num'] = 1;								$ct['money'] = $post['shouldmoney'];								$ct['zipcode'] = $post['zipcode'];								$ct['name'] = $post['name'];								$ct['phone'] = $post['phone'];								$ct['numphone'] = $numphone;								$ct['email'] = preg_replace('/( | | |\s)+/','',$post['email']);								$ct['province'] = $post['province'];								$ct['city'] = $post['city'];								$ct['address'] = $post['address'];								$ct['zhcx'] = $post['shop'].'-'.$ct['email'];			     				$khid = $this->customertt->insert($ct);								$pdlkh = 0;							}							if($post['cf'] != 1)							{							    $this->_znxc($post,$post['orderinfo'],1);							}						}//else{}如果有此订单					}				}				/**				if ($this->db->trans_status() === FALSE)                {				    $this->db->trans_commit();                }                else                {                    $this->db->trans_commit();                }				**/				//sleep(1);//停留2秒				$this->shop->save(array('tbtime'=>time()),$value['id']);			}			if($tb == 1)			{				echo json_encode(array('msg'=>'有店铺正在同步中,请5分钟后再试!','success'=>true));exit;			}			//echo json_encode(array('msg'=>'OK!','success'=>true));exit;			echo "<pre>";			print_r($sd);		}	}		public function _znxc($fullorder,$order_id,$type,$logisticstatus='')	{		$time = time();		if($type == 1)//地址确认需要状态对应		{			$notice = $this->notice->find_all("shop = '".$fullorder['shop']."' and ordertatus = '".$fullorder['state']."' and tab = '0' and message = '3' and state = '1' and ktime < '$time' and jtime > '$time' and type = '$type'");//有条件不同模板匹配			$express = array();		}		else if($type == 4)//运单号通知		{			$notice = $this->notice->find_all("shop = '".$fullorder['shop']."' and message = '3' and state = '1' and ktime < '$time' and jtime > '$time' and type = '$type'");//有条件不同模板匹配			 $express = $this->express->read($fullorder['express']);		}		else if($type == 3)//催付		{			$notice = $this->notice->find_all("shop = '".$fullorder['shop']."' and message = '3' and state = '1' and ktime < '$time' and jtime > '$time' and type = '$type'");//有条件不同模板匹配		}		else if($type == 2)//物流发送		{			$notice = $this->notice->find_all("shop = '".$fullorder['shop']."' and message = '3' and state = '1' and ktime < '$time' and jtime > '$time' and type = '$type' and logisticstatus = '$logisticstatus'");//有条件不同模板匹配			 $express = $this->express->read($fullorder['express']);		}		if(isset($notice[0]['content']) && $type != 3)		{			$fid = $this->fullordertt->get_orderinfo($order_id);			$shop = $this->shop->read($fullorder['shop']);			 $country = $this->country->read($fullorder['country']);			 $fullorder['country'] = $country['ename'];			    $go = $this->notice->get_god($fullorder,$shop,$express,$notice[0]);			    if($go == 1)			    {				    $this->fullordertt->save(array('content'=>$fid['content'].'自动发送-成功-'.$type.'-'.date("Y-m-d H:i:s",time()),'zdstate'=>$fid['zdstate'].$notice[0]['type'].'-'.$notice[0]['tab'].'|','exstateerror'=>''),$fid['id']);					return 1;			    }			    else			    {				    $this->fullordertt->save(array('exstateerror'=>'自动发送失败1:'.date('Y-m-d H',time()).'-'.$go.'('.$notice[0]['type'].'-'.$notice[0]['message'].')'),$fid['id']);			    }		}		else if(isset($notice[0]['content']) && $type == 3)		{			$shop = $this->shop->read($fullorder['shop']);			$go = $this->notice->get_god($fullorder,$shop,array(),$notice[0]);			if($go == 1)			{				$this->ttcf->save(array('cg'=>1,'shop'=>$fullorder['shop'],'data'=>'自动发送-成功-'.$type.'-'.date("Y-m-d H:i:s",time())),$fullorder['id']);					return 1;			}			else			{				$this->ttcf->save(array('cg'=>2,'shop'=>$fullorder['shop'],'data'=>'自动发送失败1:'.date('Y-m-d H',time()).'-'.$go.'('.$notice[0]['type'].'-'.$notice[0]['message'].')'),$fullorder['id']);			}		}		else		{			if($type == 3)			{				$this->ttcf->save(array('cg'=>3,'shop'=>$fullorder['shop'],'data'=>'当前订单状态无匹配模板'),$fullorder['id']);			}			else			{			    $this->fullordertt->save(array('exstateerror'=>'当前订单状态无匹配模板 - state:'.$fullorder['state'].' - shop:'.$fullorder['shop'].' - time:'.$time.' - type:'.$type.'  - notice:'.json_encode($notice)),$fid['id']);			}		}	}		public function _webhook()	{		header('HTTP/1.1 200 OK');		ob_flush();        flush();		$j = file_get_contents('php://input');		$j = json_decode($j, true);		if(isset($j['type']) && isset($j['data']['order_id']))		{			$data = json_encode($j['data']);			$tid = $this->ttwebhook->get_tid($j['tts_notification_id']);			if($tid)			{				exit;			}			else			{				$this->ttwebhook->insert(array('tid'=>$j['tts_notification_id'],'orderinfo'=>$j['data']['order_id'],'data'=>$data,'time'=>date("Y-m-d H:i:s",time())));			}			$ch = curl_init();		    curl_setopt($ch,CURLOPT_URL,'http://a10.wepolicy.cn/apitt/ttwebhook');		    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);		    curl_setopt($ch,CURLOPT_HEADER,0);		    curl_setopt($ch,CURLOPT_POST, 1);		    curl_setopt($ch,CURLOPT_TIMEOUT,1);            //设置post数据		    $post = array();		    $post['j'] = json_encode($j);            curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));		    $res = curl_exec($ch);		    curl_close($ch);			}		exit; 	}		public function _ttwebhook()	{		$post = $this->input->post(NULL, TRUE);		if(isset($post['j']))		{			$j = $this->input->post('j',true);			$j = json_decode($j, true);			$xq = array();			if($j['type'] == 1 && $j['data']['order_status'] == 'UNPAID')			{				$shop = $this->shop->get_shopid($j['shop_id']);				if(!$shop)				{					exit;				}				$d = $this->apitt->get_data(array($j['data']['order_id']),$shop);				if(isset($d['data']['orders'][0]['user_id']))				{				    $post = array('orderinfo'=>$j['data']['order_id'],'user_id'=>$d['data']['orders'][0]['user_id']);				    $id = $this->ttcf->insert($post);					$post['shop'] = $shop['id'];					$post['id'] = $id;				    $this->_znxc($post,$v,3);				}				exit;			}            $d = $this->fullordertt->get_orderinfo($j['data']['order_id']);			if($d)			{				$post = $this->fullordertt->read($d['id']);				$shop = $this->shop->read($d['shop']);				$qchz = array();				$f = explode('|',trim($d['whlabel'],'|'));				foreach ($f as $v) 		        {					$hz = explode('-',trim($v,'-'));					if(isset($hz[2]) && $hz[2] != 'DNOTO' && $hz[2] != '0')					{						$qchz[] = $hz[2];					}				}				$d['whlabel']= str_replace($qchz,'0',$d['whlabel']);				$d['fpdata']= str_replace($qchz,'0',$d['fpdata']);				$this->db->trans_begin();				if($j['type'] == 1)				{					if($j['data']['order_status'] == 'CANCEL' || $j['data']['order_status'] == 'Canceled')					{						if($d['library'] != 2)						{						    $whlabel = $this->whlabel->find_all("zd = '".$d['number']."'");						    foreach ($whlabel as $v) 		       		        {							    $this->whlabel->save(array('zd'=>''),$v['id']);						    }						    $this->fullordertt->save(array('state'=>217,'whlabel'=>$d['whlabel'],'fpdata'=>$d['fpdata']),$d['id']);						}						else						{							$this->fullordertt->save(array('state'=>214),$d['id']);						}					}					else if(($j['data']['order_status'] == 'IN_TRANSIT' || $j['data']['order_status'] == 'COMPLETED currently)') && $d['state'] != 216)					{						if($d['cf'] == 1 && $d['type'] == 34 && $j['data']['order_status'] == 'IN_TRANSIT')						{							$wb = $this->apitt->get_data(array($d['orderinfo']),$shop);							$waybill = $wb['data']['orders']['0']['tracking_number'];							$ex = $wb['data']['orders']['0']['shipping_provider'];							$express = 0;							if(stripos($ex,"UPS") !== false)							{								$express = 3;							}							else if(stripos($ex,"DHL") !== false)							{								$express = 1;							}							else if(stripos($ex,"FEDEX") !== false)							{								$express = 24;							}							else if(stripos($ex,"USPS") !== false)							{								$express = 2;							}							else if(stripos($ex,"ONTRAC") !== false)							{								$express = 62;							}							$time = time();							$post['waybill'] = $waybill;							$post['express'] = $express;							$express_id = $express;							$d['waybill'] = $waybill;							$this->fullordertt->save(array('state'=>216,'fpdata'=>$d['fpdata'],'waybill'=>$waybill,'print'=>3,'printtime'=>$time,'printnumber'=>1,'libraryconfirm'=>2,'library'=>2,'librarytime'=>$time,'weight'=>'0.4kg','review'=>6,'reviewtime'=>$time,'express'=>$express),$d['id']);						}						else						{							$this->fullordertt->save(array('state'=>216,'whlabel'=>$d['whlabel'],'fpdata'=>$d['fpdata']),$d['id']);							$express_id = $d['express'];						}						if($express_id != 0)						{							if(stripos('|'.$post['zdstate'],'|4-') === false)							{						        $this->_znxc($post,$post['orderinfo'],4);							}														$expressdata = $this->express->read($express_id);							$service = $this->service->read($expressdata['service']); 							if(($expressdata['cxcode'] == 'ups' || $expressdata['cxcode'] == '17track' || $expressdata['cxcode'] == 'usps') && $d['webhookregister'] < 1)						 	{								$logistics = $expressdata['cxcode'];								$d['servicename'] =$service['title'];//增加快递名称		    					$d['url'] = $expressdata['url'];//增加快递链接		    					@$fs = $this->$logistics->get_logistics($d);								if(isset($fs) && $fs['f'] == '1')								{									$this->fullordertt->save(array('expressstate'=>$fs['exstate'],'excontent'=>$fs['data'],'webhookregister'=>1),$d['id']);																	}						 	}						}					}					else if($j['data']['order_status'] == 'DELIVERED')					{						$je = $this->apitt->get_je($d,$shop);						$budget = 0;						if(isset($je['data']['statement_transactions']['0']['settlement_amount']))						{							foreach ($je['data']['statement_transactions'] as $val) 		       		    	{								$budget += $val['settlement_amount'];							}							$this->fullordertt->save(array('budget'=>$budget),$d['id']);						}						if(stripos('|'.$post['zdstate'],'|2-') === false)						{						    $this->_znxc($post,$post['orderinfo'],2,6);//2物流模板,6已签收						}					}				}				if($j['type'] == 2)				{					if($j['reverse_order_status '] == 50 || $j['reverse_order_status '] == 51)				    {						$whlabel = $this->whlabel->find_all("zd = '".$d['number']."'");						foreach ($whlabel as $v) 		       		    {							$this->whlabel->save(array('zd'=>''),$v['id']);						}					    $this->fullordertt->save(array('state'=>214,'whlabel'=>$d['whlabel'],'fpdata'=>$d['fpdata']),$d['id']);					}					/**					reverse_order_status					售后申请 = 1					售后拒绝申请 = 2					售后退货 = 3					售后买家已发货 = 4					售后卖家_拒绝接收 = 5					售后成功 = 50					取消成功 = 51					关闭 = 99					完成 = 100					**/				}				if ($this->db->trans_status() === TRUE)        		{					$this->db->trans_commit();				}				else				{					$this->db->trans_rollback();				}			}		}	}			public function _gxbudget()	{		$time = time();		$data = $this->fullordertt->find_all("source != 1 and budget = 0 and librarytime > '".($time-6*24*3600)."' and  librarytime < '".($time-9*24*3600)."'");		foreach ($data as $v) 		{			$shop = $this->shop->read($v['shop']);			$je = $this->apitt->get_je($v,$shop);			$budget = 0;			if(isset($je['data']['statement_transactions']['0']['settlement_amount']))			{				foreach ($je['data']['statement_transactions'] as $val) 		       	{					$budget += $val['settlement_amount'];				}				$this->fullordertt->save(array('budget'=>$budget),$v['id']);			}		}	}}
 |