| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685 | <?php defined('BASEPATH') OR exit('No direct script access allowed');class Api 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_fullorder_smt','fullorder_smt');		$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_apiyy','apiyy');		$this->load->_model('Model_whlabel_fc','whlabel_fc');		$this->load->_model('Model_shopsku','shopsku');		$this->load->_model('Model_awlgx','awlgx');		$this->load->_model('Model_apitt','apitt');		$this->load->_model('Model_producttitle','producttitle');		$this->load->_model('Model_afspaypal','afspaypal');		$this->load->_model('Model_message','message');		$this->load->_model("Model_zztmpdata",'zztmpdata');		$this->load->_model("Model_logic_ding","logic_ding");		$this->load->_model("Model_customsdeclaration","customsdeclaration");		$this->load->_model("Model_zzjobs","zzjobs");	}	//定义方法的调用规则 获取URI第二段值    public function _remap($arg,$arg_array)    {		if($arg == 'isorder')//添加        {             $this->_isorder();        }		else if($arg == 'tb')//同步独立站        {             $this->_tb();        }		else if($arg == 'waybill')//运单上传独立站        {             $this->_waybill($arg_array);        }		else if($arg == 'waybillemail')        {             $this->_waybillemail($arg_array);        }		else if($arg == 'waybillfs')        {             $this->_waybillfs($arg_array);        }		else if($arg == 'headgear')//传输头套信息        {             $this->_headgear($arg_array);        }		else if($arg == 'fsstate')        {             $this->_fsstate();        }		else if($arg == 'fswaybillemail')        {             $this->_fswaybillemail();        }		else if($arg == 'zz')        {             $this->_zz();        }		else if($arg == 'zzcs')        {             $this->_zzcs();        }		else if($arg == 'cangku')        {             $this->_cangku();        }		else if($arg == 'kc')        {             $this->_kc();        }		else if($arg == 'wlfs')        {             $this->_wlfs();        }		else if($arg == 'query')        {             $this->_query();        }		else if($arg == 'kcjc')        {             $this->_kcjc();        }		else if($arg == 'klarna')        {             $this->_klarna();        }		else if($arg == 'logistics')        {             $this->_logistics();        }		else if($arg == 'hqpaypal')        {             $this->_hqpaypal();        }		else if($arg == 'hqstripe')        {             $this->_hqstripe();        }		else if($arg == 'htmlstock')        {             $this->_htmlstock();        }		else if($arg == 'dhl')        {             $this->_dhl();        }		else if($arg == '17track')        {             $this->_17track();        }		else if($arg == 'zc17track')        {             $this->_zc17track();        }    }	//通过地址直接获取独立站订单信息	public function _isorder()	{		//set_time_limit(0);		$sid = '';$sd = array();		if(isset($_SESSION['api']))		{			$user = $this->user->get_api($_SESSION['api']);		    $user = explode('|',trim($user['shop'],'|'));			foreach ($user as $value) 		    {				$sid .= " id = '$value' or";			}			$sid = " and (".rtrim($sid,'or').")";		}		$post = $this->input->post(NULL, TRUE);		$api = $this->input->get('api',true);		$dshop = $this->input->get('dshop',true);		//@$gethl = $this->hl->get_hl();//获取即时汇率		$gethl = array();		/*  订单号加入键值-k  */		/**		$dataorder = array();		$fdata = $this->fullorder->find_all('dtime > "'.(time()-96*3600).'"','orderinfo');		foreach ($fdata as $v) 		{			$dataorder[$v['orderinfo']] = "";//获取到单号		}		**/		/*  订单号加入键值-j  */		/*  匹配加入  */		$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'],'jm'=>$v['jm'],'spare'=>$vs);					}					else					{					    $dtc[strtolower($vs)] = array('classid'=>$v['classid'],'zh'=>$v['zh'],'id'=>$v['id'],'jm'=>$v['jm'],'spare'=>$vs);					}				}			}			else			{				$dtc[strtolower($v['spare'])] = array('classid'=>$v['classid'],'zh'=>$v['zh'],'id'=>$v['id'],'jm'=>$v['jm'],'spare'=>$v['spare']);			}					}		$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  */		/*  币种加入键值-k  */		$typeclass = array();		$tdata = $this->typeclass->find_all('classid=30','id,title');		foreach ($tdata as $v) 		{			$typeclass[$v['title']] = $v['id'];		}		/*  币种加入键值-j  */		/*  支付方式-k  */		$pay = 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);			}		}		$pay['stripeios'] = $pay['stripe_payments'];		/*  支付方式-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  */		$is = $this->is->find_all('1=1','*','number asc');//获取仓库平匹配表		if(isset($post['is']) || (isset($api) && $api = '89757'))  		{			$tb = 0;			if($dshop)			{				$shop = $this->shop->find_all("id = '$dshop'");			}			else			{			    $shop = $this->shop->find_all("( type = 269 or type = 2768) and tb = 1".$sid);//获取独立站信息			}			foreach ($shop as $value) 		    {				//$value['tbtime'] = 0;				if((time()-$value['tbtime']) < 600)				{					$tb = 1;//正在同步中					break;				}				else				{				    $this->shop->save(array('tbtime'=>time()),$value['id']);				}				$setting = $this->setting->get_settings();				$this->db->trans_begin();				$res = $this->api->get_hq($value['brandname'],$value['shopadmin'],$value);				$sd[] = $res;				$sjc = $setting['sctime'];//时间差 之前是3600 现在为0				if($res)				{					foreach ($res as $v) 		        	{						if(!isset($v['order_id']))						{							continue;						}						if($value['token'] == 'SU')						{							$time = $v['purchased_on']-7*3600-$sjc;//之前是+$sjc						}						else if($value['program'] == 'Shopify')						{							$time = $v['purchased_on'];						}						else						{							if($value['id'] == 1)							{								$time = strtotime($v['purchased_on'])-7*3600-$sjc;//-$sjc;//之前是+$sjc							}							else							{								$time = strtotime($v['purchased_on'])-7*3600-$sjc;//订单时间更为时间戳 //之前是+$sjc							}						}						$num = $this->fullorder->find_count('gtime = "'.date('Ymd',$time).'" and shop = "'.$value['id'].'"');						if($value['program'] == 'Shopify'){							$order_id = $v['order_id'];						}else{							$order_id = $value['id'].$v['order_id'];						}												$tc = 0;						if(isset($v['global_currency_code']))						{						    $tc = isset($typeclass[$v['global_currency_code']])?$typeclass[$v['global_currency_code']]:0;						}						$dataorder = $this->fullorder->get_orderinfo($order_id);						$hmdid = '';						if($value['program'] == 'Shopify' && isset($dataorder['id']))						{							if($v['order_comment'] != $dataorder['clientremarks'])							{								$this->fullorder->save(array('clientremarks'=>$v['order_comment']),$dataorder['id']);							}						}						if(!isset($dataorder['id']))//现在为所有订单都获取。!$ord && strcasecmp($v['isstatus'],'processing') == 0如果没有此订单并且订单状态为等待发货则继续						{							if(!isset($cuy[$v['country']]))							{    							    $cuy[$v['country']] = 1004;							}			          	    $post = $this->api->get_data($value,$v,$gethl,$time,$cuy[$v['country']],$is,$num,$v['country'],$tc,$dtc,array(),$int,$dtctitle,$pay,$zjsku);							$kn = explode('-',$post['paypal']);							if($post['pay'] == 23 && $value['klarnaname'] != '' && $value['klarnapass'] != '')							{							    $klarna = $this->_klarnadata($post['paypal'],$value['klarnaname'],$value['klarnapass']);								if($klarna != '')								{								    $post['klarnadata'] = $klarna;								}															}							if($post['pay'] == 26 && $value['afterpayname'] != '' && $value['afterpaypass'] != '')							{							    $afterpay = $this->_afterpay($post['paypal'],$value['afterpayname'],$value['afterpaypass']);								if($afterpay != '')								{								    $post['klarnadata'] = $afterpay;								}															}							if($post['pay'] == 27 && $value['clearpayname'] != '' && $value['clearpaypass'] != '')							{							    $clearpay = $this->_clearpay($post['paypal'],$value['clearpayname'],$value['clearpaypass']);								if($clearpay != '')								{								    $post['klarnadata'] = $clearpay;								}															}							if($post['pay'] == '28' && $post['state'] != '207')							{								continue;							}							if($post['state'] == '217' || $post['state'] == '203')							{								continue;							}							/**							else if($post['pay'] == 22 && $value['paypalname'] != '' && $value['paypalpass'] != '')							{							    $paypal = $this->_paypaldata($post['paypal'],$value['paypalname'],$value['paypalpass']);								if($paypal != '')								{								    $post['klarnadata'] = $paypal;								}															}							**/														/** 启用自动分配仓库 **/							$post['express'] = 0;							$warehouse = $this->warehouse->find_all("fpzd = '1'",'*','fpsx desc');							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 > 4)							{								$post['express'] = 63;							}							if($post['express'] > 0)							{								$xze = $this->express->read($post['express']);								$post['printtype'] = $xze['type'];							}							//自动写位置 开始							$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,' ');									$tmp_vv = str_replace("'","",$vv);									$lp = $this->typeclass->find_all("zh = '$tmp_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,'-'));								//$ts += $num[1];								//判断是否是礼物  礼物不计数								$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("%.2f",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['insurance'] = 1;							$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->fullorder->insert($post);			   		   					   		  			   		   									if($post['email'] == '')							{								$post['email'] = $post['name'].'@qq.com';							}							$adrs = $this->customer->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 = '';							$customerb = $this->customer->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->customer->save(array('time'=>$post['dtime'],'is_tb'=>0,'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'] = 10;								$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'];								$ct['is_tb'] = 0;			     				$khid = $this->customer->insert($ct);								$pdlkh = 0;							}							$this->_znxc($post,$order_id,$lkh,$pdlkh,$hmdid);							/**							if($post['shop'] == '1' || $post['shop'] == '2' || $post['shop'] == '6' || $post['shop'] == '5')							{								$this->_znxc($post,$order_id,$lkh);							}							else							{							    $this->_znx($post,$order_id,$lkh);							}							**/						}//else{}如果有此订单					}				}				if ($this->db->trans_status() === FALSE)                {				    $this->db->trans_commit();                }                else                {                    $this->db->trans_commit();                }				usleep(50);//停留2秒			}			if($tb == 1)			{				echo json_encode(array('msg'=>'有店铺正在同步中,请5分钟后再试!','success'=>true));exit;			}			echo json_encode(array('msg'=>'OK!','success'=>true));exit;		}	}	public function _tb()	{		$api = $this->input->get('api',true);		if(isset($api) && $api = '89757')  		{			$data = $this->fullorder->find_all('dlz < 1 and source != 1 and waybill != "" and dtime > "'.(time()-48*3600).'"');			$dataorder = array();$datashop = array();$dataex = array();$datack = array();			/*  店铺加入键值-j  */			$fshop = $this->shop->find_all('1=1');			foreach ($fshop as $v) 			{				$datashop[$v['id']] = $v;			}			/*  店铺加入键值-k  */			/*  快递加入键值-j  */			$fex = $this->express->find_all('1=1');			foreach ($fex as $v) 			{				$dataex[$v['id']] = $v;			}			/*  快递加入键值-k  */			/*  仓库加入键值-k  */			$fwh = $this->warehouse->find_all('1=1');			foreach ($fwh as $v) 			{				$datack[$v['id']] = $v;			}			/*  仓库加入键值-j  */			//$fs = $this->notice->get_ordertatus(216);//216成功状态			foreach ($data as $v)		    {				if($v['shop'] == 5){					$ddh = $v['orderinfo'];				}else{					$ddh = substr($v['orderinfo'],1);				}			    			    $ydh = $v['waybill'];			    $xg = $v;//此订单数据			    $shop = $datashop[$xg['shop']];//此订单店铺			    $ex = $dataex[$xg['express']];//此订单快递			    $warehouse = $datack[$xg['type']];//此订单仓库				$shopifyid = $v['shopify'];				if($xg['shop'] < 7)				{		            $xg['iscode'] = $ex['title'];		            $xg['url'] = $shop['shopname'];				    @$fs = $this->api->get_paypal($xg);					$this->afspaypal->insert(array('number'=>$xg['number'],'cs'=>$fs));				}				$ms = $this->message->find_all("express like '%,".$xg['express'].",%'");				if(!isset($ms[0]))				{					$ms = $this->message->read(2);				}				else				{					$ms = $ms[0];				}				$shopname = $shop['brandname'];  //店铺名				$buyername = $xg['bname'];   //Bill Name				$email_call = $shop['shopid']; //发货人邮箱;				$phone = $shop['shopphone'];   //发货人电话				$track_type = $ex['title'];   //快递名称				$service = $ex['title'];   //快递追踪名称				$track_link = $ex['url'];   //快递查询网址				$logistics_number = $ydh;    //运单号				$t= array('%buyername%','%email_call%','%track_type%','%service%','%track_link%','%logistics_number%','%shop%','%phone%','%jtime%');				$h= array($buyername,$email_call,$track_type,$service,$track_link,$logistics_number,$shopname,$phone,$ex['yjtime']);				$remark = str_replace($t,$h,$ms['content']);			    @$gx = $this->api->get_gx($ddh,$ydh,$xg,$shop,$ex,$remark,$shopifyid);				if(!isset($gx['res']))				{					continue;				}			    $this->fullorder->save(array('dlz'=>$gx['res'],'state'=>$gx['state']),$v['id']);			}		}	}		//更新独立站运单信息	public function _waybill($arg_array)	{		$where = "dlz < '1' and state = '207' and  shop != '19' and ";		if(date("H",time()) == '8' && date("i",time()) > '20' && date("i",time()) < '39')//USPS-USA单,已出库——使用模板3 每天早上8点半  触发发送【昨天早上7点-今天早上7点】出库的		{			$where .= "(express = '2' or express = '63' or express = '64') and librarytime > '".strtotime(date("Y-m-d 7:00:0",strtotime("-1 day")))."' and librarytime < '".strtotime(date("Y-m-d 7:00:0",time()))."'";			$readid = 3;		}		else if(date("H",time()) == '21' && date("w",time()) != '0')//二、杭州联邦+杭州联邦-不报关,单独用一个模板—新模板2 每天晚上9点半 触发发送 【昨天晚上9:30——今天晚上9:30】出库的		{			if(date("w",time()) == '1')//周一执行:周六晚上9点半——周一晚上9点半 之间出库的			{			    $where .= "(express = '24' or express = '31') and librarytime > '".strtotime(date("Y-m-d 21:00:0",strtotime("-2 day")))."' and librarytime < '".strtotime(date("Y-m-d 21:00:0",time()))."'";			}			else //周二到周六: 前一天晚上9点半——当天晚上9点半之间出库的			{				$where .= "(express = '24' or express = '31') and librarytime > '".strtotime(date("Y-m-d 21:00:0",strtotime("-1 day")))."' and librarytime < '".strtotime(date("Y-m-d 21:00:0",time()))."'";			}			$readid = 2;		}		else if(date("H",time()) == '19' && date("w",time()) != '0')//其他快递-使用模板1 DHL官方、UPS、DPEX 等系统里打印运单自动有运单号的,出库后当天晚上7点执行。		{			if(date("w",time()) == '1')//周一执行:周六晚上9点半——周一晚上9点半 之间出库的			{			    $where .= "express != '2' and express != '24' and  express != '31' and printtype = '1' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 19:00:0",strtotime("-2 day")))."' and librarytime < '".strtotime(date("Y-m-d 19:00:0",time()))."'";			}			else //周二到周六: 前一天晚上9点半——当天晚上9点半之间出库的			{				$where .= "express != '2' and express != '24' and  express != '31' and printtype = '1' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 19:00:0",strtotime("-1 day")))."' and librarytime < '".strtotime(date("Y-m-d 19:00:0",time()))."'";			}			$readid = 1;		}		else if(date("H",time()) == '20' && date("w",time()) != '0')//特殊快递 有运单 但是打印状态是发货单		{			if(date("w",time()) == '1')//周一执行:周六晚上9点半——周一晚上9点半 之间出库的			{			    $where .= "express = '71' and printtype = '2' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 20:00:0",strtotime("-2 day")))."' and librarytime < '".strtotime(date("Y-m-d 20:00:0",time()))."'";			}			else //周二到周六: 前一天晚上9点半——当天晚上9点半之间出库的			{				$where .= "express = '71' and printtype = '2' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 20:00:0",strtotime("-1 day")))."' and librarytime < '".strtotime(date("Y-m-d 20:00:0",time()))."'";			}			$readid = 1;		}		else		{			exit;		}			$dataorder = array();$datashop = array();$dataex = array();$datack = array();		//  订单加入键值-k 		$fdata = $this->fullorder->find_all($where);//,'source,id,orderinfo,waybill,shop,express,type,msg,bname,state,client,name,phone,zipcode,address,email,shopify'			//*  订单加入键值-j 		//*  店铺加入键值-j 		$fshop = $this->shop->find_all('1=1');		foreach ($fshop as $v)		{			$datashop[$v['id']] = $v;		}		//*  店铺加入键值-k 		//*  快递加入键值-j 		$fex = $this->express->find_all('1=1');		foreach ($fex as $v) 		{			$dataex[$v['id']] = $v;		}		//*  快递加入键值-k 		//*  仓库加入键值-k 		$fwh = $this->warehouse->find_all('1=1');		foreach ($fwh as $v) 		{			$datack[$v['id']] = $v;		}		//*  仓库加入键值-j 		$i = 0;$j = 0;$ed = array();		foreach ($fdata as $key=>$value)		{			if($value['source'] == 1)			{				$this->fullorder->save(array('dlz'=>3,'state'=>216),$value['id']);			}			else			{				if($value['shop'] == 5){					$ddh = $value['orderinfo'];				}else{					$ddh = substr($value['orderinfo'],1);				}			    			    $ydh = $value['waybill'];			    $xg = $value;//此订单数据			    $shop = $datashop[$xg['shop']];//此订单店铺			    $ex = $dataex[$xg['express']];//此订单快递			    $warehouse = $datack[$xg['type']];//此订单仓库				$shopifyid = $value['shopify'];				if($xg['shop'] < 7)				{		            $xg['iscode'] = $ex['title'];		            $xg['url'] = $shop['shopname'];				    @$fs = $this->api->get_paypal($xg);					$this->afspaypal->insert(array('number'=>$xg['number'],'cs'=>$fs));				}				$ms = $this->message->find_all("express like '%,".$xg['express'].",%'");				if(!isset($ms[0]))				{					$ms = $this->message->read(2);				}				else				{					$ms = $ms[0];				}				$shopname = $shop['brandname'];  //店铺名				$buyername = $xg['bname'];   //Bill Name				$email_call = $shop['shopid']; //发货人邮箱;				$phone = $shop['shopphone'];   //发货人电话				$track_type = $ex['title'];   //快递名称				$service = $ex['title'];   //快递追踪名称				$track_link = $ex['url'];   //快递查询网址				$logistics_number = $ydh;    //运单号				$t= array('%buyername%','%email_call%','%track_type%','%service%','%track_link%','%logistics_number%','%shop%','%phone%','%jtime%');				$h= array($buyername,$email_call,$track_type,$service,$track_link,$logistics_number,$shopname,$phone,$ex['yjtime']);				$remark = str_replace($t,$h,$ms['content']);				// $this->logic_ding->sendToDing("erp同步独立站的信息ddh".json_encode($ddh));				// $this->logic_ding->sendToDing("erp同步独立站的信息ydh".json_encode($ydh));				// $this->logic_ding->sendToDing("erp同步独立站的信息xg".json_encode($xg));				// $this->logic_ding->sendToDing("erp同步独立站的信息shop".json_encode($shop));				// $this->logic_ding->sendToDing("erp同步独立站的信息ex".json_encode($ex));				// $this->logic_ding->sendToDing("erp同步独立站的信息remark".json_encode($remark));			    @$gx = $this->api->get_gx($ddh,$ydh,$xg,$shop,$ex,$remark,$shopifyid);				//$this->logic_ding->sendToDing("erp同步独立站的信息".json_encode($gx));				if(!isset($gx['res']))				{					continue;				}			    $this->fullorder->save(array('dlz'=>$gx['res'],'state'=>$gx['state']),$value['id']);			}			//sleep(4);		}		//同步更新 淘宝的运单号		$this->_taobao();		$this->_kcjc();	}		public function _taobao()	{		$data = $this->fullorder->find_all("shop = 19 and dlz != '3' and state = '207' and librarytime > 0");		foreach ($data as $k=>$v)		{			$this->fullorder->save(array('dlz'=>3,'state'=>216),$v['id']);		}	}		public function _kcjc()	{		$gethl = $this->whlabel->find_all("zd != '' and state = '0'");		$b = array();		foreach ($gethl as $k=>$v)		{			$a = $this->fullorder->get_number($v['zd']);			if($a['librarytime'] > 0 && $a['library'] == 2)			{				//$b[] = array($v['sku'],$v['zd']);				$this->whlabel->save(array('state'=>1,'orderinfo'=>$a['orderinfo'],'waybill'=>$a['waybill'],'outk'=>$a['librarytime'],'time'=>$a['librarytime']),$v['id']);			}		}	}		public function _waybillemail($arg_array)	{		$urls = array();$sl = 0;$time = time();		/**		if(date("H",time()) == '8' && date("i",time()) > '20' && date("i",time()) < '39')//USPS-USA单		{			$wid = 1;		}		else if(date("H",time()) == '22' && date("w",time()) != '0' && date("i",time()) > '20' && date("i",time()) < '39')//二、杭州联邦+杭州联邦-不报关		{			if(date("w",time()) == '1')//周一执行:周六晚上9点半——周一晚上9点半 之间出库的			{			    $wid = 2;			}			else //周二到周六: 前一天晚上9点半——当天晚上9点半之间出库的			{				$wid = 3;			}		}		else if(date("H",time()) == '20' && date("w",time()) != '0' && date("i",time()) > '20' && date("i",time()) < '39')//其他快递		{			if(date("w",time()) != '1')			{			    $wid = 4;			}			else			{				$wid = 5;			}		}		**/		if(date("H",time()) == '8' && date("i",time()) > '20' && date("i",time()) < '39')//USPS-USA单		{			$wid = 1;		}		else if(date("H",time()) == '20' && date("i",time()) > '20' && date("i",time()) < '39')//其他快递		{			$wid = 2;		}		else if(date("H",time()) == '21' && date("i",time()) > '20' && date("i",time()) < '39')//其他快递		{			$wid = 3;		}		else		{			exit;		}		$notice = $this->notice->find_all("message = '1' and state = '1' and type = '4' and ktime < '$time' and jtime > '$time'");//已有自动发送,这个是物流发送		foreach ($notice as $key=>$var)		{			$urls[] = array('url'=>'http://1.wepolicy.cn/api/waybillfs?v='.$var['id'],'data'=>array('var'=>$var,'wid'=>$wid));		}		foreach($urls as $value) {		$ch = curl_init();		$url = $value['url'];		curl_setopt($ch,CURLOPT_URL,$url);		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['data'] = $value['data'];        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));		$res = curl_exec($ch);		curl_close($ch);		$sl++;		}		echo $sl;		echo "<pre>";		print_r($urls);	}			public function _waybillfs()	{		$post = $this->input->post(NULL, TRUE);		$data = $this->input->post('data',true);		if($data)		{		    $notice = $data['var'];			$notice['email'] = $this->emaildata->read($notice['email']);			$wid = $data['wid'];			$fsjs = "";			if($wid == 1 && (stripos($notice['express'],',2,') !== false || stripos($notice['express'],',63,') !== false || stripos($notice['express'],',64,') !== false))			{				$js = explode(',',trim($notice['js'],','));				if(count($js) > 1)				{					$fsjs = " and (";				    foreach ($js as $v)				    {					    $fsjs .= "js = '$v' or ";				    }					$fsjs = trim($fsjs,' or ').")" ;				}				else if(count($js) == 1)				{					$fsjs = " and js = '$js[0]'";				}				$where = "(express = '2' or express = '63' or express = '64') and librarytime > '".strtotime(date("Y-m-d 8:30:0",strtotime("-6 day")))."' and librarytime < '".strtotime(date("Y-m-d 8:30:0",time()))."'".$fsjs;//3			}			/**			else if($wid == 2 && stripos($notice['express'],',1,') !== false)			{			 	$where = "(express = '24' or express = '31') and librarytime > '".strtotime(date("Y-m-d 22:00:0",strtotime("-6 day")))."' and librarytime < '".strtotime(date("Y-m-d 22:00:0",time()))."'";//4			}			else if($wid == 3 && stripos($notice['express'],',1,') !== false)			{				$where = "(express = '24' or express = '31') and librarytime > '".strtotime(date("Y-m-d 22:00:0",strtotime("-6 day")))."' and librarytime < '".strtotime(date("Y-m-d 22:00:0",time()))."'";//3			}			else if($wid == 4 && stripos($notice['express'],',1,') !== false)			{				$where = "express != '2' and express != '24' and  express != '31' and printtype = '1' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 20:00:0",strtotime("-6 day")))."' and librarytime < '".strtotime(date("Y-m-d 20:00:0",time()))."'";//3			}			else if($wid == 5 && stripos($notice['express'],',1,') !== false)			{				$where = "express != '2' and express != '24' and  express != '31' and printtype = '1' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 20:00:0",strtotime("-6 day")))."' and librarytime < '".strtotime(date("Y-m-d 20:00:0",time()))."'";//4			}			**/			else if($wid == 2 && stripos($notice['express'],',1,') !== false)			{			 	$where = "express != '2' and express != '63' and  express != '64'  and printtype = '1' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 20:00:0",strtotime("-6 day")))."' and librarytime < '".strtotime(date("Y-m-d 20:00:0",time()))."'";//4			}			else if($wid == 3 && stripos($notice['express'],',1,') !== false)			{			 	$where = "express = '71'  and printtype = '2' and waybill != '' and librarytime > '".strtotime(date("Y-m-d 20:00:0",strtotime("-6 day")))."' and librarytime < '".strtotime(date("Y-m-d 20:00:0",time()))."'";//4			}			else			{				exit;			}		    $wlfs = array();		    $dd = $this->fullorder->find_all("source != '1' and dlzemail < '1' and shop = '".$notice['shop']."' and library = 2 and ".$where);		    //$this->logic_ding->sendToDing("获取发送快件的快递条件"."source != '1' and dlzemail < '1' and shop = '".$notice['shop']."' and library = 2 and ".$where);		    foreach ($dd as $v)		    {			    $shop = $this->shop->read($v['shop']);			    $express = $this->express->read($v['express']);				if(empty($v['send_email'])){					$fs = $this->notice->get_god($v,$shop,$express,$notice);				}else{					$email = $v['email'];					$v['email'] = $v['send_email'];					$fs = $this->notice->get_god($v,$shop,$express,$notice);					$v['email'] = $email;				}			    //$this->logic_ding->sendToDing($v['orderinfo']."监听邮件发送的异常:订单信息【".json_encode($v,JSON_UNESCAPED_UNICODE)."】获取快递信息【".json_encode($notice,JSON_UNESCAPED_UNICODE)."】返回的信息".json_encode($fs));			    if($fs == 1)			    {				    $this->fullorder->save(array('dlzemail'=>1,'dlzemailtime'=>time()),$v['id']);				    				    //给crm发送信息 先存储数据 后续定时任务执行					if($v['shop'] < 10){												$this->zztmpdata->insert([							'type'=>2,							'act_name'=>'crm_order',							'content'=>json_encode($v),							'create_time'=>time()						]);											}				    				    			    }			    else			    {					//$pdtime = date('Y-m-d',time());					//$folderPath = './data/dlzemail/'.$pdtime; // 文件夹路径					//$permissions = 0777; // 权限设置					//if (!file_exists($folderPath)) { mkdir($folderPath, $permissions); }//创建文件夹					//file_exists($folderPath);					if(!is_file("./data/dlzemail/".$v['number'].".txt"))					{						$myfile = fopen("./data/dlzemail/".$v['number'].".txt", "w") or die("Unable to open file!");						fwrite($myfile, json_encode($fs.';'.$v.';'.$shop.';'.$express.';'.$notice));						fclose($myfile);					}					else					{						$myfile = fopen("./data/dlzemail/".$v['number'].".txt", "a+") or die("Unable to open file!");						fwrite($myfile, json_encode($fs.';'.$v.';'.$shop.';'.$express.';'.$notice));						fclose($myfile);					}				    $this->fullorder->save(array('dlzemail'=>2,'dlzemailtime'=>time()),$v['id']);			    }			    sleep(50);		    }		}	}			/**	//更新独立站运单信息	public function _waybill($arg_array)	{		//这里订单索引需要修改  8点是出已打印已出库   11点是已打印未出库 		if(!isset($arg_array[0]) || !isset($arg_array[1]))		{			exit;		}		if(date("w",time()) == '0' && $arg_array[0] != '3')//非usps周日不更新		{			echo 7;exit;		}		if($arg_array[0] == 3)		{			$argarray = 2;			$typec = ' and express = 2 and printtime > "'.strtotime("-3 day").'"';//更新usps-usa快递的订单		}		else		{			$argarray = $arg_array[0];			$typec = ' and librarytime > "'.strtotime(date("Y-m-d 16:30:0",strtotime("-5 day"))).'" and librarytime < "'.strtotime(date("Y-m-d 18:0:0",time())).'"';//更新快递的订单		}		$dataorder = array();$datashop = array();$dataex = array();$datack = array();		//  订单加入键值-k 		$fdata = $this->fullorder->find_all('state = "207" and print = "3" and dlz < "1" and libraryconfirm = "2" and library = "'.$argarray.'" and waybill != ""'.$typec,'source,id,orderinfo,waybill,shop,express,type,msg,bname,state,client,name,phone,zipcode,address,email');		//*  订单加入键值-j 		//*  店铺加入键值-j 		$fshop = $this->shop->find_all('1=1');		foreach ($fshop as $v)		{			$datashop[$v['id']] = $v;		}		//*  店铺加入键值-k 		//*  快递加入键值-j 		$fex = $this->express->find_all('1=1');		foreach ($fex as $v) 		{			$dataex[$v['id']] = $v;		}		//*  快递加入键值-k 		//*  仓库加入键值-k 		$fwh = $this->warehouse->find_all('1=1');		foreach ($fwh as $v) 		{			$datack[$v['id']] = $v;		}		//*  仓库加入键值-j 		//$fs = $this->notice->get_ordertatus(216);//216成功状态		$i = 0;$j = 0;$ed = array();		foreach ($fdata as $key=>$value)		{			if($value['source'] == 1)			{				$this->fullorder->save(array('dlz'=>3,'state'=>216),$value['id']);			}			else			{			    $ddh = substr($value['orderinfo'],1);			    $ydh = $value['waybill'];			    $xg = $value;//此订单数据			    $shop = $datashop[$xg['shop']];//此订单店铺			    $ex = $dataex[$xg['express']];//此订单快递			    $warehouse = $datack[$xg['type']];//此订单仓库			    //独立站地址更新订单状态、物流信息				if($arg_array[0] == 1)//23点更新用留言2				{					$readid = 2;				}				else if($arg_array[0] == 3)//7点更新用留言3				{					$readid = 3;				}				else //20点更新用默认留言(默认留言为1)				{					$readid = $xg['msg'];				}			    @$gx = $this->api->get_gx($ddh,$ydh,$xg,$shop,$ex,$readid);				if(!isset($gx['res']))				{					exit;				}			    $this->fullorder->save(array('dlz'=>$gx['res'],'state'=>$gx['state']),$xg['id']);			}						//if($gx['res'] == 1 && $fs)			//{			//	$ck = $this->_email($fs['content'],$xg,$warehouse['company']);			//}				sleep(2);//停留2秒		}    }	**/		public function _headgear($arg_array)	{		$ip = $this->input->ip_address(); 		if(!isset($arg_array[0]) || !isset($arg_array[1]))		{			exit;		}		if(!is_numeric($arg_array[0]) || !is_numeric($arg_array[1]))		{			exit;		}		$where = 'printtime > "'.strtotime(date('Y-m-d',$arg_array[0])).'" and print = 3 and library = 1 and (type = 4 or type = 13 or type = 11 or type = 12 or type = 16)';//(type = 4 or type = 7)		if($arg_array[1] == 1)		{		    $data = $this->fullordersmt->find_all($where,'express,number,orderinfo,shipremarks,printtime');		}		else		{			$data = $this->fullorder->find_all($where,'express,number,orderinfo,shipremarks,printtime');		}		foreach ($data as $k=>$v)		{			$express = $this->express->read($v['express']);			$data[$k]['express'] = $express['servicename'];			if($data[$k]['printtime'] > 0)			{			    $data[$k]['printtime'] = date('Y-m-d H:i:s',$v['printtime']);			}		}		//$state = $this->api->get_headgear($data);		echo json_encode($data);    }		public function _kc_old()	{		$post = $this->input->post(NULL, TRUE);		if(isset($post['sku']))		{			$sku = $this->input->post('sku',true);			$warehouse = $this->warehouse->find_all();			$data = array();			foreach ($sku as $val)		    {				$datasku = array();				foreach ($warehouse as $v)		        {					$z = $this->whlabel->find_count('sku = "'.$val.'" and zd = "" and state = 0 and warehouse = "'.$v['id'].'"');					$datasku[] = array('name'=>$v['title'],'number'=>$z);				}				$data[$val] = $datasku;			}		}		echo json_encode($data);    }		public function _kc()	{			$datasku = array();			$info_list = $this->whlabel->find_pc("warehouse = '5'",'sku,features,warehouse','sku');			foreach ($info_list as $val)			{					$z = $this->whlabel->find_count('sku = "'.$val['sku'].'" and zd = "" and state = 0 and warehouse = "5"');					$datasku[] = array('sku'=>$val['sku'],'number'=>$z);			}		echo json_encode($datasku);    }		public function _fsstate()//订单消息页手动发送	{		$post = $this->input->post(NULL, TRUE);		if(isset($post['s']))  		{            $id_arr = $this->input->post('s');			$notice = $this->input->post('notice');			$noticeid = $this->input->post('noticeid');			$id_arr =  explode(',',trim($id_arr,','));			if(!$id_arr)            {                echo json_encode(array('msg'=>'参数错误!','success'=>false));exit;            }			if($notice == '1' || $notice == '')			{				foreach ($id_arr as $v) 		    	{					$data = $this->fullorder->read($v);					$adrs = $this->customer->get_email($data['email'],$data['shop']);                	//$lkh = ($adrs['type'] == 1)?1:2;//白名单1黑名单2					$lkh = 1;					$pdlkh = ($adrs['num'] > 1)?1:0;//判断是否老客户					$fs = $this->_znxc($data,$data['orderinfo'],$lkh,$pdlkh);					if($fs == 1)					{						$this->fullorder->save(array('exstateerror'=>''),$data['id']);					}					sleep(40);            	}			}			else			{                foreach ($id_arr as $v) 		        {				    $data = $this->fullorder->read($v);				    $fs = $this->_sdfs($data,$noticeid);					sleep(40);                }			}							echo json_encode(array('msg'=>'发送完成!','id'=>$id_arr,'success'=>true));exit;		}	}			public function _fswaybillemail()//运单号通知页手动发送	{		$post = $this->input->post(NULL, TRUE);		if(isset($post['s']))  		{			$time = time();            $id_arr = $this->input->post('s');			$id_arr =  explode(',',trim($id_arr,','));			if(!$id_arr)            {                echo json_encode(array('msg'=>'参数错误!','success'=>false));exit;            }				foreach ($id_arr as $v) 		    	{					$d = $this->fullorder->read($v);					$shop = $this->shop->read($d['shop']);					$ex = $this->express->read($d['express']);					$fs = $this->notice->find_all("shop = '".$d['shop']."' and message = '1' and state = '1' and type = '4' and ktime < '$time' and jtime > '$time'");					$fs = $fs[0];					$fs['email'] = $this->emaildata->read($fs['email']);					if(empty($d['send_email'])){						$ck = $this->notice->get_god($d,$shop,$ex,$fs);					}else{						$email = $d['email'];						$d['email'] = $d['send_email'];						$ck = $this->notice->get_god($d,$shop,$ex,$fs);						$d['email'] = $email;					}					//$this->logic_ding->sendToDing($d['orderinfo']."监听邮件发送的异常:订单信息【".json_encode($d,JSON_UNESCAPED_UNICODE)."】获取快递信息【".json_encode($fs,JSON_UNESCAPED_UNICODE)."】返回的信息".json_encode($ck));					if($ck == 1)					{					    $this->fullorder->save(array('dlzemail'=>1,'dlzemailtime'=>time()),$v);					}					sleep(1);            	}										echo json_encode(array('msg'=>'发送完成!请检查是否成功','id'=>$id_arr,'success'=>true));exit;		}	}		/**	public function _fsstate()//订单消息页手动发送 _znxc 针对模板对应类型发送	{		$post = $this->input->post(NULL, TRUE);		if(isset($post['s']))  		{            $id_arr = $this->input->post('s');            $id_arr =  explode(',',$id_arr);            if(!$id_arr)            {                echo json_encode(array('msg'=>'参数错误!','success'=>false));exit;            }            foreach ($id_arr as $v) 		    {				$data = $this->fullorder->read($v);				$adrs = $this->customer->get_email($data['email'],$data['shop']);                $lkh = ($adrs['type'] == 1)?1:2;//白名单1黑名单2				$fs = $this->_znxc($data,$data['orderinfo'],$lkh);				if($fs == 1)				{					$this->fullorder->save(array('exstateerror'=>''),$data['id']);				}				            }			echo json_encode(array('msg'=>'发送完成!','id'=>$id_arr[0],'success'=>true));exit;		}	}	**/	public function _cangku()	{		$post = $this->input->post(NULL, TRUE);		if(isset($post['tk']))  		{			$tk = $this->input->post('tk');			$tj = $this->input->post('tj');			$d = $this->fullorder->find_all("dtime > '$tk' and dtime < '$tj'");			$k = $this->customer->find_all("time > '$tk' and time < '$tj'");			echo json_encode(array('d'=>$d,'k'=>$k));exit;		}	}	public function _znxc($fullorder,$order_id,$lkh,$pdlkh,$hmdid='')	{		$time = time();		$sl = explode(';',$fullorder['quantity']);		$quantity = 0;		foreach ($sl as $v) 		{			if($v > 1)			{				$quantity = 1;			}		}		$fid = $this->fullorder->get_orderinfo($order_id);		if($lkh == 2 || (count($sl) > 1 && $quantity == 1) || stripos($fullorder['address'],'PO ') !== false  || stripos($fullorder['address'],'P.O.') !== false  || stripos($fullorder['address'],'P. O.') !== false  || stripos($fullorder['address'],'PO.') !== false  || stripos($fullorder['address'],'P.O') !== false || stripos($fullorder['address'],' APO ') !== false)//如果是黑名单客户、多产品的、有用户留言的、包含PO BOX、包含APO //留言的正常发$fullorder['clientremarks'] != '' || 		{			$asdasd = 0;			if($lkh == 2)			{				$asdasd = 1;			}			if(count($sl) > 1 && $quantity == 1)			{				$asdasd = 2;			}			if(stripos($fullorder['address'],'PO ') !== false  || stripos($fullorder['address'],'P.O.') !== false  || stripos($fullorder['address'],'P. O.') !== false  || stripos($fullorder['address'],'PO.') !== false  || stripos($fullorder['address'],'P.O') !== false || stripos($fullorder['address'],' APO ') !== false)			{				$asdasd = 3;			}			$this->fullorder->save(array('content'=>$fid['content'].'黑名单客户、多产品的、包含PO BOX、包含APO的不发送-'.$asdasd.(($hmdid)?'['.$hmdid.']':''),'zdstate'=>$fid['zdstate'].'1-x|'),$fid['id']);//留言的现在正常发			return 'a';		}		else		{			if(count($sl) == '1' && $fullorder['quantity'] > 1)//如果item(产品)是1,但quantity大于等于2		    {			    $tab = 2;		    }		    else if($fullorder['shouldmoney'] > '400' && $fullorder['guarantee'] == 'Ineligible')//如果金额大于400美元并且无卖家保障		    {			    $tab = 1;		    }			/**			else if(count($sl) == '1' && $fullorder['quantity'] > 1 && $fullorder['baddress'] != $fullorder['saddress'])//如果item(产品)是1,但quantity大于等于2并且Bill Address不等于Ship Address		    {			    $tab = 4;		    }			else if($fullorder['baddress'] != $fullorder['saddress'])//如果Bill Address不等于Ship Address		    {			    $tab = 3;		    }			**/		    else//常规模板		    {			    $tab = 0;		    }		    $notice = $this->notice->find_all("shop = '".$fullorder['shop']."' and ordertatus = '".$fullorder['state']."' and tab = '$tab' and message = '1' and state = '1' and ktime < '$time' and jtime > '$time'");//有条件不同模板匹配		    if(isset($notice[0]['content']))		    {			    if($pdlkh == '1' && $notice[0]['thq'] != ''&& $notice[0]['thh'] != '')//非常规和老客户模板,如果是老客户并且需要替换的话			    {				    $notice[0]['content'] = str_replace($notice[0]['thq'],$notice[0]['thh'],$notice[0]['content']);			    }			    $shop = $this->shop->read($fullorder['shop']);			    //$express = $this->express->read($fullorder['express']);			    //$service = $this->service->read($express['service']); 			    $country = $this->country->read($fullorder['country']);			    $fullorder['country'] = $country['ename'];			    //$express['servicename'] =$service['title'];//增加快递名称			    $express = array();				$notice[0]['email'] = $this->emaildata->read($notice[0]['email']);			    				if(empty($fullorder['send_email'])){					$go = $this->notice->get_god($fullorder,$shop,$express,$notice[0]);				}else{					$email = $fullorder['email'];					$fullorder['email'] = $fullorder['send_email'];					$go = $this->notice->get_god($fullorder,$shop,$express,$notice[0]);					$fullorder['email'] = $email;				}				//$this->logic_ding->sendToDing($fullorder['orderinfo']."监听邮件发送的异常:订单信息【".json_encode($fullorder,JSON_UNESCAPED_UNICODE)."】获取快递信息【".json_encode($notice[0],JSON_UNESCAPED_UNICODE)."】返回的信息".json_encode($go));			    if($go == 1)			    {				    $this->fullorder->save(array('content'=>$fid['content'].'自动发送-成功;','zdstate'=>$fid['zdstate'].$notice[0]['type'].'-'.$notice[0]['tab'].'|','exstateerror'=>''),$fid['id']);					return 1;			    }			    else			    {				    $this->fullorder->save(array('exstateerror'=>'自动发送失败1:'.date('Y-m-d H',time()).'-'.$go.'('.$notice[0]['type'].'-'.$notice[0]['message'].')'),$fid['id']);			    }		    }			else			{				$this->fullorder->save(array('exstateerror'=>'当前订单状态无匹配模板'),$fid['id']);			}		}	}		public function _sdfs($fullorder,$id)//手动发送信息	{		$time = time();		$notice = $this->notice->read($id);//无条件同模板匹配		$notice['email'] = $this->emaildata->read($notice['email']);		$shop = $this->shop->read($fullorder['shop']);		$express = $this->express->read($fullorder['express']);		if($notice['type'] == '1')		{			$fslx = 'tab';			$content = '自动发送';			$stripos = '1-';		}		else if ($notice['type'] == '2')		{			$fslx = 'logisticstatus';			$content = $notice['title'];			$stripos = $notice['type'].'-'.$notice[$fslx].'|';		}		if(stripos($fullorder['zdstate'],$stripos) === false && $fullorder['wltype'] == '0')//如果没发送过并且允许发送		{			if(empty($fullorder['send_email'])){				$go = $this->notice->get_god($fullorder,$shop,$express,$notice);			}else{				$email = $fullorder['email'];				$fullorder['email'] = $fullorder['send_email'];				$go = $this->notice->get_god($fullorder,$shop,$express,$notice);				$fullorder['email'] = $email;			}			//$this->logic_ding->sendToDing($fullorder['orderinfo']."监听邮件发送的异常:订单信息【".json_encode($fullorder,JSON_UNESCAPED_UNICODE)."】获取快递信息【".json_encode($notice,JSON_UNESCAPED_UNICODE)."】返回的信息".json_encode($go));		    if($go == 1)		    {				if($notice['type'] == '1')				{			       $this->fullorder->save(array('content'=>$fullorder['content'].$content.'-成功;','zdstate'=>$fullorder['zdstate'].$notice['type'].'-'.$notice[$fslx].'|','exstateerror'=>'','wlerror'=>''),$fullorder['id']);				}				else if ($notice['type'] == '2')				{					$this->fullorder->save(array('wlcontent'=>$fullorder['wlcontent'].$content.'-成功;','wlfstime'=>time(),'zdstate'=>$fullorder['zdstate'].$notice['type'].'-'.$notice[$fslx].'|','exstateerror'=>'','wlerror'=>''),$fullorder['id']);				}			     return 1;		    }		    else		    {				if($notice['type'] == '1')				{			        $this->fullorder->save(array('exstateerror'=>$content.'发送失败1:'.date('Y-m-d H',time()).'-'.$go.'('.$notice['type'].'-'.$notice[$fslx].')'),$fullorder['id']);				}				else if ($notice['type'] == '2')				{					$this->fullorder->save(array('wlerror'=>$content.'发送失败2:'.date('Y-m-d H',time()).'-'.$go.'('.$notice['type'].'-'.$notice[$fslx].')'),$fullorder['id']);				}		    }		}	}		public function _zz()	{		//$f = $this->fullorder->find_all("1=1",'wlfstime','wlfstime desc',0,2);		if(date("w") == '0')		{			exit;		}		$f17 = array();		$time = time();		$tjlike = array();		$urls = array();$sl = 0;		$notice = $this->notice->find_all("message = '1' and state = '1' and type = '2' and ktime < '$time' and jtime > '$time'");//已有自动发送,这个是物流发送		foreach ($notice as $key=>$var)		{			$urls[] = array('url'=>'http://a'.rand(10,50).'.wepolicy.cn/api/wlfs?v='.$var['id'],'data'=>array('where'=>array('shop'=>$var['shop'],'expressstate'=>$var['logisticstatus'],'wlcontent'=>$var['title']),'var'=>$var));		}		foreach($urls as $value) {		$tjlike[] = $value['url'];		$ch = curl_init();		$url = $value['url'];		curl_setopt($ch,CURLOPT_URL,$url);		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);		curl_setopt($ch,CURLOPT_HEADER,0);		curl_setopt($ch,CURLOPT_POST, 1);		curl_setopt($ch,CURLOPT_TIMEOUT,5);        //设置post数据		$post = array();		$post['data'] = $value['data'];        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));		$res = curl_exec($ch);		curl_close($ch);		$sl++;		}		echo "<pre>";		print_r($tjlike);		echo $sl;		/**		$urls = array();		$notice = $this->notice->find_all("message = '1' and state = '1' and type = '2' and ktime < '$time' and jtime > '$time'");//已有自动发送,这个是物流发送		foreach ($notice as $key=>$var)		{			$urls[] = array('url'=>'http://1.wepolicy.cn/api/wlfs?v='.$var['id'],'data'=>array('where'=>array('shop'=>$var['shop'],'expressstate'=>$var['logisticstatus'],'wlcontent'=>$var['title']),'var'=>$var));		}	 $mh = curl_multi_init();    $urlHandlers = array();    $urlData = array();    // 初始化多个请求句柄为一个    foreach($urls as $value) {        $ch = curl_init();        $url = $value['url'];        $url .= strpos($url, '?') ? '&' : '?';        curl_setopt($ch, CURLOPT_URL, $url);        // 设置数据通过字符串返回,而不是直接输出        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		curl_setopt($ch,CURLOPT_HEADER,0);		curl_setopt($ch,CURLOPT_POST, 1);		$post = array();		$post['data'] = $value['data'];        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($post));        $urlHandlers[] = $ch;        curl_multi_add_handle($mh, $ch);    }    $active = null;    // 检测操作的初始状态是否OK,CURLM_CALL_MULTI_PERFORM为常量值-1    do {        // 返回的$active是活跃连接的数量,$mrc是返回值,正常为0,异常为-1        $mrc = curl_multi_exec($mh, $active);    } while ($mrc == CURLM_CALL_MULTI_PERFORM);    // 如果还有活动的请求,同时操作状态OK,CURLM_OK为常量值0    while ($active && $mrc == CURLM_OK) {        // 持续查询状态并不利于处理任务,每60ms检查一次,此时释放CPU,降低机器负载        usleep(50000);        // 如果批处理句柄OK,重复检查操作状态直至OK。select返回值异常时为-1,正常为1(因为只有1个批处理句柄)        if (curl_multi_select($mh) != -1) {            do {                $mrc = curl_multi_exec($mh, $active);            } while ($mrc == CURLM_CALL_MULTI_PERFORM);        }    }    // 获取返回结果    foreach($urlHandlers as $index => $ch) {        $urlData[$index] = curl_multi_getcontent($ch);        // 移除单个curl句柄        curl_multi_remove_handle($mh, $ch);    }    curl_multi_close($mh);	print_r($urlData);	**/		/**		$notice = $this->notice->find_all("message = '1' and state = '1' and type = '2' and ktime < '$time' and jtime > '$time'");//已有自动发送,这个是物流发送		foreach ($notice as $key=>$var)		{			$where = "shop = '".$var['shop']."' and waybill != '' and library = '2' and expressstate <= '".$var['logisticstatus']."' and librarytime > '".(time()-15*24*3600)."' and wlcontent not like '%".$var['title']."%'";//正式发送的时候开启这个"'			//$where = "shop = '2' and waybill != '' and library = '2' and librarytime > '".(time()-15*24*3600)."'";			$ch = curl_init(); 			curl_setopt($ch,CURLOPT_URL,'http://'.$_SERVER['HTTP_HOST'].'/api/wlfs?v='.$var['id']);			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['data'] = array('where'=>$where,'var'=>$var);        	curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));			$res = curl_exec($ch);			curl_close($ch);						//$this->_wlfs($where,$var);		}		**/				/**		$var = $this->notice->read(63);//已有自动发送,这个是物流发送		$where = "shop = '".$var['shop']."' and waybill != '' and library = '2' and expressstate <= '".$var['logisticstatus']."' and librarytime > '".(time()-15*24*3600)."' and wlcontent not like '%".$var['title']."%'";//正式发送的时候开启这个"'		$this->_wlfs($where,$var);		**/			}		public function _wlfs()	{		$webhookregister = 0;		$post = $this->input->post(NULL, TRUE);		$data = $this->input->post('data',true);		$where = $data['where'];		$var = $data['var'];		$wlfs = array();		$shopid = $where['shop'];		@$this->allocation->insert(array('title'=>date('Y-m-d',time()).'-'.$shopid));		$where = "shop = '".$where['shop']."' and waybill != '' and library = '2' and expressstate <= '".$where['expressstate']."' and librarytime > '".(time()-22*24*3600)."' and wlcontent not like '%".$where['wlcontent']."%'";//正式发送的时候开启这个"'		//$where = "shop = '".$where['shop']."' and waybill != '' and library = '2' and express = '3' and librarytime > '1636300800' and wlcontent not like '%".$where['wlcontent']."%'";//正式发送的时候开启这个"'		$this->logic_ding->sendToDing("wlfs执行信息".json_encode($data,JSON_UNESCAPED_UNICODE));		$data = $this->fullorder->find_all($where);		$csck = array();			foreach ($data as $k=>$v)		    {				//$this->logic_ding->sendToDing("获取订单的物流信息".$v['number']);				$vexpress = $v['express'];				$shop = $this->shop->read($v['shop']);				$express = $this->express->read($v['express']);				$service = $this->service->read($express['service']); 				$country = $this->country->read($v['country']);				$v['country'] = $country['ename'];				$express['servicename'] =$service['title'];//增加快递名称				$v['cxcode'] = strtolower($express['cxcode']);//增加快递服务商码				if($v['expressstate'] == $var['logisticstatus'] && $v['wlyc'] == '0' && $v['wltype'] != '1' && $v['source'] != '1')//获取快递状态等于模板状态、订单状态等于模板状态、出库时间大于-、未加入物流异常、允许发送邮件状态、非线下单						{							if($v['shop'] < '7')// && $v['shouldmoney'] > 100)							{								$wlfs[] = array('v'=>$v,'id'=>$var['id']);								//$go = $this->_sdfs($v,$var['id']);//更新顺带发送							}							continue;						}		    	if(($express['cxcode'] == '' && $v['exstateerror'] == '') || ($express['cxcode'] == '' && $v['exstateerror'] != ''))				{					continue;				}				else if($express['cxcode'] == 'usps')//$express['cxcode'] == 'fedex' || $express['cxcode'] == 'dhl' || $express['cxcode'] == 'cne' || $express['cxcode'] == 'dpex' || $express['cxcode'] == 'dpd'				{					/**					if($express['cxcode'] == 'dpex' || $express['cxcode'] == 'dpd')					{						$express['cxcode'] = 'cne';					}					**/					$logistics = $express['cxcode'];				}				// else if($express['cxcode'] == 'yscx'){				// 	//由于云尚接口老是返回状态异常 或者是物流已经签收 但是云尚的却是只有中国阶段的轨迹不符合要求 就此废除				// 	$v['servicename'] =$service['title'];//增加快递名称		    	//     $v['url'] = $express['url'];//增加快递链接				// 	$v['express'] = $vexpress;				// 	$this->zzjobs->insert([				// 		'status'=>0,				// 		'quque'=>'ysgjcx',//云尚轨迹查询				// 		'payload'=>json_encode([				// 			'v'=>$v,				// 			'id'=>$var['id']				// 		],JSON_UNESCAPED_UNICODE),				// 		'do_interval'=>1,				// 		'create_time'=>time()				// 	]);				// 	continue;				// }				else if(($express['cxcode'] == 'ups' && $v['webhookregister'] == 1) || $express['cxcode'] == '17track')				{					continue;				}				else if($express['cxcode'] == 'ups' && $v['webhookregister'] < 1)//使用webhook注册模式  || $express['cxcode'] == '17track'				{					$logistics = $express['cxcode'];					$webhookregister = 1;				}				else				{					//暂时不启用第三方,这里直接跳出					$this->fullorder->save(array('expressstate'=>'99'),$v['id']);					continue;					//$logistics = 'apismt';					//$v['express'] = strtolower($express['cxcode']);//替换为快递服务商码				}				//$this->logic_ding->sendToDing("检测是否检测--".$v['number']."--执行的轨迹追踪信息--".$logistics);		    	$v['servicename'] =$service['title'];//增加快递名称		    	$v['url'] = $express['url'];//增加快递链接		    	@$fs = $this->$logistics->get_logistics($v);				$csck[] = array($v['number'],$fs['f'],$fs['content']);				if(!isset($fs['f']))				{					$fs = $this->$logistics->get_logistics($v);					if(!isset($fs['f']))				    {						continue;					}					if($fs['f'] == '1')					{						$v['express'] = $vexpress;						if($fs['exstate'] > $v['expressstate'] || isset($fs['webhookregister']))						{						    $this->fullorder->save(array('expressstate'=>$fs['exstate'],'excontent'=>$fs['data'],'webhookregister'=>$webhookregister,'wlerror'=>''),$v['id']);						}						if($fs['exstate'] == $var['logisticstatus'] && $v['wlyc'] == '0' && $v['wltype'] != '1' && $v['source'] != '1')//获取快递状态等于模板状态、订单状态等于模板状态、出库时间大于-、未加入物流异常、允许发送邮件状态、非线下单						{							if($v['shop'] < '7')// && $v['shouldmoney'] > 100)							{								$wlfs[] = array('v'=>$v,'id'=>$var['id']);								//$go = $this->_sdfs($v,$var['id']);//更新顺带发送							}						}					}					/**					if($logistics == 'apismt')//第三方未购买,第三方查询直接进入无法查询状态					{					    $this->fullorder->save(array('expressstate'=>'99'),$v['id']);					}					**/				}				else				{					if($fs['f'] == '1')					{						$v['express'] = $vexpress;						if($fs['exstate'] > $v['expressstate'] || isset($fs['webhookregister']))						{						    $this->fullorder->save(array('expressstate'=>$fs['exstate'],'excontent'=>$fs['data'],'webhookregister'=>$webhookregister,'wlerror'=>''),$v['id']);						}						if($fs['exstate'] == $var['logisticstatus'] && $v['wlyc'] == '0' && $v['wltype'] != '1' && $v['source'] != '1')//获取快递状态等于模板状态、订单状态等于模板状态、出库时间大于-、未加入物流异常、允许发送邮件状态、非线下单						{							if($v['shop'] < '7')// && $v['shouldmoney'] > 100)							{								$wlfs[] = array('v'=>$v,'id'=>$var['id']);								//$go = $this->_sdfs($v,$var['id']);//更新顺带发送							}						}					}					else					{						$this->fullorder->save(array('wlerror'=>$fs['content']),$v['id']);					}				}			}		@$this->allocation->insert(array('title'=>$shopid.'-'.json_encode($csck)));		if($wlfs)		{		    foreach ($wlfs as $k=>$v)		    {				$t1 = microtime(true);                $this->_sdfs($v['v'],$v['id']);                $t2 = microtime(true);				$t3 = (40-($t2-$t1) < 1)?1:round(40-($t2-$t1));			    sleep($t3);		    }		}	}		public function _zzold()	{		$data = $this->fullorder->find_all("library = '2' and waybill != '' and exstate != '4' and exstate != '5' and dtime > '1580486400'");		foreach ($data as $k=>$v)		{			$shop = $this->shop->read($v['shop']);			$express = $this->express->read($v['express']);			$service = $this->service->read($express['service']); 			$country = $this->country->read($v['country']);			$v['country'] = $country['ename'];			$express['servicename'] =$service['title'];//增加快递名称		    if($express['cxcode'] == '' && $v['exstateerror'] == '')			{				continue;			}			else if($express['cxcode'] == '' && $v['exstateerror'] != '')			{				continue;			}			else if($express['cxcode'] == 'fedex' || $express['cxcode'] == 'usps' || $express['cxcode'] == 'dhl' || $express['cxcode'] == 'cne' || $express['cxcode'] == 'dpex' || $express['cxcode'] == 'dpd')			{				$logistics = $express['cxcode'];			}			else			{				$logistics = 'apismt';			}			$v['express'] = strtolower($express['cxcode']);//替换为快递服务商码		    $v['servicename'] =$service['title'];//增加快递名称		    $v['url'] = $express['url'];//增加快递链接		    $fs = $this->$logistics->get_logistics($v);			if(!isset($fs['f']))			{				$this->fullorder->save(array('exstate'=>'99'),$v['id']);			}			else			{				if($fs['f'] == '0')				{					$this->fullorder->save(array('excontent'=>$fs['content']),$v['id']);				}				if($fs['f'] == '2')				{									}				else				{				    $this->fullorder->save(array('exstate'=>$fs['exstate'],'excontent'=>$fs['data']),$v['id']);				}			}		}	}		public function _query()	{		header('Access-Control-Allow-Origin: *');		$post = $this->input->post(NULL, TRUE);		if(isset($post['orderinfo']))  		{			$list = array();		    $orderinfo = $this->input->post('orderinfo',true);			$orderinfo = explode(',',trim($orderinfo,','));			foreach ($orderinfo as $v)		    {				$exp="/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";				if(is_numeric($v) && mb_strlen($v) > 8)				{					$w = "orderinfo like '%$v%'";				}				else if(filter_var($v, FILTER_VALIDATE_EMAIL))				{					$w = "email like '%$v%'";				}				else				{					echo json_encode(array('site'=>0,'success'=>true));exit;				}				$data = $this->fullorder->find_all($w." and dtime > '1577811600'");				if(isset($data[0]))				{					if($data[0]['library'] != '2')					{						$list[] = array('orderinfo'=>$v,'site'=>1);					}					else if($data[0]['library'] == '2' && $data[0]['exstate'] == '99')					{						$list[] = array('orderinfo'=>$v,'site'=>2);					}					else if($data[0]['library'] == '2' && $data[0]['exstate'] != '99')					{						if($data[0]['excontent'] != '成功;' && $data[0]['excontent'] != '')						{						    $list[] = array('orderinfo'=>$v,'site'=>3,'data'=>$data[0]['excontent']);						}						else						{							$list[] = array('orderinfo'=>$v,'site'=>2);						}					}				}				else				{					$list[] = array('orderinfo'=>$v,'site'=>0);				}							}			echo json_encode(array('t'=>count($orderinfo),'list'=>$list,'success'=>true));exit;		}	}		public function _logistics()	{		if(isset($_GET['waybill']))  		{			$waybill = $this->input->get('waybill',true);			$s = $this->input->get('shop',true);			//$express = $this->input->get('express',true);			$data = $this->fullorder->get_waybill($waybill);			if(isset($data['excontent']) && $data['excontent'] != '')			{				//$a = $this->$express->get_logistics(array('waybill'=>$waybill));				echo json_encode(array('track'=>array('f'=>1,'data'=>$data['excontent']),'msg'=>'','success'=>1));exit;			}			else			{				$shop = $this->shop->get_shopname($s);				if(!$shop)				{					echo json_encode(array('track'=>'','msg'=>'No logistics information','success'=>0));exit;				}				$data = $this->fullorder->get_orderinfo($shop.$waybill);				if(isset($data['excontent']) && $data['excontent'] != '')				{					echo json_encode(array('track'=>array('f'=>1,'data'=>$data['excontent']),'msg'=>'','success'=>1));exit;				}				echo json_encode(array('track'=>'','msg'=>'No logistics information','success'=>0));exit;			}		}	}	public function _klarna()	{		$shop = array();$cg = array();$sb = array();		$ftime = strtotime(date("Y-m-d 0:00:0",strtotime("-10 day")))+8*3600;		$ttime = strtotime(date("Y-m-d 8:00:0",time()));		$shopdata = $this->shop->find_all("type = '269' and klarnaname != '' and klarnapass != ''");		foreach($shopdata as $v)		{		    $data = $this->fullorder->find_all("paypal like '%-%-%-%' and librarytime > '$ftime' and librarytime < '$ttime' and pay = '23' and library = '2' and source != '1' and klarna < '2' and shop = '".$v['id']."'","id,number,orderinfo,paypal,shouldmoney,shop");		    foreach($data as $val)		    {			    $api = $this->_klarnaapi($val['paypal'],$val['shouldmoney'],$v['klarnaname'],$v['klarnapass']);				$header = $api['header'];				$api = $api['res'];			    if(isset($api['error_messages'][0]))			    {				    if(stripos($api['error_messages'][0],'amount is 0 for') !== false)				    {					    $this->fullorder->save(array('klarna'=>3),$val['id']);						 $sb[] = array($val['number'],$val['orderinfo'],'oooo3');				    }				    else				    {					    $this->fullorder->save(array('klarna'=>1,'klarnaerror'=>$api['error_messages'][0]),$val['id']);					    $sb[] = array($val['number'],$val['orderinfo'],'oooo1');				    }			    }			    else if($api == '')			    {					if(isset($header['http_code']) && $header['http_code'] == 201)					{				        $this->fullorder->save(array('klarna'=>2),$val['id']);				        $cg[] = array($val['number'],$val['orderinfo'],'oooo2');					}					else					{						$this->fullorder->save(array('klarna'=>1,'klarnaerror'=>'未知错误'),$val['id']);				        $sb[] = array($val['number'],$val['orderinfo'],'oooo0');					}			    }				else if(isset($api['cs']))			    {				    $this->fullorder->save(array('klarna'=>1,'klarnaerror'=>'超时'),$val['id']);				    $sb[] = array($val['number'],$val['orderinfo'],'oooo0');			    }			    else			    {				    $this->fullorder->save(array('klarna'=>1,'klarnaerror'=>'未知错误'),$val['id']);				    $sb[] = array($val['number'],$val['orderinfo'],'oooo0');			    }		    }		}		echo "<pre>";		print_r($cg);		echo "<pre>";		print_r($sb);	}	public function _klarnaapi($paypal,$shouldmoney,$name,$pass)	{		$url = 'https://api-na.klarna.com/ordermanagement/v1/orders/'.$paypal.'/captures';		$data = '{"captured_amount": '.str_replace('.','',$shouldmoney).'}';		$header[] = "Content-Type:application/json";        $header[] = "Authorization: Basic ".base64_encode($name.":".$pass);        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);		curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);		curl_setopt($ch, CURLOPT_POST, 1);        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);		curl_setopt($ch, CURLOPT_TIMEOUT, 20);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        $res = curl_exec($ch);		$header = curl_getinfo($ch);		if($res === false)		{			if(curl_errno($ch))			{				return array('res'=>'1','header'=>'','cs'=>1);			}		}		else		{		     $res = json_decode($res,true);		     return array('res'=>$res,'header'=>$header);		}		curl_close($ch);	}		public function _klarnadata($paypal,$name,$pass)    {		$url = 'https://api-na.klarna.com/ordermanagement/v1/orders/'.$paypal;		$header[] = "Content-Type:application/json";        $header[] = "Authorization: Basic ".base64_encode($name.":".$pass);        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        $res = curl_exec($ch);        curl_close($ch);		$res = json_decode($res,true);		$data = '';		if(isset($res['fraud_status']))		{		      //  $data = (($res['fraud_status'] == 'ACCEPTED')?1:2).'|<strong>'.$res['purchase_currency'].($res['order_amount']/100).'</strong> , '.(($res['fraud_status'] != 'ACCEPTED')?'<font style="color:#f00">'.$res['fraud_status'].'</font>':$res['fraud_status']).' , description:'.$res['initial_payment_method']['description'].' , number of installments:'.$res['initial_payment_method']['number_of_installments'].'|'.$res['billing_address']['street_address'].(($res['billing_address']['street_address2']!='')?' '.$res['billing_address']['street_address2']:'').','.$res['billing_address']['city'].','.$res['billing_address']['region'].','.$res['billing_address']['postal_code'].','.$res['billing_address']['country'].','.$res['billing_address']['given_name'].' '.$res['billing_address']['family_name'].','.$res['billing_address']['phone'].','.$res['billing_address']['email'].'|'.str_replace('|','|',$res['shipping_address']['street_address']).(($res['shipping_address']['street_address2']!='')?' '.str_replace('|','|',$res['shipping_address']['street_address2']):'').','.$res['shipping_address']['city'].','.$res['shipping_address']['region'].','.$res['shipping_address']['postal_code'].','.$res['shipping_address']['country'].','.$res['shipping_address']['given_name'].' '.$res['shipping_address']['family_name'].','.$res['shipping_address']['phone'].','.$res['shipping_address']['email'];		      		      	if(isset($res['initial_payment_method']['number_of_installments'])){    				$number_of_installments = $res['initial_payment_method']['number_of_installments'];    			}else{    				$number_of_installments = 0;    			}    		    $data = (($res['fraud_status'] == 'ACCEPTED')?1:2).'|<strong>'.$res['purchase_currency'].($res['order_amount']/100).'</strong> , '.(($res['fraud_status'] != 'ACCEPTED')?'<font style="color:#f00">'.$res['fraud_status'].'</font>':$res['fraud_status']).' , description:'.$res['initial_payment_method']['description'].' , number of installments:'.$number_of_installments.'|'.$res['billing_address']['street_address'].(($res['billing_address']['street_address2']!='')?' '.$res['billing_address']['street_address2']:'').','.$res['billing_address']['city'].','.$res['billing_address']['region'].','.$res['billing_address']['postal_code'].','.$res['billing_address']['country'].','.$res['billing_address']['given_name'].' '.$res['billing_address']['family_name'].','.$res['billing_address']['phone'].','.$res['billing_address']['email'].'|'.str_replace('|','|',$res['shipping_address']['street_address']).(($res['shipping_address']['street_address2']!='')?' '.str_replace('|','|',$res['shipping_address']['street_address2']):'').','.$res['shipping_address']['city'].','.$res['shipping_address']['region'].','.$res['shipping_address']['postal_code'].','.$res['shipping_address']['country'].','.$res['shipping_address']['given_name'].' '.$res['shipping_address']['family_name'].','.$res['shipping_address']['phone'].','.$res['shipping_address']['email'];		    		    		}		return $data;	}		public function _hqpaypal()    {		$shop = $this->shop->find_all("paypalname != ''");		foreach ($shop as $val)		{		    $d = $this->fullorder->find_all("shop = '".$val['id']."' and dtime > '".(time()-(5*24*3600))."' and dtime < '".(time()-(3*3600))."' and (pay = '22' || pay = '7') and klarnadata = ''");		    foreach ($d as $v)		    {			     $paypal = $this->paypal->data($v['paypal'],$val);				 if($paypal != '')			     {				     $this->fullorder->save(array('klarnadata'=>$paypal),$v['id']);			     }		    }		}	}		public function _hqstripe()    {		$shop = $this->shop->find_all("stripe != ''");		foreach ($shop as $val)		{		    $d = $this->fullorder->find_all("shop = '".$val['id']."' and dtime > '".(time()-(5*24*3600))."' and dtime < '".time()."' and pay = '1211' and klarnadata = ''");		    foreach ($d as $v)		    {			     $paypal = $this->_stripe($v['paypal'],$val['stripe']);				 if($paypal != '')			     {				     $this->fullorder->save(array('klarnadata'=>$paypal),$v['id']);			     }		    }		}	}		public function _stripe($pay,$stripe)    {		$url = 'https://api.stripe.com/v1/payment_intents/'.$pay;        $header[] = "Authorization:Bearer ".$stripe;        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        $res = curl_exec($ch);        curl_close($ch);		$res = json_decode($res,true);		$k = '';		if(isset($res['shipping']['name']))		{		    $line = ($res['shipping']['address']['line2'] != '')?$res['shipping']['address']['line1'].' '.$res['shipping']['address']['line2']:$res['shipping']['address']['line1'];		    $k = 'stripe|'.json_encode(array('name'=>$res['shipping']['name'],'email'=>$res['receipt_email'],'address'=>$line.','.$res['shipping']['address']['city'].','.$res['shipping']['address']['state'].','.$res['shipping']['address']['postal_code'].','.$res['shipping']['address']['country'].','.$res['shipping']['phone'],'shouldmoney'=>$res['amount']/100));		}		return $k;	}		public function _afterpay($paypal,$name,$pass)    {		$url = 'https://global-api.afterpay.com/v2/payments?ids='.$paypal;		$header[] = "Accept:application/json";		$header[] = "User-Agent: Readme.io API Simulator'";        $header[] = "Authorization: Basic ".base64_encode($name.":".$pass);        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        $res = curl_exec($ch);        curl_close($ch);		$res = json_decode($res,true);		$data = '';		if(isset($res['results'][0]['orderDetails']['consumer']['email']))		{			$data = $res['results'][0]['orderDetails']['consumer']['email'].'|'.str_replace('|','|',$res['results'][0]['orderDetails']['billing']['line1']).','.str_replace('|','|',$res['results'][0]['orderDetails']['billing']['line2']).','.$res['results'][0]['orderDetails']['billing']['area1'].','.$res['results'][0]['orderDetails']['billing']['region'].','.$res['results'][0]['orderDetails']['billing']['postcode'].','.$res['results'][0]['orderDetails']['billing']['countryCode'].','.$res['results'][0]['orderDetails']['billing']['name'].','.$res['results'][0]['orderDetails']['billing']['phoneNumber'].'|'.str_replace('|','|',$res['results'][0]['orderDetails']['shipping']['line1']).','.str_replace('|','|',$res['results'][0]['orderDetails']['shipping']['line2']).','.$res['results'][0]['orderDetails']['shipping']['area1'].','.$res['results'][0]['orderDetails']['shipping']['region'].','.$res['results'][0]['orderDetails']['shipping']['postcode'].','.$res['results'][0]['orderDetails']['shipping']['countryCode'].','.$res['results'][0]['orderDetails']['shipping']['name'].','.$res['results'][0]['orderDetails']['shipping']['phoneNumber'];			$data = str_replace(',,',',',$data);		}		return $data;	}		public function _clearpay($paypal,$name,$pass)    {		$url = 'https://global-api.afterpay.com/v2/payments?ids='.$paypal;		$header[] = "Accept:application/json";		$header[] = "User-Agent: Readme.io API Simulator'";        $header[] = "Authorization: Basic ".base64_encode($name.":".$pass);        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        $res = curl_exec($ch);        curl_close($ch);		$res = json_decode($res,true);		$data = '';		if(isset($res['results'][0]['orderDetails']['consumer']['email']))		{			$data = $res['results'][0]['orderDetails']['consumer']['email'].'|'.str_replace('|','|',$res['results'][0]['orderDetails']['billing']['line1']).','.str_replace('|','|',$res['results'][0]['orderDetails']['billing']['line2']).','.$res['results'][0]['orderDetails']['billing']['area1'].','.$res['results'][0]['orderDetails']['billing']['region'].','.$res['results'][0]['orderDetails']['billing']['postcode'].','.$res['results'][0]['orderDetails']['billing']['countryCode'].','.$res['results'][0]['orderDetails']['billing']['name'].','.$res['results'][0]['orderDetails']['billing']['phoneNumber'].'|'.str_replace('|','|',$res['results'][0]['orderDetails']['shipping']['line1']).','.str_replace('|','|',$res['results'][0]['orderDetails']['shipping']['line2']).','.$res['results'][0]['orderDetails']['shipping']['area1'].','.$res['results'][0]['orderDetails']['shipping']['region'].','.$res['results'][0]['orderDetails']['shipping']['postcode'].','.$res['results'][0]['orderDetails']['shipping']['countryCode'].','.$res['results'][0]['orderDetails']['shipping']['name'].','.$res['results'][0]['orderDetails']['shipping']['phoneNumber'];			$data = str_replace(',,',',',$data);		}		return $data;	}		public function _htmlstock()	{		if(isset($_GET['hq']))  		{			$ProductsType = $this->typeclass->find_all("classid = '16' and hq = '1'",'id,title','sequence asc');			foreach ($ProductsType as $k=>$v) 		    {				if($v['title'] == 'Closure')				{				    $ProductsType[$k]['title'] = 'Closure/Frontal';				}			}			$HairColor = $this->typeclass->find_all("classid = '8' and hq = '1'",'id,title','sequence asc');			$HairWavy = $this->typeclass->find_all("classid = '15' and hq = '1'",'id,title','sequence asc');			$WigType = $this->typeclass->find_all("classid = '18' and hq = '1'",'id,title','sequence asc');			$Length = $this->typeclass->find_all("classid = '14' and hq = '1'",'id,title','sequence asc');			 echo json_encode(array('ProductsType'=>$ProductsType,'HairColor'=>$HairColor,'HairWavy'=>$HairWavy,'WigType'=>$WigType,'Length'=>$Length));exit;			 //http://1.wepolicy.cn/api/htmlstock?hq=1		}		if(isset($_GET['page']))  		{			$del = array();			$typeclass13 = $this->typeclass->find_all("classid = '13'");			$typeclass16 = $this->typeclass->find_all("classid = '16'");			foreach ($typeclass16 as $key=>$value) 		    {				foreach ($typeclass13 as $v) 		        {				    $del[] = $value['title'].' '.$v['title'];				}			}		    $page = $this->input->get('page',true);		    $perpage = $this->input->get('perpage',true);			$category = $this->input->get('ProductsType',true);//类目			$color = $this->input->get('HairColor',true);//颜色			$lowe = $this->input->get('HairWavy',true);//花型			$lacetype = $this->input->get('WigType',true);//头套种类			$size = $this->input->get('Length',true);//长度			$title = $this->input->get('title',true);//传输文本			$warehouse = 5;			$state = $this->input->get('state',true);			$where = "warehouse = '5' and state = '0'";			if($category)            {                $where  .= " and features like '%-$category-%'";            }			if($color)            {                $where  .= " and features like '%-$color-%'";            }			if($lowe)            {                $where  .= " and features like '%-$lowe-%'";            }			if($lacetype)            {                $where  .= " and features like '%-$lacetype-%'";            }			if($size)            {                $where  .= " and features like '%-$size-%'";            }			if($title)            {                $where  .= " and title like '%$title%'";            }			$order_str = "id desc";            if(empty($page))		    {                $start = 0;		    	$perpage = 1;            }		    else		    {                $start = ($page - 1)*$perpage;            }			$info_list = $this->whlabel->find_pc($where,'sku,features,warehouse','id,warehouse,sku,title,features,number',$order_str,$start,$perpage);			$data = array();			foreach ($info_list as $key=>$value) 		    {				$c = $this->whlabel->find_count($where.' and sku = "'.$value['sku'].'" and state = 0 and warehouse = "5" and features = "'.$value['features'].'" and zd = ""');				if($c > 1)				{				    $data[] = array('Item'=>str_replace($del,'',$value['title']),'Stock'=>$c);				}		    }			$total = count($this->whlabel->find_pc($where,'sku,features,warehouse','id,warehouse,sku,title,features,number'));		    $pagenum = ceil($total/$perpage);		    $over = $total-($start+$perpage);		    $rows = array('total'=>$total,'over'=>$over,'pagenum'=>$pagenum,'rows'=>($data));//总数量,剩余数量,总页数,数据		    echo json_encode($rows);exit;			///api/htmlstock?page=1&perpage=50&ProductsType=&HairColor=&HairWavy=&WigType=&Length= //页数、每页数量、类目、颜色、花型、头套种类、尺寸		}	}		public function _zc17track()	{		$express = array();		$ex = $this->express->find_all("cxcode = '17track'");		foreach ($ex as $v) 		{			$express[$v['id']] = $v['title'];		}		$time_threshold = time() - 12 * 24 * 3600;    	$this->db->select('a.number, a.express,a.waybill');    	$this->db->from('crowd_fullorder as a');    	$this->db->join('express as b', 'a.express = b.id', 'inner');    	$this->db->where('a.waybill !=', '');    	$this->db->where('a.library', '2');     	$this->db->where('a.librarytime >', $time_threshold);    	$this->db->where('a.webhookregister <', 1);    	$this->db->where('b.cxcode', '17track');    	$query = $this->db->get();		$data = $query->result_array();		$fsdata = array();		foreach ($data as $v)		{			if(!isset($express[$v['express']]))			{				continue;			}			if(stripos($express[$v['express']],'DHL') !== false)			{				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'100001');			}			else if(stripos($express[$v['express']],'UPS') !== false)			{ 				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'100002');			}			else if((stripos($express[$v['express']],'FEDEX') !== false)||(stripos($express[$v['express']],'FedEx') !== false) )			{ 				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'100003');			}			else if(stripos($express[$v['express']],'TNT') !== false)			{ 				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'100004');			}			else if(stripos($express[$v['express']],'ARAMEX') !== false)			{ 				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'100006');			}			else if(stripos($express[$v['express']],'YunExpress') !== false){				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'190008');			}			else if(stripos($express[$v['express']],'DEPX') !== false){				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'100014');			}			else if(stripos($express[$v['express']],'EMS') !== false)			{ 				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'3013');			}			else if(stripos($express[$v['express']],'GES') !== false)			{ 				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'190258');			}			else if(stripos($express[$v['express']],'3PE') !== false)			{ 				$fsdata[] = array('number'=>$v['waybill'],'carrier'=>'191376');			}			else			{				$fsdata[] = array('number'=>$v['waybill'],'auto_detection'=>'true');			}		}		$fsdata = array_chunk($fsdata, 40);		$logistics = '17track';		foreach ($fsdata as $v)		{			$fs = $this->$logistics->get_logistics(json_encode($v));			$this->logic_ding->sendToDing("监听17track注册为什么获取不到的原因,请求参数".json_encode($v));			$this->logic_ding->sendToDing("监听17track注册为什么获取不到的原因,返回参数".json_encode($fs));			if(isset($fs['f']))			{				$csck[] = array($v,$fs['f'],$fs['content']);				foreach ($v as $val)				{					$d = $this->fullorder->get_waybill($val['number']);					if($fs['f'] == '1')					{						$this->fullorder->save(array('webhookregister'=>1,'wlerror'=>''),$d['id']);					}					else					{						$this->fullorder->save(array('wlerror'=>$fs['content']),$d['id']);					}				}			}			else			{				$csck[] = array($v,'CW',"CS");			}			sleep(3);		}		@$this->allocation->insert(array('title'=>json_encode($csck)));		/**		$data = $this->fullorder->find_all("waybill != '' and library = '2' and librarytime > '".(time()-12*24*3600)."' and webhookregister < 1");		$csck = array();			foreach ($data as $k=>$v)		    {				$express = $this->express->read($v['express']);				$service = $this->service->read($express['service']); 				$v['servicename'] =$service['title'];//增加快递名称		    	$v['url'] = $express['url'];//增加快递链接				$logistics = '17track';		    	$fs = $this->$logistics->get_logistics($v);				if(isset($fs['f']))				{					$csck[] = array($v['number'],$fs['f'],$fs['content']);					if($fs['f'] == '1')				    {					    $this->fullorder->save(array('webhookregister'=>1,'wlerror'=>''),$v['id']);				    }				    else				    {					    $this->fullorder->save(array('wlerror'=>$fs['content']),$v['id']);				    }				}				else				{					$csck[] = array($v['number'],'CW',"CS");				}				sleep(1);		}		@$this->allocation->insert(array('title'=>$shopid.'-'.json_encode($csck)));		**/	}	public function _17track()	{		$xq = array();		$j = file_get_contents('PHP://input');		//$this->logic_ding->sendToDing("17track返回回调参数".$j);		$j = json_decode($j, true);		$j = $j['data'];		$express = array();		$expressdata = $this->express->find_all('1=1');		foreach ($expressdata as $v) 		{			$express[$v['id']] = $v['title'];		}			//$sh = hash("sha256",$j['event'].'/'.json_encode($j).'/0811AC1711EAABB7D764D04B824F8C2D');							$f = 'fullorder';				$d = $this->fullorder->get_waybill($j['number']);				if(!$d)				{					$f = 'fullordersmt';					$d = $this->fullordersmt->get_waybill($j['number']);					if(!$d)					{						$f = 'fullordertt';						$d = $this->fullordertt->get_waybill($j['number']);					}				}				if(!$d)				{					exit;				}				$state = '';				$zxzt = '';				if(isset($j['track_info'])){					$zxzt = array_reverse($j['track_info']['milestone']);					foreach ($zxzt as $v) 					{						if($v['time_iso'] != NULL)						{							$state = $v['key_stage'];							break;						}					}				}else{					//$this->logic_ding->sendToDing("17track接口返回数据异常,请求参数".json_encode($j));				}								$exstate = 0;//无信息				if($state == 'InfoReceived' || $state == 'PickedUp' || $state == 'Departure' || $state == 'Arrival')//运输途中				{					$exstate = 3;//在途中				}				else if($state == 'OutForDelivery')//派送中				{					$exstate = 4;				}				else if($state == 'Returned' || $zxzt == 'Returning')//投递失败				{					$exstate = 1;//派送异常				}				else if($state == 'Delivered')//成功签收				{					$exstate = 6;//签收				}				//$pd = array();				$pd = "";				$xq = '';								if(isset($j['track_info']['tracking']['providers'][0]['events']))				{					if(empty($j['track_info']['tracking']['providers'][0]['events'])){						$pd = "";					}else{						foreach ($j['track_info']['tracking']['providers'][0]['events'] as $k=>$v) 						{							if($k == 0)							{								$pd = $v['description'];							}							$xq .= date('Y-m-d H:i:s',strtotime($v['time_iso'])).' ['.$v['location'].'] '.$v['description'].'<br />';// a日期 c地址 z状态						}					}				    															if(stripos($express[$d['express']],'Fedex') !== false && stripos($pd,'International shipment release - Import') !== false)					{						$exstate = 4;//即将派送					}					else if(stripos($express[$d['express']],'DHL') !== false && stripos($pd,'Clearance processing complete') !== false)					{						$exstate = 4;//即将派送					}					else if(stripos($express[$d['express']],'UPS') !== false && stripos($pd['c'],'Louisville, KY, US') !== false && stripos($pd,'Departed from Facility') !== false)					{						$exstate = 4;//即将派送					}					else if(stripos($express[$d['express']],'GES') !== false && stripos($pd,'Shipment picked up') !== false)					{						$exstate = 4;//即将派送					}					else if(stripos($pd,'Delivery exception') !== false || stripos($pd,'Addressee Unknown') !== false || stripos($pd,'Delivered to Agent for Final Delivery') !== false || stripos($pd,'Reminder to pick up your item') !== false || stripos($pd,'Available for Pickup') !== false || stripos($pd,'Processing Exception') !== false || stripos($pd,'Return to Sender Processed') !== false || stripos($pd,'Redelivery Scheduled') !== false || stripos($pd,'Notice Left') !== false || stripos($pd,'Delivery attempted but no response at Consignee address') !== false || stripos($pd,'Delivery attempt could not be completed') !== false || stripos($pd,'Forwarded to a third party agent') !== false || stripos($pd,'Awaiting collection by the consignee') !== false || stripos($pd,'Consignee has moved from the address provided') !== false || stripos($pd,'awaiting customer pickup') !== false)					{						$exstate = 1;//异常					}				}				// if(is_array($express[$d['express']]) || is_array($pd)){				// 	$this->logic_ding->sendToDing("17track接口返回信息类型异常".json_encode($express[$d['express']],JSON_UNESCAPED_UNICODE)."===".json_encode($pd,JSON_UNESCAPED_UNICODE)."====".json_encode($j,JSON_UNESCAPED_UNICODE));				// }				$awlgx = $this->awlgx->get_number($d['number']);				if($awlgx)				{					$this->awlgx->save(array("content"=>$xq,"time"=>time(),'exstate'=>$exstate,'type'=>$f),$awlgx['id']);				}				else				{				    $this->awlgx->insert(array("number"=>$d['number'],"content"=>$xq,"time"=>time(),'exstate'=>$exstate,'type'=>$f));				}				if($xq != '')				{				    $this->$f->save(array('expressstate'=>$exstate,'excontent'=>$xq),$d['id']);				    $time = time();				    if($f == 'fullorder')				    {				        $notice = $this->notice->find_all("message = '1' and state = '1' and type = '2' and ktime < '$time' and jtime > '$time' and shop = '".$d['shop']."' and logisticstatus = '".$exstate."'");				        if($notice && $d['wlyc'] == '0' && $d['wltype'] != '1' && $d['source'] != '1' && stripos($d['wlcontent'],$notice[0]['title']) === false)				        {					         $this->_sdfs($d,$notice[0]['id']);					         					         	//给crm发送信息 先存储数据 后续定时任务执行                				if($d['shop'] < 10){                					//派送中                					if($exstate == 4){                						$this->zztmpdata->insert([                							'type'=>3,                							'act_name'=>'crm_order',                							'content'=>json_encode($d),                							'create_time'=>time()                						]);                					}                					//签收完成                					if($exstate == 6){                						$this->zztmpdata->insert([                							'type'=>4,                							'act_name'=>'crm_order',                							'content'=>json_encode($d),                							'create_time'=>time()                						]);                					}                				}				        }				    }				}													}		public function _dhl()//DHL	{		$data = $this->dhl->find_all("type != 1 and time > '".(time()-24*3600)."'");		foreach ($data as $v) 		{			$y = $this->fullorder->get_number($v['number']);			if(!$y)			{				$y = $this->fullordertt->get_number($v['number']);				if(!$y)				{					$y = $this->fullordersmt->get_number($v['number']);					if(!$y)				    {						continue;					}				}			}			//获取dhl规格			$dhl_gg_info = $this->customsdeclaration->get_ename($y['sbpm']);			if(empty($dhl_gg_info)){				continue;			}else{				$y['dhl_ggbm'] = $dhl_gg_info['dhlcode'];			}			$this->dhl->get_data_c($y,$v['id']);		}	}}
 |