| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 | <?phpclass Model_apitt extends Lin_Model {function __construct(){		parent::__construct();		$this->load->_model("Model_logic_ding","logic_ding");}	public function get_list($shop,$from,$to,$order_status,$cuy,$num,$dtc,$money,$int,$dtctitle,$pay,$typeclass,$ex,$sjc,$zjsku)//获取订单列表	{		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/order/202309/orders/search';		$time = time();		$post['create_time_ge'] = $from;		$post['create_time_lt'] = $to;		$post['order_status'] = $order_status;		$queryParams['page_size'] = 100;		$queryParams['sort_order'] = 'ASC';		$queryParams['sort_field'] = 'create_time';		$queryParams['shop_cipher'] =$shop['shop_cipher'];		$queryParams['shop_id'] =$shop['codeid'];		$queryParams['app_key'] =$shop['app_key'];		$queryParams['shop_cipher'] =$shop['shop_cipher'];		$queryParams['timestamp'] =$time;		$link .= '?'.http_build_query($queryParams);		$sign = $this->sign($link,$shop['app_secret'],$post);		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->su_curl($post,$url,$headers);		//$this->logic_ding->sendToDing($shop['shopname']."测试获取TT订单".$res);		$res = json_decode($res,true);		$list = array();$page_token = '';$arr = array();		if(isset($res['data']['orders']))		{			foreach ($res['data']['orders'] as $val) 		    {				 $d = $this->fullordertt->get_orderinfo($val['id']);				 if(!$d)				 {					 $list[] = $val['id'];				 }			}			if($res['data']['total_count'] > 100)			{				$page_token = $res['data']['next_page_token'];				$synum = $res['data']['total_count']-100;				if($synum > 100)				{					$synum = ceil($synum/100);				}				else				{					$synum = 1;				}				for($i=0;$i<$synum;$i++)				{					if($page_token)					{					    $net_date = $this->get_next_list($shop,$from,$to,$order_status,$page_token);					    $page_token = $net_date[1];					    foreach ($net_date['0'] as $val) 		        	    {						    $d = $this->fullordertt->get_orderinfo($val['id']);				    	    if(!$d)				    	    {							    $list[] = $val['id'];						    }						}					}				}			}			$cs = array();			if(count($list) > 50)			{				$n = ceil(count($list)/50);$x = 0;				for($i=0;$i<$n;$i++)				{					$k = ($i<1)?0:$i*50;					$data = array_slice($list,$k,50);					$d = $this->get_data($data,$shop);					$cs[] = $d;					if(isset($d['data']))		            {					    foreach ($d['data']['orders'] as $val) 		                {						    $arr[$x] = $val;							$x++;					    }					}				}			}			else			{				$d = $this->get_data($list,$shop);				if(isset($d['data']))		        {					 foreach ($d['data']['orders'] as $val) 		             {						 $arr[] = $val;					 }				}			}		}		$read = array();		$gnum = array();		foreach ($arr as $val) 		{		    			$create_time = substr($val['create_time'],0,10)-$sjc;			if(isset($gnum[date('ymd',$create_time)]))			{				$gnum[date('ymd',$create_time)] += 1;				// if($shop['id'] == 44){    // 		           $this->logic_ding->sendToDing("测试获取TT订单-1-".date('ymd',$create_time)."-".$gnum[date('ymd',$create_time)]);    // 		    }			}			else			{				//$num = $this->fullordertt->find_count('gtime = "'.date('Ymd',$create_time).'" and shop = "'.$shop['id'].'"');				//避免number 冲突的问题    			$info = $this->fullordertt->find('gtime = "'.date('Ymd',$create_time).'" and shop = "'.$shop['id'].'"',"*","id desc");				if(empty($info)){					$num = 0;				}else{					$tmp_number_arr = explode("-",$info['number']);					//合并订单					if(count($tmp_number_arr) == 5){						$num = $this->fullordertt->find_count('gtime = "'.date('Ymd',$create_time).'" and shop = "'.$shop['id'].'"');					}else{						$num = array_pop($tmp_number_arr);						$num = $num*1;					}									}				$gnum[date('ymd',$create_time)] = $num+1;				// if($shop['id'] == 44){    // 		           $this->logic_ding->sendToDing("测试获取TT订单-2-".date('ymd',$create_time)."-".$gnum[date('ymd',$create_time)]);    // 		    }			}			$read[] = $this->get_read($val,$time,$shop,$cuy,$gnum[date('ymd',$create_time)],$dtc,$money,$int,$dtctitle,$pay,$typeclass,$ex,$sjc,$zjsku);		}		return array($read,$list);	}		public function get_next_list($shop,$from,$to,$order_status,$page_token='')//获取订单列表	{		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/order/202309/orders/search';		$time = time();		$post['create_time_ge'] = $from;		$post['create_time_lt'] = $to;		$post['order_status'] = $order_status;		$queryParams['page_size'] = 100;		$queryParams['sort_order'] = 'ASC';		$queryParams['sort_field'] = 'create_time';		$queryParams['shop_cipher'] =$shop['shop_cipher'];		$queryParams['shop_id'] =$shop['codeid'];		$queryParams['app_key'] =$shop['app_key'];		$queryParams['timestamp'] =$time;		if($page_token)		{		    $queryParams['page_token'] = $page_token;		}		$link .= '?'.http_build_query($queryParams);		$sign = $this->sign($link,$shop['app_secret'],$post);		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->su_curl($post,$url,$headers);		$res = json_decode($res,true);		$orders = array();		if(isset($res['data']['orders']))		{			$orders = $res['data']['orders'];		}		return array($orders,$res['data']['next_page_token']);	}		public function get_data($list,$shop)	{		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/order/202309/orders';		$time = time();		$ids = implode(",",$list);		$link .= '?shop_cipher='.$shop['shop_cipher'].'&app_key='.$shop['app_key'].'×tamp='.$time.'&ids='.$ids;		$sign = $this->sign($link,$shop['app_secret'],'');		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->su_curl('',$url,$headers,$date_type='json',$timeout=300,$httptype="GET");		$res = json_decode($res,true);		return $res;	}			public function get_je($d,$shop)//预估到账金额	{		$url = 'https://open-api.tiktokglobalshop.com';		$link = '/finance/202309/orders/'.$d['orderinfo'].'/statement_transactions';		$time = time();		$link .= '?shop_cipher='.$shop['shop_cipher'].'&app_key='.$shop['app_key'].'×tamp='.$time;		$sign = $this->sign($link,$shop['app_secret'],'');		$url .= $link.'&sign='.$sign;		$headers = array('Content-Type: application/json','x-tts-access-token:'.$shop['token']);		$res = $this->su_curl('',$url,$headers,$date_type='json',$timeout=300,$httptype="GET");		$res = json_decode($res,true);		return $res;	}		public function get_read($data,$time,$shop,$cuy,$num,$dtc,$money,$int,$dtctitle,$pay,$typeclass,$ex,$sjc,$zjsku)	{		$purl = 'https://shop.tiktok.com/view/product/';		$link = '';$product = '';$sku = '';$quantity = '';$price = "";$row_total ="";		$lpsq = array();		foreach ($data['line_items'] as $v) 		{			if(isset($lpsq[$v['seller_sku']]))			{				$lpsq[$v['seller_sku']]['quantity'] += 1;				$tmp_row_total = $v['sale_price'] ;				foreach($v['item_tax'] as $kk => $vv){				    if(isset($vv['tax_amount'])){				         $tmp_row_total  = 	$tmp_row_total*1 + $vv['tax_amount']*1;				    }				   				}				$lpsq[$v['seller_sku']]['row_total'] = $lpsq[$v['seller_sku']]['row_total']*1 + $tmp_row_total*1;			}			else			{				//$lpsq[$v['seller_sku']] = array('link'=>$purl.$v['product_id'],'product'=>$v['product_name'],'sku'=>$v['seller_sku'],'quantity'=>1);				$tmp_row_total = $v['sale_price'] ;				foreach($v['item_tax'] as $kk => $vv){				    if(isset($vv['tax_amount'])){				         $tmp_row_total  = 	$tmp_row_total*1 + $vv['tax_amount']*1;				    }				   				}				$lpsq[$v['seller_sku']] = array('link'=>$purl.$v['product_id'],'product'=>$v['product_name'],'sku'=>$v['seller_sku'],'quantity'=>1,'price'=>$v['original_price'],"row_total"=>$tmp_row_total);			}		}//  		$this->logic_ding->sendToDing($shop['shopname']."测试获取TT订单".json_encode($data));//  		$this->logic_ding->sendToDing($shop['shopname']."测试获取TT订单数据转化".json_encode($lpsq));		foreach ($lpsq as $v) 		{			$link .= $v['link'].',';			$product .= $v['product'].',';			$sku .= $v['sku'].',';			$quantity .= $v['quantity'].';';			$price .= $v['price'].',';			$row_total .= $v['row_total'].',';		}			if($data['status'] == 'DELIVERED' || $data['status'] == 'IN_TRANSIT' || $data['status'] == 'COMPLETED')		{			$s = 216;		}		else if($data['status'] == 'AWAITING_SHIPMENT')		{			$s = 207;		}		else if($data['status'] == 'CANCELLED')		{			$s = 217;		}		else		{			$s = 283;		}		if(isset($zjsku[$shop['id']]))//判断是否找到店铺SKU		{			$sku = rtrim($sku,',').','.$zjsku[$shop['id']];		}		$post['user_id'] = $data['user_id'];		$post['state'] = $s;		$post['shop'] = $shop['id'];//店铺ID		$post['user'] = $shop['shopuser'];//店铺负责人		$post['product'] = rtrim($product,',');//产品名称		$post['link'] = rtrim($link,',');//产品链接		$post['issku'] = rtrim($sku,',');		$post['quantity'] = rtrim($quantity,';');		$post['clientremarks'] = $data['buyer_message'];//客户备注		$post['paypal'] = '';//交易号		$post['guarantee'] = '';//卖家保障		$post['parameter'] = '';//属性		$post['shippingmethod'] = $data['delivery_option_name'].' '.$data['payment']['shipping_fee'];//用户选择快递方式及运费金额		$post['source'] = 2;//订单类型		$post['type'] = 1;//发货仓库		$post['capital'] = 3;//资金支付状况,全部付款		$numbernew = $shop['shortname'].'-'.substr(date('ymd',substr($data['create_time'],0,10)-$sjc),1);		$numberwb = (substr(strval($num+1000),1,3));		if($numbernew == 'TT-QQS-40807')		{			$numberwb = $numberwb+7;		}	    //过完今天就删除	    $tmp_time = date("Y-m-d");	   // if($tmp_time == '20250114'){	   //    $numberwb = $numberwb+7;	   // }		$post['number'] = $shop['shortname'].'-'.substr(date('ymd',substr($data['create_time'],0,10)-$sjc),1).'-'.$numberwb;//编号				$post['orderinfo'] = $data['id'];//订单号		$post['insurance'] = 0;//运输保险费用		$address = $data['recipient_address']['address_detail'];		$post['baddress'] = $address.','.$data['recipient_address']['district_info'][3]['address_name'].','.$data['recipient_address']['district_info'][1]['address_name'].','.$data['recipient_address']['postal_code'].','.$data['recipient_address']['region_code'].','.$data['recipient_address']['phone_number'];		$post['saddress'] = $address.','.$data['recipient_address']['district_info'][3]['address_name'].','.$data['recipient_address']['district_info'][1]['address_name'].','.$data['recipient_address']['postal_code'].','.$data['recipient_address']['region_code'].','.$data['recipient_address']['phone_number'];		$post['country'] = $cuy[$data['recipient_address']['region_code']];//此国家的ID		$post['al'] = $data['recipient_address']['region_code'];//联邦名称		$post['bname'] = preg_replace('/( | | |\s)/',' ',$data['recipient_address']['name']);//名称		$post['sname'] = preg_replace('/( | | |\s)/',' ',$data['recipient_address']['name']);//名称		$post['client'] = preg_replace('/( | | |\s)/',' ',$data['recipient_address']['name']);//公司名称		$post['name'] = preg_replace('/( | | |\s)/',' ',$data['recipient_address']['name']);//收件人名称		$post['phone'] = preg_replace('/\D/s','',$data['recipient_address']['phone_number']);//收件人电话		$post['email'] = preg_replace('/( | | |\s)+/','',$data['buyer_email']);//客户邮箱		$post['zipcode'] = $data['recipient_address']['postal_code'];//收件人邮编		$post['province'] = $data['recipient_address']['district_info'][1]['address_name'];//收件人省份		$post['city'] = $data['recipient_address']['district_info'][3]['address_name'];//收件人城市		$post['address'] = $address;//收件人地址		$post['shouldmoney'] = $data['payment']['total_amount'];//应收金额		$post['skje'] = $post['shouldmoney'];//收款金额		$post['ismoney'] = $data['payment']['currency'].$post['shouldmoney'];//支付币种金额		$yga = $post['shouldmoney'];//金额		$post['cf'] = ($data['shipping_type']=='SELLER')?0:1;//是否仓发TIKTOK平台仓发 SELLER商家发,ERP中1平台仓发,0商家发		$post['budget'] = 0;//预估到账金额		/**		if(isset($data['pay']) && $yga > 0)		{			$post['pay'] = $pay[$data['pay']]['id'];			$ygc = $pay[$data['pay']]['estimaterate'];//预估到账公式			$post['estimaterate'] = $pay[$data['pay']]['estimaterate'];			$ifbudget = eval("return $yga*1.$ygc;");			if($ifbudget > 0)			{			    $post['budget'] = eval("return $yga*1.$ygc;");//预估到帐金额			}		}		else if($yga > 0)		{			$post['pay'] = 0;			$ygb = $shop['estimaterate'];//店铺默认到账公式			$post['estimaterate'] = $shop['estimaterate'];			$ifbudget = eval("return $yga*1.$ygb;");			if($ifbudget > 0)			{			    $post['budget'] = eval("return $yga*1.$ygb;");//预估到帐金额			}		}		**/		$post['overtime'] = $data['shipping_due_time']-$sjc;//超时时间		$post['buytime'] = substr($data['paid_time'],0,10)-$sjc;//格式化付款时间		$post['dtime'] = substr($data['create_time'],0,10)-$sjc;//订单时间		$post['gtime'] = date('Ymd',substr($data['create_time'],0,10)-$sjc);//格式化订单时间		$post['currencytitle'] = $data['payment']['currency'];//结算币种名称		$post['currency'] = $typeclass[$data['payment']['currency']];//钱币ID		$post['time'] = time();//同步时间		$post['hl'] = '6.4';//汇率		$post['delivery_option_id'] = $data['delivery_option_id'];		if(isset($data['delivery_option_name']))		{			$post['express'] = (isset($ex[$data['delivery_option_name']]))?$ex[$data['delivery_option_name']]['id']:0;//快递方式		}		if(isset($data['line_items'][0]['tracking_number']))		{			$post['waybill'] = $data['line_items'][0]['tracking_number'];		}		 		//$this->logic_ding->sendToDing("测试获取TT订单编码".$post['number']);		$matching = $this->api->matching($post['quantity'],$post['issku'],$dtc,$money,$int,$dtctitle,$shop,[		        'price'=>trim($price,','),			    'row_total'=>trim($row_total,','),		    ]);		$post['shipremarks'] = $matching['title'];		$post['cost'] = $matching['cost'];		$post['purchase'] = $matching['purchase'];		$post['fpdata'] = $matching['product'];		$post['whlabel'] = $matching['whlabel'];		$post['slpx'] = $matching['wcslpx'];		return $post;	}		public function sign($url,$appSecret,$body='') 	{		// 解析URL获取查询参数		$queryParams = array();		parse_str(parse_url($url, PHP_URL_QUERY), $queryParams);		// 排除'sign'和'access_token'		unset($queryParams['sign'], $queryParams['access_token']);		// 按字典顺序排序查询参数		ksort($queryParams);		// 拼接参数为{key}{value}格式		$input = '';		foreach ($queryParams as $key => $value)		{    		$input .= $key . $value;		}		// 追加请求路径		$path = parse_url($url, PHP_URL_PATH);		$input = $path . $input;		if ($body) 		{			$input .= json_encode($body);	    }		// 使用app_secret包裹生成的字符串		$input = $appSecret . $input . $appSecret;		// 生成签名		$sign = hash_hmac('sha256', $input,$appSecret);        return $sign;	}		public function su_curl($data,$url,$header=array(),$date_type='json',$timeout=300,$httptype="POST",$userpwd='')    {            if ($date_type == 'http_build_query')		{            $data = http_build_query($data);        }		else if ($date_type == 'json')		{            $data = json_encode($data);        }        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_HEADER, false);        switch ($httptype)		{            case "GET":            curl_setopt($ch, CURLOPT_HTTPGET, true);            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");            break;			            case "POST":            curl_setopt($ch, CURLOPT_POST, true);            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");            break;			            case "PUT":            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");            break;			            case "DELETE":            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");            break;        }        $isSecure = strpos($url, "https://");        if ($isSecure === 0)		{            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        }        if(!empty($header))		{            curl_setopt($ch, CURLOPT_SSLVERSION , 6); //NEW ADDITION            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);        }        if(!empty($userpwd))		{            curl_setopt($ch,CURLOPT_USERPWD,$userpwd);        }        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);        $result = curl_exec($ch);        curl_close($ch);        return $result;	}}  //end class
 |