Model_yuntu.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. <?php
  2. if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  3. use GuzzleHttp\Client;
  4. /**
  5. * 此类主要是为了服务于云途快递的API接口
  6. */
  7. class Model_yuntu extends Lin_Model
  8. {
  9. //public $base_url = "https://openapi-sbx.yunexpress.cn"; //测试环境
  10. public $base_url = "https://openapi.yunexpress.cn";//正式环境
  11. public $token_url = "/openapi/oauth2/token";
  12. //正式环境
  13. public $yt_config = [
  14. "appId"=> "96ab2e464e8e",
  15. "appSecret"=> "9ecc186728b64103ac1a5967c90c70e3",
  16. "sourceKey"=> "wzmu5q6x"
  17. ];
  18. //测试环境
  19. // public $yt_config = [
  20. // "appId"=> "d34f30df34ae",
  21. // "appSecret"=> "9ace1fa73c4b4567a6ae5ac7e254b48f",
  22. // "sourceKey"=> "wzmu5q6x"
  23. // ];
  24. function __construct(){
  25. parent::__construct();
  26. $this->load->_model("Model_logic_ding",'logic_ding');
  27. }
  28. public function get_data($data){
  29. $token = $this->getAccessToken();
  30. if(empty($token)){
  31. return [
  32. 'x'=>'0',
  33. 'Description'=>"请求时token为空,请联系技术!!!",
  34. ];
  35. }
  36. $url = "/v1/order/package/create";
  37. //拼接参数
  38. $receive_address = [];
  39. $receive_address[] = $data['address'];
  40. if(!empty($data['address2'])){
  41. $receive_address[] = $data['address2'];
  42. }
  43. if(!empty($data['printnumber'])){
  44. $data['printnumber'] = $data['printnumber']*1 + 1;
  45. }
  46. $params = [
  47. "product_code"=> "YTKD",
  48. //"product_code"=> "S1002",
  49. "customer_order_number"=> empty($data['printnumber'])?$data['number']: $data['number']."_".$data['printnumber'],
  50. "packages"=> [
  51. [
  52. "weight"=> $data['zzl']
  53. ],
  54. ],
  55. "receiver"=> [
  56. "first_name"=> $data['name'],
  57. "country_code"=> $data['lb'],
  58. "province"=> $data['province'],
  59. "city"=> $data['city'],
  60. "address_lines"=> $receive_address,
  61. "postal_code"=> $data['zipcode'],
  62. "phone_number"=> $data['phone'],
  63. "email"=> isset($data['email'])?$data['email']:'',
  64. "company"=>$data['client'],
  65. ],
  66. "declaration_info"=> [
  67. [
  68. "quantity"=>$data['ts'],
  69. "unit_price"=>$data['dtsbjz'],
  70. "unit_weight"=>sprintf("%.3f",$data['zzl']/$data['ts']),
  71. "name_en"=> $data['sbpm'],
  72. "name_local"=>$data['zwpm'],
  73. ],
  74. ],
  75. "customs_number"=>[
  76. "ioss_code"=>$data['ioss']
  77. ]
  78. // "sender"=> [
  79. // "first_name"=> "first_name",
  80. // "last_name"=> "last_name",
  81. // "company"=> "company",
  82. // "country_code"=> "11",
  83. // "province"=> "province",
  84. // "city"=> "city",
  85. // "address_lines"=> [
  86. // "address_lines1"
  87. // ],
  88. // "postal_code"=> "postal_code",
  89. // "phone_number"=> "phone_number",
  90. // "email"=> "email",
  91. // ],
  92. ];
  93. if($data['printcode'] == 'YunExpress_BaoXian'){
  94. $params["extra_services"] =[
  95. [
  96. "extra_code"=>"VAS_IP",
  97. "extra_value"=>"BJFDR",
  98. ]
  99. ];
  100. }
  101. if($data['printcode'] == 'YunExpress_JFPHTKR'){
  102. $params["product_code"] = 'YunExpress_JFPHTKR';
  103. unset($params['customs_number']['ioss_code']);
  104. echo "<pre>";
  105. print_r($params);
  106. die;
  107. }
  108. $start_time = time();
  109. $res = $this->sendNewPost($url,$params,$token);
  110. // echo "<pre>";
  111. // var_dump($params);
  112. // var_dump($res);
  113. $this->logic_ding->sendToDing($data['number']."云途快递报文信息【".json_encode($params)."】返回参数[".json_encode($res)."]");
  114. if(isset($res['code'])&&($res['code'] != 1)){
  115. return [
  116. 'x'=>'0',
  117. 'Description'=>$res['msg'],
  118. ];
  119. }else{
  120. usleep(30);
  121. $r = $this->get_label($res['result']['waybill_number']);
  122. $end_time = time();
  123. if( $end_time - $start_time > 45){
  124. $this->logic_ding->addJobs('outtime_order',['number'=>$data['number']]);
  125. }
  126. //var_dump($res);
  127. if($r['x'] != 1){
  128. return [
  129. 'x'=>'2',
  130. 'waybill'=>$res['result']['waybill_number'],
  131. "url"=>"",
  132. 'Description'=>$r['Description'],
  133. ];
  134. }else{
  135. return [
  136. 'x'=>'1',
  137. 'waybill'=>$res['result']['waybill_number'],
  138. "url"=>$r['url']
  139. ];
  140. }
  141. }
  142. }
  143. /**
  144. * 获取电子面单
  145. */
  146. public function get_label($order_number){
  147. $token = $this->getAccessToken();
  148. if(empty($token)){
  149. return [
  150. 'x'=>'0',
  151. 'Description'=>"获取token失败",
  152. ];
  153. //throw new Exception("获取token失败");
  154. }
  155. $query = [
  156. 'order_number'=> $order_number,
  157. ];
  158. $url ="/v1/order/label/get";
  159. $res = $this->sendNewGet($url,$query,$token);
  160. $this->logic_ding->sendToDing($order_number."云途快递报文信息获取电子面单返回参数[".json_encode($res)."]");
  161. if(isset($res['code'])&&($res['code'] != 1)){
  162. return [
  163. 'x'=>'0',
  164. 'Description'=>$res['msg'],
  165. ];
  166. }else{
  167. return [
  168. 'x'=>'1',
  169. 'url'=>$res['result']['url'],
  170. ];
  171. }
  172. }
  173. /**
  174. * 基于guzzlehttp的get请求
  175. */
  176. protected function sendNewGet($url,$query,$token = ""){
  177. $timestamp = time() . "000";
  178. $bodyString=null;
  179. // 设置请求的URL
  180. $all_url = $this->base_url.$url."?".http_build_query($query);
  181. $tmp_sign = $this->generateSignatureContent($timestamp, "GET", $url, $bodyString);
  182. $sign= $this->generateSha256Signature($tmp_sign, $this->yt_config['appSecret']);
  183. // 初始化cURL会话
  184. $ch = curl_init($all_url);
  185. // 设置cURL选项
  186. $options = array(
  187. CURLOPT_SSL_VERIFYPEER=>false,
  188. CURLOPT_SSL_VERIFYHOST=>false,
  189. CURLOPT_RETURNTRANSFER => true,
  190. CURLOPT_HTTPHEADER => array(
  191. 'Content-Type: application/json',
  192. 'token: ' . $token ,
  193. 'date: ' . $timestamp,
  194. 'sign: ' . $sign
  195. ),
  196. );
  197. // 应用这些选项到cURL会话
  198. curl_setopt_array($ch, $options);
  199. // 执行cURL会话并获取响应
  200. $response = curl_exec($ch);
  201. // 检查是否有错误发生
  202. if ($response === false) {
  203. $error = curl_error($ch);
  204. curl_close($ch);
  205. return [
  206. "code"=> -1,
  207. "msg"=> $error
  208. ];
  209. }
  210. // 关闭cURL会话
  211. curl_close($ch);
  212. // 输出响应内容
  213. return json_decode($response,true);
  214. }
  215. /**
  216. * 基于guzzlehttp的post请求
  217. */
  218. protected function sendNewPost($url,$params,$token = ""){
  219. $timestamp = time() . "000";
  220. $bodyString=json_encode($params);
  221. // 设置请求的URL
  222. $all_url = $this->base_url.$url;
  223. $tmp_sign = $this->generateSignatureContent($timestamp, "POST", $url, $bodyString);
  224. $sign= $this->generateSha256Signature($tmp_sign, $this->yt_config['appSecret']);
  225. // 初始化cURL会话
  226. $ch = curl_init($all_url);
  227. // 设置cURL选项
  228. $options = array(
  229. CURLOPT_SSL_VERIFYPEER=>false,
  230. CURLOPT_SSL_VERIFYHOST=>false,
  231. CURLOPT_RETURNTRANSFER => true,
  232. CURLOPT_POST => true,
  233. CURLOPT_POSTFIELDS => $bodyString,
  234. CURLOPT_HTTPHEADER => array(
  235. 'Content-Type: application/json',
  236. 'token: ' . $token ,
  237. 'date: ' . $timestamp,
  238. 'sign: ' . $sign
  239. ),
  240. );
  241. // 应用这些选项到cURL会话
  242. curl_setopt_array($ch, $options);
  243. // 执行cURL会话并获取响应
  244. $response = curl_exec($ch);
  245. // 检查是否有错误发生
  246. // 检查是否有错误发生
  247. if ($response === false) {
  248. $error = curl_error($ch);
  249. curl_close($ch);
  250. return [
  251. "code"=> -1,
  252. "msg"=> $error
  253. ];
  254. }
  255. // 关闭cURL会话
  256. curl_close($ch);
  257. // 输出响应内容
  258. return json_decode($response,true);
  259. }
  260. /**
  261. * 基于guzzlehttp的post请求
  262. */
  263. protected function sendPost($url,$params,$token = ""){
  264. $all_url = $this->base_url.$url;
  265. $jsonData = json_encode($params);
  266. // 初始化cURL会话
  267. $ch = curl_init($all_url);
  268. // 设置cURL选项
  269. $options = [
  270. CURLOPT_SSL_VERIFYPEER=>false,
  271. CURLOPT_SSL_VERIFYHOST=>false,
  272. CURLOPT_RETURNTRANSFER => true,
  273. CURLOPT_POST => true,
  274. CURLOPT_POSTFIELDS => $jsonData,
  275. CURLOPT_HTTPHEADER => [
  276. 'Content-Type: application/json'
  277. ],
  278. ];
  279. curl_setopt_array($ch, $options);
  280. // 执行cURL会话并获取响应
  281. $response = curl_exec($ch);
  282. // 检查是否有错误发生
  283. if ($response === false) {
  284. $error = curl_error($ch);
  285. curl_close($ch);
  286. return [
  287. "code"=> -1,
  288. "msg"=> $error
  289. ];
  290. }
  291. // 关闭cURL会话
  292. curl_close($ch);
  293. $data = json_decode($response, true);
  294. return $data;
  295. }
  296. /**
  297. * 签名算法
  298. */
  299. /*
  300. * 加签内容构造
  301. */
  302. private function generateSignatureContent($timestamp, $method, $uri, $body = null) {
  303. $params = [
  304. 'date' => $timestamp,
  305. 'method' => $method,
  306. 'uri' => $uri,
  307. ];
  308. if (!empty($body)) {
  309. $params['body'] = $body;
  310. }
  311. ksort($params);
  312. $signatureContent = http_build_query($params, '', '&');
  313. return urldecode($signatureContent);
  314. }
  315. /*
  316. * 加签
  317. */
  318. private function generateSha256Signature($data, $key){
  319. //return utf8_encode(base64_encode(hash_hmac('sha256', $data,$key,true)));
  320. return mb_convert_encoding(base64_encode(hash_hmac('sha256', $data,$key,true)), 'ISO-8859-1', 'UTF-8');
  321. }
  322. private function getAccessToken(){
  323. $info= $this->setting->find("skey = 'yuntu_express_token'");
  324. if(empty($info)){
  325. $token = $this->makeToken();
  326. $this->setting->insert([
  327. "skey"=> "yuntu_express_token",
  328. "svalue"=> $token,
  329. "expiretime"=> (time() + 7100),
  330. "sessionkey"=> "yuntu_express_token"
  331. ]);
  332. return $token;
  333. }
  334. if($info['expiretime'] < time()){
  335. $token = $this->makeToken();
  336. $this->setting->save([
  337. "svalue"=> $token,
  338. "expiretime"=> (time() + 7100)
  339. ],"yuntu_express_token");
  340. return $token;
  341. }
  342. return $info['svalue'];
  343. }
  344. private function makeToken(){
  345. $res = $this->sendPost($this->token_url,[
  346. "grantType"=>"client_credentials",
  347. "appId"=> $this->yt_config['appId'],
  348. "appSecret"=>$this->yt_config['appSecret'],
  349. "sourceKey"=> $this->yt_config['sourceKey']
  350. ]);
  351. if(isset($res['accessToken'])){
  352. $token = $res['accessToken'];
  353. return $token;
  354. }else{
  355. $this->logic_ding->sendToDing("云途快递获取token失败,返回参数[".json_encode($res)."]");
  356. return "";
  357. }
  358. }
  359. /**
  360. * 获取运单号
  361. */
  362. public function getTransferNumber($waybill_numbers){
  363. // /v1/order/last-mile/get
  364. $token = $this->getAccessToken();
  365. if(empty($token)){
  366. throw new Exception("获取token失败");
  367. }
  368. $query = [
  369. 'waybill_numbers'=> $waybill_numbers,
  370. ];
  371. $url ="/v1/order/last-mile/get";
  372. $res = $this->sendNewPost($url,$query,$token);
  373. return $res;
  374. }
  375. }