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'); } //定义方法的调用规则 获取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 == 'cs') { $this->_cs(); } else if($arg == 'csa') { $this->_csa(); } } public function get_list($shop,$from,$to,$order_status,$cuy,$num,$dtc,$money,$int,$dtctitle,$pay,$typeclass,$ex,$sjc)//获取订单列表 { $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->get_next_list($shop,$from,$to,$order_status,$page_token); $page_token = $net_date[1]; foreach ($net_date['0'] as $val) { $d = $this->fullordertt->get_orderinfo($val['id']); if(!$d) { $list[] = $val['id']; } } } } else { foreach ($res['data']['orders'] as $val) { $d = $this->fullordertt->get_orderinfo($val['id']); if(!$d) { $list[] = $val['id']; } } } $cs = array(); if(count($list) > 50) { $n = ceil(count($list)/50);$x = 0; for($i=0;$i<$n;$i++) { $k = ($i<1)?0:$i*50; $data = array_slice($list,$k,50); $d = $this->get_data($data,$shop); $cs[] = $d; if(isset($d['data'])) { foreach ($d['data']['orders'] as $val) { $arr[$x] = $val; $x++; } } } } else { $d = $this->get_data($list,$shop); if(isset($d['data'])) { foreach ($d['data']['orders'] as $val) { $arr[] = $val; } } } } $read = array(); $gnum = array(); foreach ($arr as $val) { $create_time = substr($val['create_time'],0,10)-$sjc; if(isset($gnum[date('ymd',$create_time)])) { $gnum[date('ymd',$create_time)] += 1; } else { $num = $this->fullordertt->find_count('gtime = "'.date('Ymd',$create_time).'" and shop = "'.$shop['id'].'"'); $gnum[date('ymd',$create_time)] = $num+1; } $read[] = $this->get_read($val,$time,$shop,$cuy,$gnum[date('ymd',$create_time)],$dtc,$money,$int,$dtctitle,$pay,$typeclass,$ex,$sjc); } return array($read,$list); } public function get_next_list($shop,$from,$to,$order_status,$page_token='')//获取订单列表 { $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; if($page_token) { $queryParams['page_token'] = $page_token; } $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(isset($res['data']['orders'])) { return array($res['data']['orders'],$res['data']['next_page_token']); } } public function get_data($list,$shop) { $url = 'https://open-api.tiktokglobalshop.com'; $link = '/order/202309/orders'; $time = time(); $ids = implode(",",$list); $link .= '?shop_cipher='.$shop['shop_cipher'].'&app_key='.$shop['app_key'].'×tamp='.$time.'&ids='.$ids; $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); return $res; } public function _csa() { $data = $this->fullordertt->get_orderinfo(576607595986915436); $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['token'],$shop['app_secret']); $url .= $link.'&sign='.$sign; $headers = array('x-tts-access-token:'.$shop['token']); $res = $this->api->su_curl('',$url,$headers,$date_type='json',$timeout=300,$httptype="GET",$userpwd=''); $res = json_decode($res,true); echo "
";
		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 "
";
		print_r($res);
		
	}
	


	
	public function _sq()
	{
		//授权获取app_key和code用于下一步获取token
		$post = $this->input->get(NULL, TRUE);
		if(isset($post['app_key']))
		{
		    $app_key = $this->input->get('app_key',true);
			$code = $this->input->get('code',true);
			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);//?status=any所有订单 &limit=200每页多少单
       		        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_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 "
";
						print_r($res);
				    }
					else
					{
						echo json_encode($res);
					}
				}
				else
				{
					echo "没有此店铺";
				}
			}
		}
				
	}
	
	public function _token()//判断tokentime通过refresh_token刷新token
	{
		$shop = $this->shop->find_all("type = '1514'");//找TT店铺
		foreach ($shop as $v) 
		{
			if($v['tokentime'] < time()+30*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);
           	    $res = curl_exec($ch);
           	    curl_close($ch);
           	    $res = json_decode($res,true);
		   	    if(isset($res['data']))
		   	    {
					$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'],'shop_cipher'=>$shop_cipher),$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-2*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) 
		        	{
						$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'];
							    //自动写位置 开始
							   $zclp = array();$pxsl = array();
							   $slpx = explode('|',$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;
					           }
							}
							//自动写位置 结束
							/** **/
							//合并重复项
							$hbcfw = explode('|',trim($post['whlabel'],'|'));
							$hbcff = explode(';',trim($post['fpdata'],';'));
							$c = 0;
							$hbw = array();
							$hbf = array();
							for($i=0;$i 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']);
							//查询净重结束
			   		   		$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 "
";
			print_r($sd);
		}
	}
	
	public function _znxc($fullorder,$order_id,$type)
	{
		$time = time();
		$fid = $this->fullordertt->get_orderinfo($order_id);
		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'");//有条件不同模板匹配
		}
		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'");//有条件不同模板匹配
		}
		if(isset($notice[0]['content']))
		{
			$shop = $this->shop->read($fullorder['shop']);
			 $country = $this->country->read($fullorder['country']);
			 $fullorder['country'] = $country['ename'];
			 $express = array();
			    $go = $this->notice->get_god($fullorder,$shop,$express,$notice[0]);
			    if($go == 1)
			    {
				    $this->fullordertt->save(array('content'=>$fid['content'].'自动发送-成功;','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
			{
				$this->fullordertt->save(array('exstateerror'=>'当前订单状态无匹配模板'),$fid['id']);
			}
	}
	
	public function _webhook()
	{
		$j = '';
		$xq = array();
		$j = file_get_contents('PHP://input');
		$j = json_decode($j, true);
		if(isset($j['type']) && isset($j['data']['order_id']))
		{
			$d = $this->fullordertt->get_orderinfo($j['data']['order_id']);
			if($d)
			{
				$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')
					{
						$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 if(($j['data']['order_status'] == 'IN_TRANSIT' || $j['data']['order_status'] == 'DELIVERED' || $j['data']['order_status'] == 'COMPLETED currently)') && $d['state'] != 216)
					{
						if($d['cf'] == 1 && $d['type'] == 34 && $j['data']['order_status'] == 'IN_TRANSIT')
						{
							$shop = $this->shop->read($d['shop']);
							$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("UPS",$ex) !== false)
							{
								$express = 3;
							}
							else if(stripos("DHL",$ex) !== false)
							{
								$express = 1;
							}
							else if(stripos("FEDEX",$ex) !== false)
							{
								$express = 24;
							}
							else if(stripos("USPS",$ex) !== false)
							{
								$express = 2;
							}
							$time = time();
							$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']);
						}
						$post = $this->fullordertt->read($d['id']);
						if($post['express'] != 0)
						{
						    $this->_znxc($post,$post['orderinfo'],4);
						}
					}
				}
				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();
					header('HTTP/1.1 200 OK');
				}
				else
				{
					$this->db->trans_rollback();
				}
			}
		}
	}
}