DeliveryController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. namespace ghs\controllers;
  3. use biz\shop\classes\ShopClass;
  4. use bizGhs\express\classes\GhsDeliveryOrderClass;
  5. use bizGhs\express\classes\ShansAuthTokenClass;
  6. use bizGhs\order\classes\OrderClass;
  7. use common\components\delivery\services\adapter\HuolalaAdapter;
  8. use common\components\util;
  9. use common\components\delivery\services\DispatchService;
  10. use Yii;
  11. /**
  12. * 聚合配送(自配 + 聚合动力)
  13. * Class DeliveryController
  14. * @package ghs\controllers
  15. */
  16. class DeliveryController extends BaseController
  17. {
  18. public $guestAccess = ['callback', 'shansong-auth-callback', 'huolala-auth-callback', 'fengniao-callback'];
  19. // ------------------ 授权(账号绑定) ---------------------
  20. //授权
  21. public function actionMerchantAuth()
  22. {
  23. //闪送授权(商户授权:授权后能为商户下所有门店发单)
  24. $auth = new \common\components\delivery\platform\shansong\Auth();
  25. $redirectUrl = 'https://api.shop.hzghd.com/delivery/shansong-auth-callback';
  26. $authUrl = $auth->generateMerchantAuthUrl($this->mainId, $redirectUrl);
  27. // 重定向用户
  28. header('Location: ' . $authUrl);
  29. }
  30. public function actionHuolalaAuth()
  31. {
  32. $huoLalaAuth = new \common\components\delivery\platform\huolala\Auth();
  33. $mainId = $this->mainId;
  34. $redirectUrl = 'https://api.shop.hzghd.com/delivery/huolala-auth-callback' . '?mainId=' . $mainId;
  35. $authUrl = $huoLalaAuth->generateAuthUrl($redirectUrl);
  36. header('Location: ' . $authUrl);
  37. }
  38. public function actionFengniaoAuth()
  39. {
  40. $fengnaioAuth = new \common\components\delivery\platform\fengniao\Auth();
  41. $mainId = $this->mainId;
  42. $redirectUrl = 'https://api.shop.hzghd.com/delivery/fengniao-auth-callback' . '?mainId=' . $mainId;
  43. $authUrl = $fengnaioAuth->generateAuthUrl($redirectUrl);
  44. header('Location: ' . $authUrl);
  45. }
  46. public function actionDadaAuth()
  47. {
  48. $dadaAuth = new \common\components\delivery\platform\dada\Auth();
  49. $ticket = $dadaAuth->getTicket();
  50. $mainId = $this->mainId;
  51. $redirectUrl = 'https://api.shop.hzghd.com/delivery/dada-auth-callback' . '?mainId=' . $mainId;
  52. $shopNumber = '40d8391f9b05477b';
  53. $state = 'huidiao_biaoshi';
  54. $authUrl = $dadaAuth->generateAuthUrl($ticket, $state, $shopNumber);
  55. header('Location: ' . $authUrl);
  56. }
  57. public function actionHuolalaVehicle()
  58. {
  59. $mainId = $this->mainId;
  60. $authPlatforms = ShansAuthTokenClass::getByCondition(['user_id'=>$mainId, 'platform'=>'huolala']);
  61. $huolalaAdapter = new HuolalaAdapter($authPlatforms['access_token']);
  62. $cities = $huolalaAdapter->getCityVehicleList(1006);
  63. return $this->asJson($cities);
  64. }
  65. // 查询开通城市
  66. public function actionOpenCitiesLists()
  67. {
  68. $platform = Yii::$app->request->get('platform');
  69. $ds = new DispatchService($this->mainId);
  70. $cities = $ds->openCitiesLists($platform);
  71. if ($platform == 'shansong') {
  72. $newCitiesArr = [];
  73. $citiesArr = $cities['data'];
  74. foreach($citiesArr as $block) {
  75. foreach ($block['cities'] as $city) {
  76. $newCitiesArr[$city['name']] = $city;
  77. }
  78. }
  79. // 把newCitiesArr保存到 platform/huolala/cities.php 文件中
  80. $citiesFile = Yii::getAlias('@common/components/delivery/platform/shansong/cities.php');
  81. // 如果文件不存在,则创建文件
  82. if (!file_exists($citiesFile)) {
  83. file_put_contents($citiesFile, '<?php return []; ?>');
  84. }
  85. // 文件内容要包含命名空间
  86. $content = '<?php return ' . var_export($newCitiesArr, true) . '; ?>';
  87. file_put_contents($citiesFile, $content);
  88. return $newCitiesArr;
  89. } else if ($platform == 'huolala') {
  90. $citiesArr = $cities['data']['city_list'];
  91. $newCitiesArr = [
  92. 'expire' => $cities['data']['expire'],
  93. ];
  94. foreach($citiesArr as $city) {
  95. $newCitiesArr[$city['name']] = [
  96. 'city_id' => $city['city_id'],
  97. 'city_name' => $city['name'],
  98. ];
  99. }
  100. // 把newCitiesArr保存到 platform/huolala/cities.php 文件中
  101. $citiesFile = Yii::getAlias('@common/components/delivery/platform/huolala/cities.php');
  102. // 如果文件不存在,则创建文件
  103. if (!file_exists($citiesFile)) {
  104. file_put_contents($citiesFile, '<?php namespace common\components\delivery\platform\huolala; return []; ?>');
  105. }
  106. // 文件内容要包含命名空间
  107. $content = '<?php namespace common\components\delivery\platform\huolala; return ' . var_export($newCitiesArr, true) . '; ?>';
  108. file_put_contents($citiesFile, $content);
  109. return $newCitiesArr;
  110. } else {
  111. return $cities;
  112. }
  113. return $cities;
  114. }
  115. public function actionAddress()
  116. {
  117. $post = Yii::$app->request->post();
  118. $adminId = $this->adminId;
  119. util::checkRepeatCommit($adminId, 4);
  120. $orderId = intval($post['orderId']);
  121. $order = OrderClass::getById($orderId, false, 'fullAddress');
  122. $shop = ShopClass::getById($this->shopId, false, 'fullAddress');
  123. $ret = [
  124. "send_address" => $shop['fullAddress'],
  125. "receive_address" => $order['fullAddress']
  126. ];
  127. util::success($ret, "success");
  128. }
  129. // 获取多个平台报价
  130. public function actionAllDeliveryQuotes()
  131. {
  132. $post = Yii::$app->request->post();
  133. $orderTime = $post['pickupTime'];
  134. $adminId = $this->adminId;
  135. util::checkRepeatCommit($adminId, 4);
  136. $orderId = intval($post['orderId']);
  137. $order = OrderClass::getById($orderId);
  138. $shop = ShopClass::getById($this->shopId);
  139. $ds = new DispatchService($this->mainId);
  140. $platforms = $ds->getBestPlatformByPrice($order, $shop, $orderTime);
  141. $deliveryList = [];
  142. foreach ($platforms['quotes'] as $item) {
  143. switch ($item['platform']) {
  144. case 'shansong':
  145. $deliveryList[] = [
  146. 'name' => '闪送',
  147. 'en_name' => 'shansong',
  148. 'price' => $item['total_amount'],
  149. 'distance' => $item['total_distance'],
  150. 'type' => '',
  151. 'issOrderNo' => $item['order_number'] //
  152. ];
  153. break;
  154. case 'fengniao':
  155. // 循环遍历 goods_infos 数组,提取有效项的信息
  156. $validGoods = [];
  157. if (!empty($item['goods_infos']) && is_array($item['goods_infos'])) {
  158. foreach ($item['goods_infos'] as $good) {
  159. if (!empty($good['is_valid']) && $good['is_valid'] == 1) {
  160. $validGoods[] = [
  161. 'actual_delivery_amount_cent' => $good['actual_delivery_amount_cent'] ?? 0,
  162. 'service_goods_id' => $good['service_goods_id'] ?? ''
  163. ];
  164. }
  165. }
  166. }
  167. $deliveryList[] = [
  168. 'name' => '蜂鸟',
  169. 'en_name' => 'fengniao',
  170. 'price' => !empty($validGoods) ? $validGoods[0]['actual_delivery_amount_cent'] : 0,
  171. 'distance' => $item['distance'],
  172. 'valid_goods' => $validGoods, // 返回所有有效的商品信息
  173. 'type' => ''
  174. ];
  175. break;
  176. case 'huolala':
  177. $deliveryList[] = [
  178. 'name' => '货拉拉',
  179. 'en_name' => 'huolala',
  180. 'price' => isset($item['price_list']) ? $item['price_list'][0]['price_conditions'][0]['total_price'] : 0,
  181. 'distance' => isset($item['price_list']) ? $item['price_list'][0]['distance_info']['distance_total'] : 0,
  182. 'type' => $item['vehicle_type'],
  183. 'order_vehicle_id' => isset($item['price_list']) ? $item['price_list'][0]['vehicle_info']['order_vehicle_id'] : 0,
  184. 'city_id' => $item['city_id'],
  185. 'city_info_revision' => $item['city_info_revision'],
  186. // 下单需要透传的数据
  187. 'vehicle_std' => $item['vehicle_std'],
  188. 'spec_req' => $item['spec_req'],
  189. 'price_calculate_id' => isset($item['price_list']) ? $item['price_list'][0]['price_calculate_id'] : '',
  190. 'price_item_encryption' => isset($item['price_list']) ? $item['price_list'][0]['price_conditions'][0]['price_item_encryption'] : '',
  191. 'vehicle_attr' => isset($item['price_list']) ? $item['price_list'][0]['vehicle_info']['vehicle_attr'] : 0,
  192. 'commodity_info' => isset($item['price_list']) ? $item['price_list'][0]['price_conditions'][0]['commodity_info'] : [],
  193. ];
  194. break;
  195. }
  196. }
  197. $ret['deliveryList'] = $deliveryList;
  198. util::success($ret, "success");
  199. }
  200. // 创建订单(真实下单)
  201. public function actionCreateOrder()
  202. {
  203. $post = Yii::$app->request->post();
  204. $orderId = $post['orderId']; // xhGhsOrder.id
  205. $params = $post['allParams'];
  206. $platform = $params['en_name'];// $post['platform'] 是中文
  207. $pickupTime = $post['pickupTime'];
  208. $params['mainId'] = $this->mainId;
  209. $params['ip'] = Yii::$app->request->userIP;
  210. $params['remark'] = $post['remark'];
  211. $params['total_price_fen'] = $post['price'];
  212. $params['order_time'] = $pickupTime['value'];
  213. $shopId = $this->shopId;
  214. $ghsOrder = OrderClass::getById($orderId, true);
  215. // if ($ghsOrder['status'] != 2) {
  216. // util::fail('订单状态不是待配送');
  217. // }
  218. if(!in_array($ghsOrder['sendStatus'], [-4, -1])) {
  219. Yii::error('订单已经发过跑腿');
  220. util::fail('订单已经发过跑腿');
  221. }
  222. $ds = new DispatchService($this->mainId, $platform);
  223. $ret = $ds->createOrder($ghsOrder, $shopId, $params);
  224. if (isset($ret['code']) && $ret['code'] == 0) {
  225. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId'=>$this->mainId, 'orderId'=>$ret['data']['order_id']]);
  226. if (empty($gdo)) {
  227. $data = [
  228. 'mainId' => $this->mainId,
  229. 'shopId' => $this->shopId,
  230. 'deliveryId' => $ret['platform'],
  231. 'ghsOrderId' => $orderId,
  232. 'orderId' => $ret['data']['order_id'],
  233. 'distance' => $ret['data']['distance'],
  234. 'fee' => $ret['data']['fee'],
  235. 'orderStatus' => 0
  236. ];
  237. GhsDeliveryOrderClass::add($data);
  238. } else {
  239. Yii::info('重复创建订单');
  240. }
  241. //更新订单
  242. $ghsOrder->sendDistance = $ret['data']['distance'];
  243. $ghsOrder->sendStatus = 0;
  244. $ghsOrder->deliveryId = $ret['platform'];
  245. $ghsOrder->sendType = 2;// 2指跑腿
  246. $ghsOrder->save();
  247. util::success($ret, "success");
  248. }
  249. util::fail('创建跑腿失败');
  250. }
  251. /**
  252. * 查询订单
  253. *
  254. * 1. 蜂鸟平台 orderId 可以使用 "XSD_CS26322799" (即:表 xhGhsOrder.orderSn)
  255. */
  256. public function actionSelectOrder()
  257. {
  258. $post = Yii::$app->request->post();
  259. $platform = $post['platform'];
  260. $orderId = $post['orderId'];
  261. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : '';
  262. $ds = new DispatchService($this->mainId, $platform);
  263. $ret = $ds->selectOrder($orderId, $orderSn);
  264. $return = isset($ret['ret']) ? $ret['ret'] : $ret['code']; // 各平台兼容处理
  265. if($return == 0) {
  266. util::success($ret, "success");
  267. }
  268. util::fail('查询失败');
  269. }
  270. // 取消订单
  271. public function actionCancelOrder()
  272. {
  273. $post = Yii::$app->request->post();
  274. $orderId = $post['orderId'] ?? 0; // 平台的orderId,
  275. $platform = $post['platform'] ?? '';
  276. $ghsOrderId = $post['ghsOrderId'] ?? 0;
  277. if($platform == '') {
  278. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId'=>$this->mainId, 'ghsOrderId'=>$ghsOrderId, 'orderStatus!='=>-1], true);
  279. if(!empty($gdo)) {
  280. $orderId = $gdo->orderId;
  281. $platform = $gdo->deliveryId;
  282. } else {
  283. util::fail('未找到对应订单: ' . $ghsOrderId);
  284. }
  285. }
  286. $ds = new DispatchService($this->mainId, $platform);
  287. $ret = $ds->cancelOrder($orderId, '');
  288. if($ret['code'] == 0) {
  289. // 更新跑腿订单与批发订单状态
  290. $gdo->orderStatus = -1;
  291. $gdo->save();
  292. $ghsOrder = OrderClass::getById($ghsOrderId, true, 'id, sendDistance, sendStatus, deliveryId');
  293. $ghsOrder->sendDistance = 0;
  294. $ghsOrder->sendStatus = -4;
  295. $ghsOrder->deliveryId = '';
  296. $ghsOrder->save();
  297. util::success($ret['data'], "success");
  298. }
  299. util::fail('取消失败');
  300. }
  301. // 第三方回调入口
  302. /**
  303. * 回调接口
  304. */
  305. public function actionCallback()
  306. {
  307. $callbackData = Yii::$app->request->post();
  308. if (empty($callbackData)) {
  309. $postStr = file_get_contents('php://input');
  310. $callbackData = json_decode($postStr, true);
  311. if (empty($callbackData)) {
  312. util::fail('回调请求的数据为空');
  313. }
  314. }
  315. // 从配置中获取安全token
  316. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  317. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  318. // 记录回调日志
  319. Yii::info('聚合配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'delivery');
  320. }
  321. /**
  322. * 闪送回调接口
  323. */
  324. public function actionShansongCallback()
  325. {
  326. $callbackData = Yii::$app->request->post();
  327. if (empty($callbackData)) {
  328. $postStr = file_get_contents('php://input');
  329. $callbackData = json_decode($postStr, true);
  330. }
  331. Yii::info('shansong 回调 -- post: ' . json_encode($callbackData));
  332. $get = Yii::$app->request->get();
  333. Yii::info('shansong 回调 -- get: ' . json_encode($get));
  334. }
  335. /**
  336. * 蜂鸟回调接口
  337. */
  338. public function actionFengniaoCallback()
  339. {
  340. $callbackData = Yii::$app->request->post();
  341. if (empty($callbackData)) {
  342. $postStr = file_get_contents('php://input');
  343. $callbackData = json_decode($postStr, true);
  344. }
  345. Yii::info('fengniao 回调 -- post: ' . json_encode($callbackData));
  346. $get = Yii::$app->request->get();
  347. Yii::info('fengniao 回调 -- get: ' . json_encode($get));
  348. util::complete('蜂鸟回调接口');
  349. }
  350. /**
  351. * 闪送授权回调接口
  352. */
  353. public function actionShansongAuthCallback()
  354. {
  355. $code = Yii::$app->request->get('code');
  356. $state = Yii::$app->request->get('state');
  357. $shopId = Yii::$app->request->get('shopId');
  358. $isAllStoreAuth = Yii::$app->request->get('isAllStoreAuth');
  359. $thirdStoreId = Yii::$app->request->get('thirdStoreId');
  360. $storeId = Yii::$app->request->get('storeId');
  361. // 验证state参数(防止CSRF)
  362. //if ($state != $yourUserId) {
  363. //throw new \yii\web\BadRequestHttpException('Invalid state parameter');
  364. //}
  365. // 获取AccessToken
  366. $auth = new \common\components\delivery\platform\shansong\Auth();
  367. $result = $auth->getAccessToken($code);
  368. if (!$result['success']) {
  369. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  370. }
  371. // 保存授权信息到数据库
  372. $data = [
  373. 'user_id' => $state,
  374. 'shop_id' => $shopId,
  375. 'access_token' => $result['access_token'],
  376. 'refresh_token' => $result['refresh_token'],
  377. 'expires_at' => time() + $result['expires_in'],
  378. 'auth_type' => $isAllStoreAuth ? 'all_store' : 'single_store',
  379. 'platform_type' => 'shansong'
  380. ];
  381. if (!$isAllStoreAuth) {
  382. $data['third_store_id'] = $thirdStoreId;
  383. $data['shans_store_id'] = $storeId;
  384. }
  385. ShansAuthTokenClass::add($data);
  386. if (false) {
  387. throw new \yii\web\HttpException(500, '保存授权信息失败');
  388. }
  389. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  390. }
  391. /**
  392. * 货拉拉授权回调接口
  393. */
  394. public function actionHuolalaAuthCallback()
  395. {
  396. $get = Yii::$app->request->get();
  397. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  398. Yii::info($getData);
  399. $callbackData = Yii::$app->request->post();
  400. if (empty($callbackData)) {
  401. $postStr = file_get_contents('php://input');
  402. $callbackData = json_decode($postStr, true);
  403. if (empty($callbackData)) {
  404. Yii::info('回调请求的数据为空');
  405. }
  406. }
  407. Yii::info('货拉拉授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'delivery');
  408. $code = $get['code'];
  409. $mainId = $get['mainId'];
  410. // 获取AccessToken
  411. $auth = new \common\components\delivery\platform\huolala\Auth();
  412. $result = $auth->getAccessToken($code);
  413. if (!$result['success']) {
  414. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  415. }
  416. // 保存授权信息到数据库
  417. $data = [
  418. 'user_id' => $mainId,
  419. 'shop_id' => $result['auth_mobile'],
  420. 'access_token' => $result['access_token'],
  421. 'refresh_token' => $result['refresh_token'],
  422. 'expires_at' => strtotime($result['auth_end_time']),
  423. 'auth_type' => 'all_store',
  424. 'platform' => 'huolala'
  425. ];
  426. ShansAuthTokenClass::add($data);
  427. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  428. }
  429. /**
  430. * 蜂鸟授权回调接口
  431. */
  432. public function actionFengniaoAuthCallback()
  433. {
  434. $get = Yii::$app->request->get();
  435. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  436. Yii::info($getData);
  437. $callbackData = Yii::$app->request->post();
  438. if (empty($callbackData)) {
  439. $postStr = file_get_contents('php://input');
  440. $callbackData = json_decode($postStr, true);
  441. if (empty($callbackData)) {
  442. Yii::info('回调请求的数据为空');
  443. }
  444. }
  445. Yii::info('蜂鸟授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
  446. $mainId = $get['mainId'];
  447. $code = $get['code'];
  448. $merchantId = $get['merchant_id'];
  449. $scope = $get['scope'];
  450. $state = $get['state'];
  451. // 获取AccessToken
  452. $auth = new \common\components\delivery\platform\fengniao\Auth();
  453. $result = $auth->getAccessToken($code, $merchantId);
  454. if (!$result['success']) {
  455. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  456. }
  457. $result = $result['data'];
  458. // 保存授权信息到数据库
  459. $data = [
  460. 'user_id' => $mainId,
  461. 'shop_id' => '',
  462. 'access_token' => $result['access_token'],
  463. 'refresh_token' => $result['refresh_token'],
  464. 'expires_at' => $result['expire_in'],
  465. 'auth_type' => 'all_store',
  466. 'platform' => 'fengniao'
  467. ];
  468. ShansAuthTokenClass::add($data);
  469. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  470. }
  471. /**
  472. * 达达授权回调接口
  473. */
  474. public function actionDadaAuthCallback()
  475. {
  476. $get = Yii::$app->request->get();
  477. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  478. Yii::info($getData);
  479. $callbackData = Yii::$app->request->post();
  480. if (empty($callbackData)) {
  481. $postStr = file_get_contents('php://input');
  482. $callbackData = json_decode($postStr, true);
  483. if (empty($callbackData)) {
  484. Yii::info('回调请求的数据为空');
  485. }
  486. }
  487. Yii::info('达达授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'dada');
  488. }
  489. }