Transact.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php defined('BASEPATH') OR exit('No direct script access allowed');
  2. class Transact extends Start_Controller {
  3. private $sid;
  4. // private $baseurl="https://api-m.sandbox.paypal.com";
  5. private $baseurl="https://api.paypal.com";
  6. public function __construct(){
  7. parent::__construct();
  8. $this->load->library('session');
  9. $this->load->_model('Model_fullorder','fullorder');
  10. $this->load->_model('Model_fullordertt','fullordertt');
  11. $this->load->_model('Model_fullorder_smt','fullordersmt');
  12. $this->load->_model('Model_express','express');
  13. $this->load->_model('Model_shop','shop');
  14. $this->load->_model('Model_transact','transact');
  15. $this->load->library('parser');
  16. // $this->load->library('dispute_collect');
  17. if(isset($_SESSION['api']))
  18. {
  19. $user = $this->user->get_api($_SESSION['api']);
  20. $fgshop = [];
  21. $user = explode('|',trim($user['shop'],'|'));
  22. foreach ($user as $value)
  23. {
  24. if($value<=6){
  25. $fgshop[]=$value;
  26. }
  27. }
  28. }
  29. $sid=$this->input->get('sid');
  30. if(!$sid||!in_array($sid,$fgshop)){
  31. $sid=$fgshop[0];
  32. }
  33. $this->sid=$sid;
  34. }
  35. //定义方法的调用规则 获取URI第二段值
  36. public function _remap($arg,$arg_array)
  37. {
  38. if($arg == 'detail')//添加
  39. {
  40. $this->_detail($arg_array);
  41. }elseif($arg == 'syns'){
  42. $this->syns($arg_array);
  43. }
  44. else
  45. {
  46. $this->_index($arg_array);
  47. }
  48. }
  49. public function _index(){
  50. $dt = 0;
  51. if(isset($_SESSION['api']))
  52. {
  53. $user = $this->user->get_api($_SESSION['api']);
  54. $usp = $user;
  55. $fgshop = "";$sid = "";
  56. $usersp = explode('|',trim($user['shop'],'|'));
  57. foreach ($usersp as $value)
  58. {
  59. $fgshop .= " shop = ".$value." or";
  60. $sid .= " id = ".$value." or";
  61. }
  62. if($user['vip'] == 1)
  63. {
  64. $vip = 1;
  65. }
  66. else
  67. {
  68. $vip = 0;
  69. }
  70. }
  71. else
  72. {
  73. $vip = 0;
  74. }
  75. $post = $this->input->post(NULL, TRUE);
  76. $where = "1=1 and (".rtrim($fgshop,'or').")";
  77. if(isset($post['page']))
  78. {
  79. $shop = $this->input->post('shop',true);
  80. $page = $this->input->post('page',true);
  81. $express = $this->input->post('express',true);
  82. $perpage = $this->input->post('perpage',true);
  83. $orderinfo = $this->input->post('orderinfo',true);
  84. $number = $this->input->post('number',true);
  85. $waybill = $this->input->post('waybill',true);
  86. //数据排序
  87. $order_str = "id desc";
  88. if(empty($page))
  89. {
  90. $start = 0;
  91. $perpage = 1;
  92. }
  93. else
  94. {
  95. $start = ($page - 1)*$perpage;
  96. }
  97. if($express)
  98. {
  99. $where .= " and carrier = '$express'";
  100. }
  101. if($shop)
  102. {
  103. $where .= " and shop = '$shop'";
  104. }
  105. if($orderinfo)
  106. {
  107. $where .= " and order_id = '$orderinfo'";
  108. }
  109. if($number)
  110. {
  111. $where .= " and number = '$number'";
  112. }
  113. if($waybill)
  114. {
  115. $where .= " and tracking_number = '$waybill'";
  116. }
  117. //取得信息列表id,shop,type,source,user,orderinfo,number,name,state,buytime,clientremarks,review,print,library,libraryconfirm,express,waybill,orderremarks,black
  118. $info_list = $this->transact->find_all($where,'id,shop,order_id,number,transaction_id,carrier,tracking_number,is_transact',$order_str,$start,$perpage);
  119. foreach($info_list as $k=>$v){
  120. $shop=$this->shop->read($v['shop']);
  121. $info_list[$k]['shop']=$shop['shopname'];
  122. $express=$this->express->read($v['carrier']);
  123. $info_list[$k]['carrier']=$express['iscode'];
  124. $info_list[$k]['order_id']='<h9 class="window" data-h="/transact/detail/'.$v['id'].'" data-t="订单号:'.$v['order_id'].'"><p>'.$v['order_id'].'</p></h9>';
  125. $info_list[$k]['is_transact']=$v['is_transact']?"是":"否";
  126. // $info_list[$k]['black']=[];
  127. }
  128. $total = $this->transact->find_count($where);
  129. $pagenum = ceil($total/$perpage);
  130. $over = $total-($start+$perpage);
  131. $rows = array('total'=>$total,'over'=>$over,'pagenum'=>$pagenum,'rows'=>($info_list));
  132. echo json_encode($rows);exit;
  133. }
  134. // $this->data=
  135. $wlshop = $this->shop->find_all('1=1 and '.rtrim($sid,'or'));
  136. $this->data['express'] = $this->express->find_all();
  137. $this->data['wlshop'] = $wlshop;
  138. $this->_Template('transact',$this->data);
  139. }
  140. public function _detail($arg_array){
  141. $id=$arg_array[0];
  142. $transact=$this->transact->read($id);
  143. if(!$transact){
  144. echo json_encode(array('msg'=>'数据不存在','success'=>false));exit;
  145. }
  146. // if(isset($transact['info'])&&!empty($transact['info'])){
  147. // $info=json_decode($transact['info'],true);
  148. // // $this->data['info']=$transact['info'];
  149. // }else{
  150. $shop=$this->shop->read($transact['shop']);
  151. $info=$this->transaction($shop['shopname'],$transact['transaction_id']);
  152. if(isset($info['debug_id'])&&!empty($info['debug_id'])){
  153. echo json_encode(array('msg'=>$info['message'],'success'=>false));exit;
  154. }
  155. // $this->transact->save(['info'=>json_encode($info,true)]);
  156. // }
  157. if(!empty($info['transaction_details'])){
  158. $detail=$info['transaction_details'][0];
  159. }else{
  160. $detail=[];
  161. }
  162. $this->data['info']=$detail;
  163. $this->_Template('transact_info',$this->data);
  164. }
  165. public function syns(){
  166. $shops=[
  167. 1=>'supernovahair',
  168. 2=>'asteriahair',
  169. 3=>'alipearlhair',
  170. 4=>'westkiss',
  171. 5=>'yolissahair',
  172. 6=>'wigginshair',
  173. ];
  174. $shops=[ 1=>'supernovahair'];
  175. //step1 获取最新订单数据
  176. $start_time=strtotime(date('Y-m-d',time()-24*3600));
  177. // $end_time=strtotime(date('Y-m-d',time()));
  178. $end_time=time();
  179. $dlz = $this->fullorder->paypal($start_time,$end_time);
  180. $smt = $this->fullordersmt->paypal($start_time,$end_time);
  181. $data = array_merge($dlz,$smt);
  182. $keys=['number','order_id','transaction_id','tracking_number','carrier','shop','created_at','updated_at'];
  183. $list=[];
  184. try {
  185. $this->db->trans_begin();
  186. for($i=1;$i<=count($data);$i++){
  187. $item=[];
  188. $v=$data[$i-1];
  189. $item['number']=$v['number'];
  190. $item['order_id']=$v['orderinfo'];
  191. $item['transaction_id']=$v['paypal'];
  192. $item['tracking_number']=$v['waybill'];
  193. $item['carrier']=$v['express'];
  194. $item['shop']=$v['shop'];
  195. $item['created_at']=time();
  196. $item['updated_at']=time();
  197. $list[]=$item;
  198. if($i % 10==0||$i==count($data)){
  199. $res=$this->transact->insert_batch($keys,$list);
  200. if(!$res){
  201. throw new Exception("数据库异常");
  202. }
  203. $list=[];
  204. }
  205. }
  206. if ($this->db->trans_status() === FALSE){
  207. throw new Exception("数据库异常");
  208. }
  209. $this->db->trans_commit();
  210. } catch (\Throwable $e) {
  211. $this->db->trans_rollback();
  212. }
  213. //step2 更新track
  214. $where="1=1 and is_transact=0";
  215. $where.=" and created_at > ".strtotime(date('Y-m-d',time()-24*3600*7));
  216. $transact_data=$this->transact->find_all($where);
  217. $express_list=$this->express->find_all();
  218. $express_list=array_combine(array_column($express_list,'id'),$express_list);
  219. $list=[];
  220. foreach($shops as $k=>$shop){
  221. $shopdata=array_filter($transact_data,function($item)use($k){
  222. return $item['shop']==$k;
  223. });
  224. $shopdata=array_values($shopdata);
  225. try {
  226. $this->db->trans_begin();
  227. for($i=1;$i<=count($shopdata);$i++){
  228. $item=[];
  229. $v=$shopdata[$i-1];
  230. if(!empty($express_list[$v['carrier']])){
  231. $expressName=$express_list[$v['carrier']]['iscode'];
  232. $allow_express=['FEDEX','TOLL','DHL','USPS','UPS','TNT','ARAMEX','ROYAL_MAIL'];
  233. if(!in_array($expressName,$allow_express)){
  234. $item['carrier_name_other']=$expressName;
  235. $expressName="OTHER";
  236. }
  237. }else{
  238. throw new \Exception("快递不存在");
  239. }
  240. if(empty($v['tracking_number'])){
  241. continue;
  242. }
  243. if(substr_count($v['transaction_id'],'-')>=2){
  244. continue;
  245. }
  246. $item['transaction_id']=$v['transaction_id'];
  247. $item['tracking_number']=$v['tracking_number'];
  248. $item['carrier']=$expressName;
  249. $item['status']="SHIPPED";
  250. $list[]=$item;
  251. //20 为固定数值 api单次更新限制
  252. if($i % 20==0||$i==count($shopdata)){
  253. $info=$this->setTrack($shop,$list);
  254. if(isset($info['errors'])&&!empty($info['errors'])){
  255. throw new Exception("请求paypal异常");
  256. // echo json_encode(array('msg'=>$info['message'],'success'=>false));exit;
  257. }
  258. $res=$this->db
  259. ->set('is_transact',1)
  260. ->where_in('transaction_id',array_column($list,'transaction_id'))
  261. ->update("transact");
  262. //更新数据库;
  263. if(!$res){
  264. throw new Exception("数据库异常");
  265. }
  266. $list=[];
  267. }
  268. }
  269. if ($this->db->trans_status() === FALSE){
  270. throw new Exception("数据库异常");
  271. }
  272. $this->db->trans_commit();
  273. } catch (\Throwable $e) {
  274. $this->db->trans_rollback();
  275. p($e->getMessage());
  276. }
  277. }
  278. //step3
  279. // foreach($shops as $k=>$shop){
  280. // $list=$this->transaction($shop,'',7);
  281. // p($list);
  282. // }
  283. return true;
  284. }
  285. private function setTrack($dp,$data){
  286. $url = $this->baseurl.'/v1/shipping/trackers-batch';
  287. $header[] = 'Content-Type: application/json';
  288. $header[] = 'Authorization: Bearer '.$this->getToken($dp);
  289. $param=['trackers'=>$data];
  290. $info = $this->_curl($param,$url,3000,'POST',"json",$header);
  291. $info = json_decode($info,true);
  292. return $info;
  293. }
  294. private function transaction($dp,$transaction_id="",$day=30){
  295. $url = $this->baseurl.'/v1/reporting/transactions?';
  296. $header[] = 'Content-Type: application/json';
  297. $header[] = 'Authorization: Bearer '.$this->getToken($dp);
  298. $start_date=date("Y-m-d\TH:i:sO",time()-24*3600*$day);
  299. $end_date=date("Y-m-d\TH:i:sO",time());
  300. $param=[
  301. 'start_date'=>$start_date,
  302. 'end_date'=>$end_date,
  303. 'fields'=>"all",
  304. ];
  305. if($transaction_id){
  306. $param['transaction_id']=$transaction_id;
  307. }
  308. $data = http_build_query($param);
  309. $url=$url.$data;
  310. $info = $this->_curl([],$url,3000,'GET',"http_build_query",$header);
  311. $info = json_decode($info,true);
  312. return $info;
  313. }
  314. private function getToken($dp)
  315. {
  316. $access_arr=[];
  317. $url = $this->baseurl.'/v1/oauth2/token';
  318. $header[] = 'Content-Type: application/json';
  319. $header[] = 'Accept-Language: en_US';
  320. $header[] = 'Accept: */*';
  321. $data = array('grant_type' => 'client_credentials');
  322. $method = 'POST';
  323. $hf_path = $_SERVER["DOCUMENT_ROOT"] . '/data/hf_access_token.txt';
  324. $hf_access_token = '';
  325. if(file_exists($hf_path))
  326. {
  327. $file_read = fopen($hf_path, 'r');
  328. $access_str = fgets($file_read);
  329. fclose($file_read);
  330. $access_arr = unserialize($access_str);
  331. if(isset($access_arr[$dp])&&is_array($access_arr[$dp])){
  332. $dp_access_arr=$access_arr[$dp];
  333. if (time() < intval($dp_access_arr['expires_at']))
  334. {
  335. $hf_access_token = isset($dp_access_arr['access_token']) ? $dp_access_arr['access_token'] : '';
  336. }
  337. }
  338. }
  339. if(!$hf_access_token)
  340. {
  341. // $config=$this->getDpConfig();
  342. // $config=[
  343. // 'account'=>'paypal-facilitator@supernovahair.com',
  344. // 'client_id'=>'Ae5ZECTwT-JY-GrHW2-XW234yJ4tYT-7RAt3s1mY8GtW1rX470Kr8weXkCH3GMaO-V7mnmnCTsxFvsiy',
  345. // 'secret'=>'EOiZjIwRaiK3pvbJgMURKcGy6ULt5YCGLkqN7WngwG-r34brYrfVwS6ECI8cig7l8lOObvF-ukeZxB-3',
  346. // ];
  347. $config=[
  348. 'account'=>'paypal@supernovahair.com',
  349. 'client_id'=>'AYn5qSfZKh9ApN_IQvwuRq-3t07XflNIbczH6pfz-GccZ1bPTiYk3RzJVTJPQkMmoQM-PWmZX1hkUB18',
  350. 'secret'=>'EBd_oR-c1s4SVhznh1832_ua0WumbAqFamSM5uKJSHbpRv8qkI1Z9D2Tqcizaz5DRrgmQ7Mkl-Cq-TgL',
  351. ];
  352. $file = fopen($hf_path, 'w');
  353. $hf_account = $config['account'];
  354. $client_id = $config['client_id'];
  355. $secret_id = $config['secret'];
  356. $userpwd = $client_id . ':' . $secret_id;
  357. $info = $this->_curl($data,$url,3000,$method,true,$header,$userpwd);
  358. $result = json_decode($info,true);
  359. // $access_new = (time() + $result['expires_in']) . ':' . $result['access_token'];
  360. $access_arr[$dp]=[
  361. 'expires_at'=>time() + $result['expires_in'],
  362. 'access_token'=>$result['access_token'],
  363. ];
  364. fwrite($file, serialize($access_arr));
  365. fclose($file);
  366. $hf_access_token = $result['access_token'];
  367. }
  368. return $hf_access_token;
  369. }
  370. private function _curl($data,$url,$timeout=300,$httptype="POST",$date_type=false,$header=array(),$userpwd='')
  371. {
  372. if ($date_type == 'http_build_query')
  373. {
  374. $data = http_build_query($data);
  375. }
  376. else if ($date_type == 'json')
  377. {
  378. $data = json_encode($data);
  379. }
  380. $ch = curl_init();
  381. curl_setopt($ch, CURLOPT_URL, $url);
  382. curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
  383. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  384. curl_setopt($ch, CURLOPT_HEADER, false);
  385. switch ($httptype)
  386. {
  387. case "GET":
  388. curl_setopt($ch, CURLOPT_HTTPGET, true);
  389. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
  390. break;
  391. case "POST":
  392. curl_setopt($ch, CURLOPT_POST, true);
  393. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  394. break;
  395. case "PUT":
  396. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  397. break;
  398. case "DELETE":
  399. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
  400. break;
  401. }
  402. $isSecure = strpos($url, "https://");
  403. if ($isSecure === 0)
  404. {
  405. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  406. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  407. }
  408. if(!empty($header))
  409. {
  410. curl_setopt($ch, CURLOPT_SSLVERSION , 6); //NEW ADDITION
  411. curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
  412. }
  413. if(!empty($userpwd))
  414. {
  415. curl_setopt($ch,CURLOPT_USERPWD,$userpwd);
  416. }
  417. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  418. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  419. $result = curl_exec($ch);
  420. curl_close($ch);
  421. return $result;
  422. }
  423. }