Model_fedexv1.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. <?php
  2. class Model_Fedexv1 extends Lin_Model {
  3. function __construct(){
  4. parent::__construct();
  5. $this->load->_model('Model_aapeizhi','aapeizhi');
  6. $this->load->_model("Model_logic_ding",'logic_ding');
  7. }
  8. public $base_url = "https://apis.fedex.com.cn";
  9. public $f_config = [
  10. "account"=>"692362136",
  11. "key"=>"l7c6ae3d27cce34bdca31cf6e0ff4af125",
  12. 'secret' =>'475eb390bf334bda8b5f44f1c07b7c10',
  13. "client_id"=>"l7c6ae3d27cce34bdca31cf6e0ff4af125",
  14. "client_secret"=>"475eb390bf334bda8b5f44f1c07b7c10",
  15. //追物流轨迹的
  16. 'track_key'=>"l71bded23966b144df9fc01956f6dd655d",
  17. 'track_secret'=>"61730ddbae764dcba70f4737cdaaa6e7"
  18. ];
  19. public function getAccessToken(){
  20. $res = $this->setting->find("skey='fedex_v1_access_token'");
  21. if($res){
  22. if(time() > $res['expiretime']){
  23. $this->setting->query("DELETE FROM `crowd_setting` WHERE `skey`='fedex_v1_access_token'");
  24. return $this->makeAccessToken();
  25. }
  26. return $res['svalue'];
  27. }else{
  28. return $this->makeAccessToken();
  29. }
  30. }
  31. public function makeAccessToken(){
  32. $url = "/oauth/token";
  33. $headers = [
  34. "Content-Type:application/x-www-form-urlencoded",
  35. ];
  36. $params = [
  37. "grant_type"=>"client_credentials",
  38. "client_id"=> $this->f_config['client_id'],
  39. "client_secret"=> $this->f_config['client_secret'],
  40. ];
  41. $params=http_build_query($params);
  42. $res = $this->sendPost($url,$params,$headers);
  43. if(isset($res['access_token'])){
  44. $this->setting->insert([
  45. 'skey'=>"fedex_v1_access_token",
  46. 'svalue' => $res['access_token'],
  47. 'expiretime' => time() + 3600 -10
  48. ]);
  49. }
  50. return $res['access_token'];
  51. }
  52. public function getTrackToken(){
  53. $res = $this->setting->find("skey='fedex_v1_track_access_token'");
  54. if($res){
  55. if(time() > $res['expiretime']){
  56. $this->setting->query("DELETE FROM `crowd_setting` WHERE `skey`='fedex_v1_track_access_token'");
  57. return $this->makeTrackToken();
  58. }
  59. return $res['svalue'];
  60. }else{
  61. return $this->makeTrackToken();
  62. }
  63. }
  64. public function makeTrackToken(){
  65. $url = "/oauth/token";
  66. $headers = [
  67. "Content-Type:application/x-www-form-urlencoded",
  68. ];
  69. $params = [
  70. "grant_type"=>"client_credentials",
  71. "client_id"=> $this->f_config['track_key'],
  72. "client_secret"=> $this->f_config['track_secret'],
  73. ];
  74. $params=http_build_query($params);
  75. $res = $this->sendPost($url,$params,$headers);
  76. if(isset($res['access_token'])){
  77. $this->setting->insert([
  78. 'skey'=>"fedex_v1_track_access_token",
  79. 'svalue' => $res['access_token'],
  80. 'expiretime' => time() + 3600 -10
  81. ]);
  82. }
  83. return $res['access_token'];
  84. }
  85. private function setData($order_info){
  86. $customer_streets = [];
  87. $customer_streets[] = $order_info['address'];
  88. if(!empty($order_info['address2'])){
  89. $customer_streets[] = $order_info['address2'];
  90. }
  91. $state_codes = $this->aapeizhi->getFedexStateCode();
  92. $params = [
  93. "labelResponseOptions"=>"URL_ONLY",
  94. "accountNumber"=>[
  95. "value"=> (int)$this->f_config['account']
  96. ],
  97. "requestedShipment"=>[
  98. "shipper"=>[
  99. "contact"=>[
  100. "personName"=>"LONGYI",
  101. "phoneNumber"=>"18539006340",
  102. "companyName"=>"LONGYI",
  103. ],
  104. "address"=>[
  105. "streetLines"=> [
  106. "1403, Buliding C, Bodi Center",
  107. "NingWei Street, XiaoShan"
  108. ],
  109. "city"=>"Hangzhou",
  110. "stateOrProvinceCode"=>"",
  111. "postalCode"=>310000,//杭州邮编
  112. "countryCode"=>$order_info['warehouse']['lb']
  113. ],
  114. ],
  115. "recipients"=>[
  116. [
  117. "contact" => [
  118. "personName"=>$order_info['name'],
  119. "phoneNumber"=>$order_info['phone'],
  120. "companyName"=>$order_info['client']
  121. ],
  122. "address"=>[
  123. "streetLines" =>$customer_streets,
  124. "city"=>$order_info['city'],
  125. "stateOrProvinceCode"=>strlen($order_info['province'])==2?strtoupper($order_info['province']):$state_codes[strtolower($order_info['province'])],
  126. "postalCode"=>(string)$order_info['zipcode'],
  127. "countryCode"=>$order_info['lb'],
  128. ],
  129. ]
  130. ],
  131. "shipDatestamp"=>date("Y-m-d"),
  132. "serviceType"=>($order_info['js'] == 3)?"FEDEX_INTERNATIONAL_PRIORITY":"FEDEX_INTERNATIONAL_CONNECT_PLUS",
  133. "packagingType"=> "FEDEX_BOX",
  134. "pickupType"=>"DROPOFF_AT_FEDEX_LOCATION",
  135. "blockInsightVisibility"=>false,
  136. "shippingChargesPayment"=>[
  137. "paymentType"=>"SENDER"
  138. ],
  139. "shipmentSpecialServices"=>[
  140. "specialServiceTypes"=>[
  141. "ELECTRONIC_TRADE_DOCUMENTS",
  142. ],
  143. "etdDetail"=>[
  144. "requestedDocumentTypes"=>[
  145. "COMMERCIAL_INVOICE"
  146. ]
  147. ]
  148. ],
  149. "shippingDocumentSpecification"=>[
  150. "shippingDocumentTypes"=>[
  151. "COMMERCIAL_INVOICE"
  152. ],
  153. "commercialInvoiceDetail"=>[
  154. "documentFormat"=>[
  155. "docType"=>"PDF",
  156. "stockType"=>"PAPER_LETTER"
  157. ],
  158. "customerImageUsages"=>[
  159. [
  160. "id"=> "IMAGE_1",
  161. "type"=> "SIGNATURE",
  162. "providedImageType"=> "SIGNATURE"
  163. ],
  164. [
  165. "id"=> "IMAGE_2",
  166. "type"=> "LETTER_HEAD",
  167. "providedImageType"=> "LETTER_HEAD"
  168. ]
  169. ]
  170. ]
  171. ],
  172. "labelSpecification"=>[
  173. "imageType"=>"PDF",
  174. "labelStockType"=>"STOCK_4X6",
  175. "customerSpecifiedDetail"=>[
  176. "docTabContent"=>[
  177. "docTabContentType"=>"STANDARD"
  178. ]
  179. ]
  180. ],
  181. "customsClearanceDetail"=>[
  182. "dutiesPayment"=>[
  183. "paymentType"=>"SENDER",
  184. ],
  185. "documentContent"=>"COMMODITY",
  186. "commodities"=>[
  187. [
  188. "description"=>$order_info['sbpm'].'-'.$order_info['ts'].'PCS',
  189. "countryOfManufacture"=> "CN",
  190. "quantity"=> $order_info['ts'],
  191. "quantityUnits"=> "cm",
  192. "unitPrice"=> [
  193. "amount"=> $order_info['dtsbjz'],
  194. "currency"=> "USD"
  195. ],
  196. "customsValue"=> [
  197. "amount"=>$order_info['zsbjz'],
  198. "currency"=> "USD"
  199. ],
  200. "weight"=> [
  201. "units"=> "KG",
  202. "value"=> 0.4
  203. ]
  204. ]
  205. ]
  206. ],
  207. "requestedPackageLineItems"=>[
  208. [
  209. "weight"=>[
  210. "units"=>"KG",
  211. "value"=>0.4
  212. ]
  213. ]
  214. ]
  215. ]
  216. ];
  217. return $params;
  218. }
  219. //上传货物信息 获取运单 托运
  220. public function get_data($order_info){
  221. try{
  222. $url = "/ship/v1/shipments";
  223. $headers = [
  224. "x-customer-transaction-id"=>$order_info['number'],
  225. "Content-Type:application/json",
  226. "Authorization: Bearer ".$this->getAccessToken(),
  227. "x-locale" => "en_US",//这个是语种加国家
  228. "Accept: application/json",
  229. ];
  230. // echo "<pre>";
  231. // var_dump("Bearer ".$this->getAccessToken());
  232. $params = $this->setData($order_info);
  233. //var_dump($params);
  234. $params=json_encode($params);
  235. //var_dump($params);
  236. $res = $this->sendPost($url,$params,$headers);
  237. //var_dump(json_encode($res,JSON_UNESCAPED_UNICODE));
  238. //var_dump($res);
  239. //die;
  240. if(isset($res['code']) && $res['code'] == -1){
  241. return array('x'=>'0','Description'=>$res['msg']);
  242. }
  243. if(!isset($res["transactionId"])){
  244. return array('x'=>'0','Description'=>'请求异常');
  245. }
  246. if(isset($res["errors"])){
  247. return array('x'=>'0','Description'=>json_encode($res["errors"]));
  248. }
  249. $invoice_url = "";
  250. foreach($res['output']['transactionShipments'][0]['shipmentDocuments'] as $v){
  251. if($v['contentType'] == "COMMERCIAL_INVOICE"){
  252. $invoice_url = $v['url'];
  253. }
  254. }
  255. return
  256. [
  257. 'x'=>'1',
  258. 'waybill'=>$res['output']['transactionShipments'][0]['masterTrackingNumber'],
  259. 'label'=>$res['output']['transactionShipments'][0]['pieceResponses'][0]['packageDocuments'][0]['url'],
  260. 'invoice'=>$invoice_url,
  261. ];
  262. }catch(Exception $e){
  263. $error_msg = "error:[fedexv1]创建发货单出错".$e->getMessage()."|".$e->getLine()."|".$e->getFile()."|请求参数".json_encode($order_info,JSON_UNESCAPED_UNICODE);
  264. $this->logic_ding->sendToDing($error_msg);
  265. if(isset($res)){
  266. $error_msg = "error:[fedexv1]创建发货单出错".$e->getMessage()."|".$e->getLine()."|".$e->getFile()."|返回参数".json_encode($res,JSON_UNESCAPED_UNICODE);
  267. $this->logic_ding->sendToDing($error_msg);
  268. }
  269. }
  270. }
  271. //根据单号获取 快递信息
  272. public function get_logistics($number){
  273. $url = "/track/v1/trackingnumbers";
  274. $params = [
  275. "includeDetailedScans"=>false,
  276. "trackingInfo"=>[
  277. [
  278. "trackingNumberInfo"=>[
  279. "trackingNumber"=> $number['waybill']
  280. ]
  281. ]
  282. ]
  283. ];
  284. $headers = [
  285. "Content-Type:application/json",
  286. "Authorization: Bearer ".$this->getTrackToken(),
  287. "x-locale" => "en_US",//这个是语种加国家
  288. "Accept: application/json",
  289. ];
  290. $params=json_encode($params);
  291. var_dump(json_encode($headers));
  292. var_dump($params);
  293. var_dump($this->getTrackToken());
  294. $res = $this->sendPost($url,$params,$headers);
  295. var_dump(json_encode($res));
  296. echo "<pre>";
  297. var_dump($res);
  298. }
  299. public function sendPost($url,$params,$headers){
  300. // var_dump($bodyString);
  301. // 设置请求的URL
  302. $all_url = $this->base_url.$url;
  303. //var_dump($all_url);
  304. // 初始化cURL会话
  305. $ch = curl_init($all_url);
  306. // 设置cURL选项
  307. $options = array(
  308. CURLOPT_SSL_VERIFYPEER=>false,
  309. CURLOPT_SSL_VERIFYHOST=>false,
  310. CURLOPT_RETURNTRANSFER => true,
  311. CURLOPT_POST => true,
  312. CURLOPT_POSTFIELDS => $params,
  313. CURLOPT_HTTPHEADER => $headers,
  314. CURLOPT_ENCODING => "gzip,deflate"
  315. );
  316. // 应用这些选项到cURL会话
  317. curl_setopt_array($ch, $options);
  318. // 执行cURL会话并获取响应
  319. $response = curl_exec($ch);
  320. // 检查是否有错误发生
  321. if ($response === false) {
  322. $error = curl_error($ch);
  323. curl_close($ch);
  324. return [
  325. "code"=> -1,
  326. "msg"=> $error
  327. ];
  328. }
  329. // 关闭cURL会话
  330. curl_close($ch);
  331. // 输出响应内容
  332. return json_decode($response,true);
  333. }
  334. //上传数字签名 和 信头 接口在 文件上传api 主要就传一次 用postman传就行 不费事了 etd 必须先传
  335. public function upload_img(){
  336. $all_url = "https://documentapitest.prod.fedex.com/sandbox/documents/v1/lhsimages/upload";
  337. }
  338. public function send_sign(){
  339. $params = [
  340. "document"=>[
  341. "referenceId"=>"1234",
  342. "name"=>"sign.png",
  343. "contentType"=>"image/png",
  344. "meta"=>[
  345. "imageType"=>"SIGNATURE",
  346. "imageIndex"=>"IMAGE_1"
  347. ]
  348. ],
  349. "rules"=>[
  350. "workflowName"=> "LetterheadSignature"
  351. ]
  352. ];
  353. $body = [
  354. 'document'=>json_encode($params),
  355. 'attachment'=>new CURLFile("D:\wwwroot\cerp.wepolicy.cn\sign.png")
  356. ];
  357. $headers = [
  358. "x-customer-transaction-id"=>time(),
  359. "Content-Type:multipart/form-data",
  360. "Authorization: Bearer ".$this->getAccessToken(),
  361. "x-locale" => "en_US",//这个是语种加国家
  362. "Accept: application/json",
  363. ];
  364. $r = $this->send_img_post($body,$headers);
  365. echo "<pre>";
  366. var_dump($r);
  367. }
  368. public function send_xintou(){
  369. $params = [
  370. "document"=>[
  371. "referenceId"=>"1234",
  372. "name"=>"Logo.png",
  373. "contentType"=>"image/png",
  374. "meta"=>[
  375. "imageType"=>"LETTERHEAD",
  376. "imageIndex"=>"IMAGE_2"
  377. ]
  378. ],
  379. "rules"=>[
  380. "workflowName"=> "LetterheadSignature"
  381. ]
  382. ];
  383. $body = [
  384. 'document'=>json_encode($params),
  385. 'attachment'=>new CURLFile("D:\wwwroot\cerp.wepolicy.cn\Logo.png")
  386. ];
  387. $headers = [
  388. "x-customer-transaction-id"=>time(),
  389. "Content-Type:multipart/form-data",
  390. "Authorization: Bearer ".$this->getAccessToken(),
  391. "x-locale" => "en_US",//这个是语种加国家
  392. "Accept: application/json",
  393. ];
  394. $r = $this->send_img_post($body,$headers);
  395. echo "<pre>";
  396. var_dump($r);
  397. }
  398. public function send_img_post($body,$headers){
  399. $upload_img_url = "/documents/v1/lhsimages/upload";
  400. $all_url = "https://documentapi.prod.fedex.com/documents/v1/lhsimages/upload";
  401. var_dump($all_url);
  402. var_dump($body);
  403. // 初始化cURL会话
  404. $ch = curl_init($all_url);
  405. // 设置cURL选项
  406. $options = array(
  407. CURLOPT_SSL_VERIFYPEER=>false,
  408. CURLOPT_SSL_VERIFYHOST=>false,
  409. CURLOPT_RETURNTRANSFER => true,
  410. CURLOPT_POST => true,
  411. CURLOPT_POSTFIELDS => $body,
  412. CURLOPT_HTTPHEADER => $headers,
  413. CURLOPT_ENCODING => "gzip,deflate"
  414. );
  415. // 应用这些选项到cURL会话
  416. curl_setopt_array($ch, $options);
  417. // 执行cURL会话并获取响应
  418. $response = curl_exec($ch);
  419. // 检查是否有错误发生
  420. if ($response === false) {
  421. $error = curl_error($ch);
  422. curl_close($ch);
  423. return [
  424. "code"=> -1,
  425. "msg"=> $error
  426. ];
  427. }
  428. // 关闭cURL会话
  429. curl_close($ch);
  430. // 输出响应内容
  431. return json_decode($response,true);
  432. }
  433. }