Model_fedexv1.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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_PAK",
  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. "customerReferences"=>[
  214. "customerReferenceType"=>"CUSTOMER_REFERENCE",
  215. "value"=>$order_info['number']
  216. ]
  217. ],
  218. ]
  219. ]
  220. ];
  221. return $params;
  222. }
  223. //上传货物信息 获取运单 托运
  224. public function get_data($order_info){
  225. try{
  226. $url = "/ship/v1/shipments";
  227. $headers = [
  228. "x-customer-transaction-id"=>$order_info['number'],
  229. "Content-Type:application/json",
  230. "Authorization: Bearer ".$this->getAccessToken(),
  231. "x-locale" => "en_US",//这个是语种加国家
  232. "Accept: application/json",
  233. ];
  234. // echo "<pre>";
  235. // var_dump("Bearer ".$this->getAccessToken());
  236. $params = $this->setData($order_info);
  237. //var_dump($params);
  238. $params=json_encode($params);
  239. //var_dump($params);
  240. $res = $this->sendPost($url,$params,$headers);
  241. //var_dump(json_encode($res,JSON_UNESCAPED_UNICODE));
  242. //var_dump($res);
  243. //die;
  244. if(isset($res['code']) && $res['code'] == -1){
  245. return array('x'=>'0','Description'=>$res['msg']);
  246. }
  247. if(!isset($res["transactionId"])){
  248. return array('x'=>'0','Description'=>'请求异常');
  249. }
  250. if(isset($res["errors"])){
  251. return array('x'=>'0','Description'=>json_encode($res["errors"]));
  252. }
  253. $invoice_url = "";
  254. foreach($res['output']['transactionShipments'][0]['shipmentDocuments'] as $v){
  255. if($v['contentType'] == "COMMERCIAL_INVOICE"){
  256. $invoice_url = $v['url'];
  257. }
  258. }
  259. return
  260. [
  261. 'x'=>'1',
  262. 'waybill'=>$res['output']['transactionShipments'][0]['masterTrackingNumber'],
  263. 'label'=>$res['output']['transactionShipments'][0]['pieceResponses'][0]['packageDocuments'][0]['url'],
  264. 'invoice'=>$invoice_url,
  265. ];
  266. }catch(Exception $e){
  267. $error_msg = "error:[fedexv1]创建发货单出错".$e->getMessage()."|".$e->getLine()."|".$e->getFile()."|请求参数".json_encode($order_info,JSON_UNESCAPED_UNICODE);
  268. $this->logic_ding->sendToDing($error_msg);
  269. if(isset($res)){
  270. $error_msg = "error:[fedexv1]创建发货单出错".$e->getMessage()."|".$e->getLine()."|".$e->getFile()."|返回参数".json_encode($res,JSON_UNESCAPED_UNICODE);
  271. $this->logic_ding->sendToDing($error_msg);
  272. }
  273. }
  274. }
  275. //根据单号获取 快递信息
  276. public function get_logistics($number){
  277. $url = "/track/v1/trackingnumbers";
  278. $params = [
  279. "includeDetailedScans"=>false,
  280. "trackingInfo"=>[
  281. [
  282. "trackingNumberInfo"=>[
  283. "trackingNumber"=> $number['waybill']
  284. ]
  285. ]
  286. ]
  287. ];
  288. $headers = [
  289. "Content-Type:application/json",
  290. "Authorization: Bearer ".$this->getTrackToken(),
  291. "x-locale" => "en_US",//这个是语种加国家
  292. "Accept: application/json",
  293. ];
  294. $params=json_encode($params);
  295. var_dump(json_encode($headers));
  296. var_dump($params);
  297. var_dump($this->getTrackToken());
  298. $res = $this->sendPost($url,$params,$headers);
  299. var_dump(json_encode($res));
  300. echo "<pre>";
  301. var_dump($res);
  302. }
  303. public function sendPost($url,$params,$headers){
  304. // var_dump($bodyString);
  305. // 设置请求的URL
  306. $all_url = $this->base_url.$url;
  307. //var_dump($all_url);
  308. // 初始化cURL会话
  309. $ch = curl_init($all_url);
  310. // 设置cURL选项
  311. $options = array(
  312. CURLOPT_SSL_VERIFYPEER=>false,
  313. CURLOPT_SSL_VERIFYHOST=>false,
  314. CURLOPT_RETURNTRANSFER => true,
  315. CURLOPT_POST => true,
  316. CURLOPT_POSTFIELDS => $params,
  317. CURLOPT_HTTPHEADER => $headers,
  318. CURLOPT_ENCODING => "gzip,deflate"
  319. );
  320. // 应用这些选项到cURL会话
  321. curl_setopt_array($ch, $options);
  322. // 执行cURL会话并获取响应
  323. $response = curl_exec($ch);
  324. // 检查是否有错误发生
  325. if ($response === false) {
  326. $error = curl_error($ch);
  327. curl_close($ch);
  328. return [
  329. "code"=> -1,
  330. "msg"=> $error
  331. ];
  332. }
  333. // 关闭cURL会话
  334. curl_close($ch);
  335. // 输出响应内容
  336. return json_decode($response,true);
  337. }
  338. //上传数字签名 和 信头 接口在 文件上传api 主要就传一次 用postman传就行 不费事了 etd 必须先传
  339. public function upload_img(){
  340. $all_url = "https://documentapitest.prod.fedex.com/sandbox/documents/v1/lhsimages/upload";
  341. }
  342. public function send_sign(){
  343. $params = [
  344. "document"=>[
  345. "referenceId"=>"1234",
  346. "name"=>"sign.png",
  347. "contentType"=>"image/png",
  348. "meta"=>[
  349. "imageType"=>"SIGNATURE",
  350. "imageIndex"=>"IMAGE_1"
  351. ]
  352. ],
  353. "rules"=>[
  354. "workflowName"=> "LetterheadSignature"
  355. ]
  356. ];
  357. $body = [
  358. 'document'=>json_encode($params),
  359. 'attachment'=>new CURLFile("D:\wwwroot\cerp.wepolicy.cn\sign.png")
  360. ];
  361. $headers = [
  362. "x-customer-transaction-id"=>time(),
  363. "Content-Type:multipart/form-data",
  364. "Authorization: Bearer ".$this->getAccessToken(),
  365. "x-locale" => "en_US",//这个是语种加国家
  366. "Accept: application/json",
  367. ];
  368. $r = $this->send_img_post($body,$headers);
  369. echo "<pre>";
  370. var_dump($r);
  371. }
  372. public function send_xintou(){
  373. $params = [
  374. "document"=>[
  375. "referenceId"=>"1234",
  376. "name"=>"Logo.png",
  377. "contentType"=>"image/png",
  378. "meta"=>[
  379. "imageType"=>"LETTERHEAD",
  380. "imageIndex"=>"IMAGE_2"
  381. ]
  382. ],
  383. "rules"=>[
  384. "workflowName"=> "LetterheadSignature"
  385. ]
  386. ];
  387. $body = [
  388. 'document'=>json_encode($params),
  389. 'attachment'=>new CURLFile("D:\wwwroot\cerp.wepolicy.cn\Logo.png")
  390. ];
  391. $headers = [
  392. "x-customer-transaction-id"=>time(),
  393. "Content-Type:multipart/form-data",
  394. "Authorization: Bearer ".$this->getAccessToken(),
  395. "x-locale" => "en_US",//这个是语种加国家
  396. "Accept: application/json",
  397. ];
  398. $r = $this->send_img_post($body,$headers);
  399. echo "<pre>";
  400. var_dump($r);
  401. }
  402. public function send_img_post($body,$headers){
  403. $upload_img_url = "/documents/v1/lhsimages/upload";
  404. $all_url = "https://documentapi.prod.fedex.com/documents/v1/lhsimages/upload";
  405. var_dump($all_url);
  406. var_dump($body);
  407. // 初始化cURL会话
  408. $ch = curl_init($all_url);
  409. // 设置cURL选项
  410. $options = array(
  411. CURLOPT_SSL_VERIFYPEER=>false,
  412. CURLOPT_SSL_VERIFYHOST=>false,
  413. CURLOPT_RETURNTRANSFER => true,
  414. CURLOPT_POST => true,
  415. CURLOPT_POSTFIELDS => $body,
  416. CURLOPT_HTTPHEADER => $headers,
  417. CURLOPT_ENCODING => "gzip,deflate"
  418. );
  419. // 应用这些选项到cURL会话
  420. curl_setopt_array($ch, $options);
  421. // 执行cURL会话并获取响应
  422. $response = curl_exec($ch);
  423. // 检查是否有错误发生
  424. if ($response === false) {
  425. $error = curl_error($ch);
  426. curl_close($ch);
  427. return [
  428. "code"=> -1,
  429. "msg"=> $error
  430. ];
  431. }
  432. // 关闭cURL会话
  433. curl_close($ch);
  434. // 输出响应内容
  435. return json_decode($response,true);
  436. }
  437. }