DeliveryController.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. <?php
  2. namespace ghs\controllers;
  3. use biz\common\classes\GhsNotifyClass;
  4. use Yii;
  5. use biz\shop\classes\ShopClass;
  6. use bizGhs\express\classes\GhsDeliveryOrderClass;
  7. use bizGhs\express\classes\DeliveryAuthTokenClass;
  8. use bizGhs\order\classes\OrderClass;
  9. use common\components\noticeUtil;
  10. use common\components\util;
  11. use common\components\delivery\services\DispatchService;
  12. use ghs\models\delivery\CancelOrderForm;
  13. use ghs\models\delivery\CreateOrderForm;
  14. use ghs\models\delivery\OrderDetailForm;
  15. use yii\web\Response;
  16. /**
  17. * 聚合配送
  18. * Class DeliveryController
  19. * @package ghs\controllers
  20. */
  21. class DeliveryController extends BaseController
  22. {
  23. public $guestAccess = [
  24. 'callback',
  25. 'shansong-auth-callback', 'shansong-callback',
  26. 'huolala-auth-callback', 'huolala-callback',
  27. 'fengniao-auth-callback', 'fengniao-callback',
  28. 'shunfeng-callback',
  29. 'dada-auth-callback', 'dada-callback',
  30. 'didi-auth-callback', 'didi-callback',
  31. ];
  32. public function actionList()
  33. {
  34. $platformList = [];
  35. $platformLogos = [
  36. 'dada' => ['name' => '达达', 'logo' => '📦'],
  37. 'shunfeng' => ['name' => '顺丰同城', 'logo' => '🚚'],
  38. 'meituan' => ['name' => '美团', 'logo' => '🍱'],
  39. 'fengniao' => ['name' => '蜂鸟', 'logo' => '🍜'],
  40. 'huolala' => ['name' => '货拉拉跑腿', 'logo' => '🚛'],
  41. 'shansong' => ['name' => '闪送', 'logo' => '⚡'],
  42. 'didi' => ['name' => '滴滴', 'logo' => '🚗'],
  43. 'uu' => ['name' => 'UU跑腿', 'logo' => '🛵']
  44. ];
  45. $allDeliveries = DeliveryAuthTokenClass::getAllByCondition(['mainId' => $this->mainId]);
  46. foreach ($allDeliveries as $d) {
  47. $item = [
  48. 'id' => $d['platform'],
  49. 'logo' => $platformLogos[$d['platform']]['logo'],
  50. 'name' => $platformLogos[$d['platform']]['name'],
  51. 'is_authorized' => true,
  52. 'balance' => $d['balance'] / 100.0,
  53. 'access_type' => 'oauth'
  54. ];
  55. $platformList[] = $item;
  56. }
  57. util::success(['platformList' => $platformList]);
  58. }
  59. // 获取授权URL
  60. public function actionGetAuthUrl()
  61. {
  62. $platform = Yii::$app->request->get('platformId');
  63. $Auth = new \common\components\delivery\services\AuthService();
  64. $mainId = $this->mainId;
  65. switch ($platform) {
  66. case 'shansong':
  67. $Auth->shansongAuth($mainId);
  68. break;
  69. case 'huolala':
  70. $Auth->huolalaAuth($mainId);
  71. break;
  72. case 'fengniao':
  73. $Auth->fengniaoAuth($mainId);
  74. break;
  75. case 'shunfeng':
  76. $Auth->shunfengAuth($mainId);
  77. break;
  78. case 'didi':
  79. $Auth->didiAuth($mainId, $this->shopId);
  80. break;
  81. case 'dada':
  82. $Auth->dadaAuth($mainId, $this->shopId);
  83. break;
  84. default:
  85. util::error(-1, $platform . '不存在');
  86. break;
  87. }
  88. }
  89. // 取消授权
  90. public function actionCancelAuth()
  91. {
  92. // 有平台有对应的取消授权接口,有的没有。
  93. // 有的就对接下,然后再删除数据。没有的直接删除数据就行。
  94. $platform = Yii::$app->request->get('platform');
  95. $delivery = DeliveryAuthTokenClass::getByCondition(['mainId' => $this->mainId, 'platform' => $platform]);
  96. if ($delivery) {
  97. if ($platform == 'shansong') {
  98. $auth = new \common\components\delivery\platform\shansong\Auth();
  99. $result = $auth->cancelAuthorization($delivery['accessToken']);
  100. if ($result['success']) {
  101. // 授权已取消
  102. } else {
  103. if ($result['message'] == '商户未授权,请授权后再次尝试') {
  104. Yii::info($this->mainId . '--商户未授权,请授权后再次尝试');
  105. } else {
  106. util::fail('取消授权失败:' . $result['message']);
  107. }
  108. }
  109. }
  110. } else {
  111. util::fail('取消授权失败,数据未找到');
  112. }
  113. $ret = DeliveryAuthTokenClass::deleteByCondition(['mainId' => $this->mainId, 'platform' => $platform]);
  114. if ($ret > 0) {
  115. util::success([], '取消授权成功');
  116. } else {
  117. util::fail('取消授权失败');
  118. }
  119. }
  120. // ----------------------------------------------- 各业务接口 ---------------------------------------------------------------
  121. // public function actionHuolalaVehicle()
  122. // {
  123. // $mainId = $this->mainId;
  124. // $authPlatforms = DeliveryAuthTokenClass::getByCondition(['mainId' => $mainId, 'platform' => 'huolala']);
  125. // $huolalaAdapter = new HuolalaAdapter($authPlatforms['access_token']);
  126. // $cities = $huolalaAdapter->getCityVehicleList(1006);
  127. // return $this->asJson($cities);
  128. // }
  129. /**
  130. * @deprecated
  131. *
  132. * 查询开通城市
  133. * @return array
  134. */
  135. public function actionOpenCitiesLists()
  136. {
  137. $platform = Yii::$app->request->get('platform');
  138. $ds = new DispatchService($this->mainId);
  139. $cities = $ds->openCitiesLists($platform);
  140. if ($platform == 'shansong') {
  141. $newCitiesArr = [];
  142. $citiesArr = $cities['data'];
  143. foreach ($citiesArr as $block) {
  144. foreach ($block['cities'] as $city) {
  145. $newCitiesArr[$city['name']] = $city;
  146. }
  147. }
  148. return $newCitiesArr;
  149. } else if ($platform == 'huolala') {
  150. $citiesArr = $cities['data']['city_list'];
  151. $newCitiesArr = [
  152. 'expire' => $cities['data']['expire'],
  153. ];
  154. foreach ($citiesArr as $city) {
  155. $newCitiesArr[$city['name']] = [
  156. 'city_id' => $city['city_id'],
  157. 'city_name' => $city['name'],
  158. ];
  159. }
  160. return $newCitiesArr;
  161. }
  162. return $cities;
  163. }
  164. // 获取发货地址和收货地址
  165. public function actionAddress()
  166. {
  167. $post = Yii::$app->request->post();
  168. $adminId = $this->adminId;
  169. util::checkRepeatCommit($adminId, 4);
  170. $orderId = intval($post['orderId']);
  171. $order = OrderClass::getById($orderId, false, 'fullAddress, long, lat');
  172. $shop = ShopClass::getById($this->shopId, false, 'fullAddress, long, lat');
  173. $ret = [
  174. "sender" => [
  175. 'name' => '门店',
  176. 'address' => $shop['fullAddress'],
  177. 'long' => $shop['long'],
  178. 'lat' => $shop['lat'],
  179. ],
  180. "receiver" => [
  181. 'name' => '客户',
  182. 'address' => $order['fullAddress'],
  183. 'long' => $order['long'],
  184. 'lat' => $order['lat'],
  185. ],
  186. ];
  187. util::success($ret, "success");
  188. }
  189. // 获取各跑腿平台报价
  190. public function actionAllDeliveryQuotes()
  191. {
  192. util::checkRepeatCommit($this->adminId, 3);
  193. $post = Yii::$app->request->post();
  194. $orderId = intval($post['orderId']);
  195. $order = OrderClass::getById($orderId);
  196. if (empty($order)) {
  197. util::fail('没有找到订单');
  198. }
  199. if ($order['mainId'] != $this->mainId) {
  200. util::fail('不是你的订单');
  201. }
  202. if (empty($order['address'])) {
  203. util::fail('客户地址缺失');
  204. }
  205. if (empty($order['long']) || empty($order['lat'])) {
  206. util::fail('客户地址信息缺失');
  207. }
  208. $pickupTime = $post['pickupTime'];
  209. $weight = $post['weight'];
  210. $remark = $post['remark'] ?? '';
  211. $order['weight'] = $weight;
  212. $order['remark'] = $remark;
  213. $shop = ShopClass::getById($this->shopId);
  214. $ds = new DispatchService($this->mainId);
  215. $ds->validateOrder($order); //对 $order 进行验证
  216. $platformQuotes = $ds->getAllPlatformPrice($order, $shop, $pickupTime);
  217. if (isset($platformQuotes['error'])) {
  218. util::fail($platformQuotes['error']);
  219. }
  220. // 格式化各平台报价为前端展示格式
  221. $deliveryList = $ds->formatPlatformQuotesForDisplay($platformQuotes);
  222. // 按 price 从低到高排序
  223. yii\helpers\ArrayHelper::multisort($deliveryList, 'price', SORT_ASC);
  224. $ret['deliveryList'] = $deliveryList;
  225. util::success($ret, "success");
  226. }
  227. // 批发快捷开单时 -- 获取各跑腿平台报价
  228. public function actionQuickOrderDeliveryQuotes()
  229. {
  230. $post = Yii::$app->request->post();
  231. $orderTime = date('Y-m-d H:i:s');
  232. // --------- $customId ----------
  233. $customId = $post['customId'];
  234. $custom = \bizGhs\custom\classes\CustomClass::getById($customId, true);
  235. if (empty($custom)) {
  236. util::fail('获取custom数据失败');
  237. }
  238. // 生成随机订单号,不要跟原来的混起来,跑腿-销售单-
  239. $prefix = 'PT-XSD-' . $this->mainId . '-';
  240. $orderSn = $prefix . round(microtime(true) * 1000);
  241. //构建出 Order 数据
  242. $order = [
  243. 'orderSn' => $orderSn,
  244. 'customName' => $custom['name'],
  245. 'customMobile' => $custom['mobile'],
  246. 'fullAddress' => $custom['fullAddress'],
  247. 'floor' => $custom['floor'],
  248. 'dist' => $custom['dist'],
  249. 'lat' => $custom['lat'],
  250. 'long' => $custom['long'],
  251. 'address' => $custom['address'], //'toAddress' => $order['address'],
  252. 'city' => $custom['city'],
  253. 'weight' => $post['weight'] ?? 1,
  254. 'remark' => $post['remark'] ?? '',
  255. 'prePrice' => floatval($post['totalPrice'] ?? 0),
  256. 'actPrice' => floatval($post['totalPrice'] ?? 0),
  257. ];
  258. $shop = ShopClass::getById($this->shopId);
  259. $ds = new DispatchService($this->mainId);
  260. $ds->validateOrder($order); //对 $order 进行验证
  261. $platformQuotes = $ds->getAllPlatformPrice($order, $shop, $orderTime);
  262. if (isset($platformQuotes['error'])) {
  263. util::fail($platformQuotes['error']);
  264. }
  265. // 格式化各平台报价为前端展示格式
  266. $deliveryList = $ds->formatPlatformQuotesForDisplay($platformQuotes);
  267. // 按 price 从低到高排序
  268. yii\helpers\ArrayHelper::multisort($deliveryList, 'price', SORT_ASC);
  269. $ret['deliveryList'] = $deliveryList;
  270. util::success($ret, "success");
  271. }
  272. // 创建订单(真实下单)
  273. public function actionCreateOrder()
  274. {
  275. $form = new CreateOrderForm();
  276. $form->loadAndValidate();
  277. $post = $form->getAttributes();
  278. $orderId = $post['orderId'] ?? 0; // xhGhsOrder.id
  279. $params = $post['allParams'] ?? [];
  280. $platform = $params['en_name'] ?? '';// 平台英文名,$post['platform'] 是中文
  281. if (empty($platform)) {
  282. util::fail('请选择跑腿');
  283. }
  284. $pickupTime = $post['pickupTime'];
  285. $params['mainId'] = $this->mainId;
  286. $params['ip'] = Yii::$app->request->userIP;
  287. $params['weight'] = $post['weight'];
  288. $params['remark'] = $post['remark'] ?? '';
  289. $params['total_price_fen'] = $post['price'];
  290. $params['pickupTime'] = $pickupTime['value'];
  291. $ghsOrder = OrderClass::getById($orderId, true);
  292. if (empty($ghsOrder)) {
  293. util::fail('没有找到订单');
  294. }
  295. if ($ghsOrder->mainId != $this->mainId) {
  296. util::fail('不是你的订单');
  297. }
  298. if (!in_array($ghsOrder['sendStatus'], [-4, -2, -1])) {
  299. Yii::error('订单已经发过跑腿');
  300. util::fail('订单已经发过跑腿');
  301. }
  302. //避免连续点击的重复提交 ssh
  303. $adminId = $this->adminId;
  304. util::checkRepeatCommit($adminId, 3);
  305. $ds = new DispatchService($this->mainId, $platform);
  306. $ret = $ds->createOrder($ghsOrder, 'xhGhsOrder', $this->shopId, $params);
  307. if (isset($ret['code']) && $ret['code'] == 0) {
  308. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'orderId' => $ret['data']['orderId'], 'orderStatus!=' => -1], true);
  309. if (empty($gdo)) {
  310. $data = [
  311. 'mainId' => $this->mainId,
  312. 'shopId' => $this->shopId,
  313. 'deliveryId' => $ret['platform'],
  314. 'ghsOrderId' => $orderId,
  315. 'orderId' => $ret['data']['orderId'],
  316. 'distance' => $ret['data']['distance'],
  317. 'fee' => $ret['data']['fee'],
  318. 'orderStatus' => 0
  319. ];
  320. // createdAt 中保存了滴滴跑腿订单的后半截数据
  321. if($platform == 'didi'){
  322. $data['createdAt'] = date('Y-m-d H:i:s', $ret['data']['timeStamp']);
  323. }
  324. GhsDeliveryOrderClass::add($data);
  325. } else {
  326. Yii::info('重复创建订单');
  327. noticeUtil::push('重复创建订单: ' . $ret['data']['orderId']);
  328. $gdo->orderId = $ret['data']['orderId'];
  329. $gdo->deliveryId = $ret['platform'];
  330. $gdo->distance = $ret['data']['distance'];
  331. $gdo->fee = $ret['data']['fee'];
  332. $gdo->orderStatus = 0;
  333. $gdo->save();
  334. }
  335. //更新订单
  336. $ghsOrder->sendDistance = $ret['data']['distance'];
  337. $ghsOrder->sendStatus = 0;
  338. $ghsOrder->deliveryId = $ret['platform'];
  339. $ghsOrder->sendType = 2;// 2指跑腿
  340. $ghsOrder->save();
  341. //OrderClass::hasSend($ghsOrder);// 更新 status (不正确的,暂留做为对比)
  342. //发货
  343. $params = ['fhType' => 0, 'fhWl' => '', 'fhWlNo' => '', 'staffId' => 0, 'staffName' => ''];
  344. OrderClass::orderSend($ghsOrder, $params);
  345. util::success($ret, "success");
  346. } else {
  347. if (isset($ret['msg'])) {
  348. util::fail($ret['msg']);
  349. }
  350. util::fail('创建跑腿失败');
  351. }
  352. }
  353. /**
  354. * 查询订单详情
  355. *
  356. * 1. 蜂鸟平台 orderId 可以使用 "XSD_CS26322799" (即:表 xhGhsOrder.orderSn)
  357. */
  358. public function actionOrderDetail()
  359. {
  360. $form = new OrderDetailForm();
  361. $form->loadAndValidate();
  362. $post = $form->getAttributes();
  363. $platform = $post['platform'];
  364. $orderId = $post['orderId'];
  365. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : '';
  366. $ds = new DispatchService($this->mainId, $platform);
  367. $ret = $ds->selectOrder($orderId, $orderSn);
  368. $return = isset($ret['ret']) ? $ret['ret'] : $ret['code']; // 各平台兼容处理
  369. if ($return == 0) {
  370. util::success($ret, "success");
  371. }
  372. util::fail('查询失败');
  373. }
  374. // 取消订单
  375. public function actionCancelOrder()
  376. {
  377. $form = new CancelOrderForm();
  378. $form->loadAndValidate();
  379. $post = $form->getAttributes();
  380. $orderId = $post['orderId'] ?? 0; // 平台的orderId,
  381. $platform = $post['platform'] ?? '';
  382. $ghsOrderId = $post['ghsOrderId'];
  383. // 先获取配送订单,确保 $gdo 始终可用
  384. $gdos = GhsDeliveryOrderClass::getAllByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus!=' => -1], 'id DESC', '*', null, true);
  385. if (empty($gdos)) {
  386. util::fail('未找到对应订单: ' . $ghsOrderId);
  387. }
  388. if(count($gdos)>=2){
  389. noticeUtil::push("xhGhsDeliveryOrder ghsOrderId={$ghsOrderId} 有两笔以上是在配送中");
  390. $gdo = $gdos[0];
  391. }else{
  392. $gdo = $gdos[0];
  393. }
  394. // 如果没有提供平台和订单ID,从配送订单中获取
  395. if ($platform == ''){
  396. $platform = $gdo->deliveryId;
  397. }
  398. if($orderId == 0) {
  399. $orderId = $gdo->orderId;
  400. }
  401. $ds = new DispatchService($this->mainId, $platform);
  402. $cancelCostCent = 0;
  403. if ($platform == 'fengniao') {
  404. //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
  405. $cancelParams = ['order_id' => $orderId, 'order_cancel_code' => $post['order_cancel_code']];
  406. $res = $ds->getAdapter()->preCancelOrder($cancelParams);
  407. if ($res['code'] != 0) {
  408. util::fail('运单状态不允许取消');
  409. }
  410. $cancelCostCent = $res['data']['actual_cancel_cost_cent']; //取消实际需金额(单位:分)
  411. }
  412. if ($platform == 'shunfeng') {
  413. //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
  414. $cancelParams = ['order_id' => $orderId, 'order_cancel_code' => $post['order_cancel_code']];
  415. $res = $ds->getAdapter()->preCancelOrder($cancelParams);
  416. if ($res['code'] != 0) {
  417. util::fail('运单状态不允许取消');
  418. }
  419. $post['order_type'] = 1; //查询订单ID类型 1、顺丰订单号 2、商家订单号
  420. }
  421. if ($platform == 'dada') {
  422. $order = OrderClass::getById($gdo->ghsOrderId, false, 'id,orderSn');
  423. $orderId = $order['orderSn'];
  424. }
  425. if ($platform == 'didi') {
  426. $order = OrderClass::getById($gdo->ghsOrderId, false, 'id,orderSn');
  427. $timeStamp = strtotime($gdo->createdAt);
  428. $post['outOrderNo'] = \common\components\delivery\platform\didi\Didi::generateUniOroder($order['orderSn'], $timeStamp);
  429. $post['cancelSource'] = 1; // TODO 要增加取消码判断
  430. }
  431. $post['order_cancel_role'] = 1; //1:商户取消, 2:用户取消
  432. $ret = $ds->cancelOrder($orderId, $post);
  433. if ($ret['code'] == 0) {
  434. $ghsOrder = OrderClass::getById($ghsOrderId, true, 'id, sendDistance, sendStatus, deliveryId, purchaseId, status, purchaseId');
  435. $ghsOrder->sendDistance = 0;
  436. // 测试发现取消配送没回调的平台,统一在这主动更新配送状态
  437. if(in_array($platform, ['shunfeng', 'fengniao'])){
  438. $ghsOrder->sendStatus = -1;
  439. OrderClass::cancelOrderSend($ghsOrder, ['staffId' => 0, 'staffName' => '']);
  440. // 更新跑腿订单与批发订单状态
  441. $gdo->orderStatus = -1;
  442. OrderClass::cancelOrderSend($ghsOrder, ['staffId' => 0, 'staffName' => '']);
  443. GhsNotifyClass::ptErrorNotify($ghsOrder->id, '门店主动取消');
  444. }
  445. $gdo->cancelCost = $ret['platform'] !== 'fengniao' ? $ret['data']['deductionFee'] : $cancelCostCent; // 由于蜂鸟平台返回的扣费不一样造成
  446. if (!$gdo->save()) {
  447. Yii::error('保存配送订单失败: ' . json_encode($gdo->errors));
  448. util::fail('保存配送订单失败');
  449. }
  450. // $ghsOrder->deliveryId = ''; // 为了获取上一次的配送记录,不要置空
  451. $ghsOrder->sendTip = 0;
  452. if (!$ghsOrder->save()) {
  453. Yii::error('保存批发订单失败: ' . json_encode($ghsOrder->errors));
  454. util::fail('保存批发订单失败');
  455. }
  456. util::success($ret['data'], "success");
  457. }
  458. util::fail('失败:'.$ret['msg']);
  459. }
  460. /**
  461. * 获取订单取消原因
  462. */
  463. public function actionCancelReason()
  464. {
  465. $post = Yii::$app->request->post();
  466. $ghsOrderId = $post['ghsOrderId'];
  467. $platform = $post['platform'];
  468. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus!=' => -1], true);
  469. if (!empty($gdo)) {
  470. $orderId = $gdo->orderId;
  471. //$platform = $gdo->deliveryId;
  472. } else {
  473. util::fail('未找到对应订单: ' . $ghsOrderId);
  474. }
  475. $ds = new DispatchService($this->mainId, $platform);
  476. $ret = $ds->getCancelReasonList($orderId);
  477. if ($ret['code'] == 0) {
  478. util::success($ret['data']);
  479. } else {
  480. Yii::error('获取订单取消原因:' . json_encode($ret));
  481. util::fail($ret['msg']);
  482. }
  483. }
  484. /**
  485. * 添加小费
  486. */
  487. public function actionAddTip()
  488. {
  489. $post = Yii::$app->request->post();
  490. $ghsOrderId = $post['ghsOrderId'];
  491. $platform = $post['platform'];
  492. $tips = intval($post['tips']);
  493. if ($tips < 0) {
  494. util::fail('小费金额至少为1元');
  495. }
  496. $tips *= 100;
  497. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus' => ['in', [0, 1, 2, 10]]], true);
  498. if ($gdo == null) {
  499. util::fail('当前配送状态无法加小费');
  500. }
  501. $ds = new DispatchService($this->mainId, $platform);
  502. $ret = $ds->addTip(['orderId' => $gdo->orderId, 'tips' => $tips]);
  503. if ($ret['code'] == 0) {
  504. $gdo->tip = $tips + $gdo->tip;
  505. $gdo->save();
  506. $orderObj = OrderClass::getById($gdo->ghsOrderId, true, 'id,sendTip');
  507. $orderObj->sendTip = $tips / 100 + $orderObj->sendTip;
  508. $orderObj->save();
  509. util::success($ret['data']);
  510. } else {
  511. Yii::error('添加小费请求失败,请求数据是:' . json_encode($ret));
  512. util::fail($ret['msg']);
  513. }
  514. }
  515. // ---------------------------------------------------- 普通回调接口 ----------------------------------------------------------
  516. // 第三方回调入口
  517. /**
  518. * 回调接口
  519. */
  520. public function actionCallback()
  521. {
  522. $callbackData = Yii::$app->request->post();
  523. if (empty($callbackData)) {
  524. $postStr = file_get_contents('php://input');
  525. $callbackData = json_decode($postStr, true);
  526. if (empty($callbackData)) {
  527. util::fail('回调请求的数据为空');
  528. }
  529. }
  530. // 记录回调日志
  531. Yii::info('聚合配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'delivery');
  532. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  533. }
  534. /**
  535. * 闪送回调接口
  536. * 回调返回的格式必须是{"status":200,"msg":"","data":null}格式,当status为200表示回调成功,否则,回调失败。当回调失败时,间隔一分钟重试一次,最多重试五次。
  537. */
  538. public function actionShansongCallback()
  539. {
  540. $callbackData = Yii::$app->request->post();
  541. if (empty($callbackData)) {
  542. $postStr = file_get_contents('php://input');
  543. $callbackData = json_decode($postStr, true);
  544. }
  545. Yii::info('shansong 回调 -- post: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  546. $obj = new \common\components\delivery\platform\shansong\OrderStatusCallBack();
  547. $ret = $obj->handle($callbackData);
  548. if ($ret) {
  549. return $this->asJson(['status' => 200, 'msg' => 'OK', "data" => null]);
  550. } else {
  551. Yii::error('闪送回调失败: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  552. return $this->asJson(['status' => 200, 'msg' => '回调失败', "data" => null]);
  553. }
  554. }
  555. /**
  556. * 蜂鸟回调接口
  557. */
  558. public function actionFengniaoCallback()
  559. {
  560. $callbackData = Yii::$app->request->post();
  561. Yii::info('fengniao 回调 -- post: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  562. // 逆向回调接口结果的加签
  563. $param = [
  564. 'app_id' => $callbackData['app_id'],
  565. 'timestamp' => $callbackData['timestamp'],
  566. 'business_data' => $callbackData['business_data']
  567. ];
  568. $fa = new \common\components\delivery\services\adapter\FengniaoAdapter();
  569. $paramSign = $fa->generateSignature($param);
  570. if ($paramSign == $callbackData['signature']) {
  571. $businessData = isset($callbackData['business_data']) ? $callbackData['business_data'] : '';
  572. if (empty($businessData)) {
  573. $this->asJson(['return_code' => -1, 'return_msg' => 'business data is empty']);
  574. }
  575. $businessData = json_decode($businessData, true);
  576. $cbnObj = new \common\components\delivery\platform\fengniao\CallBackNotify();
  577. $ret = $cbnObj->handle($businessData['callback_business_type'], $businessData['param']);
  578. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  579. } else {
  580. Yii::error('蜂鸟回调接口签名出错');
  581. }
  582. }
  583. /**
  584. * 货拉拉回调接口
  585. */
  586. public function actionHuolalaCallback()
  587. {
  588. $post = Yii::$app->request->post();
  589. Yii::info('货拉拉回调接口post:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'delivery');
  590. $action = $post['action'] ?? '';
  591. if ($action != 'order_update') {
  592. Yii::error('当前接口只处理货拉拉订单状态变更事件');
  593. return $this->asJson(['return_code' => 0, 'msg' => '当前接口只处理货拉拉订单状态变更事件']);
  594. }
  595. $param = $post;
  596. unset($param['signature']);
  597. $huolala = new \common\components\delivery\platform\huolala\Huolala();
  598. $paramSign = $huolala->generateSignatureWithoutAppSecret($param); //注意:不用拼接secret,所有的参数都参与计算,包含空值。
  599. if ($paramSign == $post['signature']) {
  600. $cbh = new \common\components\delivery\platform\huolala\CallBackHandler();
  601. $ret = $cbh->handler($post);
  602. if ($ret) {
  603. return $this->asJson(['serial_no' => $post['serial_no']]);
  604. } else {
  605. Yii::error('货拉拉回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
  606. return $this->asJson(['return_code' => -1, 'return_msg' => 'failed']);
  607. }
  608. } else {
  609. Yii::error('蜂鸟回调接口签名出错');
  610. return $this->asJson(['return_code' => -1, 'return_msg' => 'signature error']);
  611. }
  612. }
  613. /**
  614. * 达达回调接口
  615. */
  616. public function actionDadaCallback()
  617. {
  618. $post = Yii::$app->request->post();
  619. if (empty($post)) {
  620. $postStr = file_get_contents('php://input');
  621. $post = json_decode($postStr, true);
  622. }
  623. Yii::info('达达回调:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'dada-callback');
  624. $handler = new \common\components\delivery\platform\dada\CallBackHandler();
  625. $ret = $handler->handle($post);
  626. if($ret){
  627. Yii::info('达达回调业务成功处理', 'dada-callback');
  628. }
  629. return $this->asJson(['status' => 'ok']);
  630. }
  631. /**
  632. * 顺丰回调接口
  633. *
  634. * 授权回调也是在这实现的
  635. */
  636. public function actionShunfengCallback()
  637. {
  638. $post = Yii::$app->request->post();
  639. $cbh = new \common\components\delivery\platform\shunfeng\CallBackHandler();
  640. $ret = $cbh->handle($post);// 各回调处理
  641. if ($ret) {
  642. return $this->asJson(['error_code' => 0, 'error_msg' => 'success']);
  643. } else {
  644. Yii::error('顺丰回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
  645. return $this->asJson(['error_code' => -1, 'error_msg' => 'failed']);
  646. }
  647. }
  648. /**
  649. * 滴滴回调接口
  650. */
  651. public function actionDidiCallback()
  652. {
  653. $post = Yii::$app->request->post();
  654. Yii::info('didi callback: ' . json_encode($post));
  655. $cbh = new \common\components\delivery\platform\didi\CallBackHandler();
  656. $ret = $cbh->handle($post);// 各回调处理
  657. if ($ret) {
  658. if(is_array($ret)){
  659. return $this->asJson($ret);
  660. }
  661. return $this->asJson(['error_code' => 0, 'error_msg' => 'success']);
  662. } else {
  663. Yii::error('滴滴回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
  664. return $this->asJson(['error_code' => -1, 'error_msg' => 'failed']);
  665. }
  666. }
  667. // ---------------------------------------------------- 授权回调接口 ----------------------------------------------------------
  668. /**
  669. * 闪送授权回调接口
  670. */
  671. public function actionShansongAuthCallback()
  672. {
  673. $code = Yii::$app->request->get('code');
  674. $state = Yii::$app->request->get('state');
  675. $shopId = Yii::$app->request->get('shopId');
  676. $isAllStoreAuth = Yii::$app->request->get('isAllStoreAuth');
  677. $thirdStoreId = Yii::$app->request->get('thirdStoreId');
  678. $storeId = Yii::$app->request->get('storeId');
  679. // 验证state参数(防止CSRF)
  680. //if ($state != $yourUserId) {
  681. //throw new \yii\web\BadRequestHttpException('Invalid state parameter');
  682. //}
  683. // 获取AccessToken
  684. $auth = new \common\components\delivery\platform\shansong\Auth();
  685. $result = $auth->getAccessToken($code);
  686. if (!$result['success']) {
  687. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  688. }
  689. // 保存授权信息到数据库
  690. $data = [
  691. 'mainId' => $state,
  692. 'shopId' => $shopId, //闪送商户ID
  693. 'accessToken' => $result['access_token'],
  694. 'refreshToken' => $result['refresh_token'],
  695. 'expiresAt' => time() + $result['expires_in'],
  696. 'authType' => $isAllStoreAuth ? 'all_store' : 'single_store',
  697. 'platform' => 'shansong'
  698. ];
  699. if (!$isAllStoreAuth) {
  700. $data['third_store_id'] = $thirdStoreId;
  701. $data['shans_store_id'] = $storeId;
  702. }
  703. DeliveryAuthTokenClass::add($data);
  704. if (false) {
  705. throw new \yii\web\HttpException(500, '保存授权信息失败');
  706. }
  707. $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
  708. $template = '';
  709. if (is_file($templatePath) && is_readable($templatePath)) {
  710. $template = file_get_contents($templatePath);
  711. }
  712. if ($template === false || $template === '') {
  713. throw new \yii\web\HttpException(500, '返回h5页面不存在');
  714. }
  715. $content = strtr($template, [
  716. '{{title}}' => '授权成功',
  717. '{{heading}}' => '授权成功',
  718. '{{message}}' => '您的闪送账号已成功完成授权,现在可以返回使用聚合配送服务。',
  719. ]);
  720. $response = Yii::$app->response;
  721. $response->format = Response::FORMAT_HTML;
  722. $response->content = $content;
  723. return $response;
  724. }
  725. /**
  726. * 货拉拉授权回调接口
  727. */
  728. public function actionHuolalaAuthCallback()
  729. {
  730. $get = Yii::$app->request->get();
  731. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  732. Yii::info($getData);
  733. $code = $get['code'];
  734. $mainId = $get['mainId'];
  735. // 获取AccessToken
  736. $auth = new \common\components\delivery\platform\huolala\Auth();
  737. $result = $auth->getAccessToken($code);
  738. if (!$result['success']) {
  739. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  740. }
  741. // 保存授权信息到数据库
  742. $data = [
  743. 'mainId' => $mainId,
  744. 'shopId' => '',
  745. 'accessToken' => $result['access_token'],
  746. 'refreshToken' => $result['refresh_token'],
  747. 'expiresAt' => strtotime($result['auth_end_time']),
  748. 'authType' => 'all_store',
  749. 'platform' => 'huolala'
  750. ];
  751. DeliveryAuthTokenClass::add($data);
  752. $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
  753. $template = '';
  754. if (is_file($templatePath) && is_readable($templatePath)) {
  755. $template = file_get_contents($templatePath);
  756. }
  757. if ($template === false || $template === '') {
  758. $template = '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{title}}</title></head><body><h1>{{heading}}</h1><p>{{message}}</p></body></html>';
  759. }
  760. $content = strtr($template, [
  761. '{{title}}' => '授权成功',
  762. '{{heading}}' => '授权成功',
  763. '{{message}}' => '您的货拉拉账号已成功完成授权,现在可以返回使用聚合配送服务。',
  764. ]);
  765. $response = Yii::$app->response;
  766. $response->format = Response::FORMAT_HTML;
  767. $response->content = $content;
  768. return $response;
  769. }
  770. /**
  771. * 蜂鸟授权回调接口
  772. */
  773. public function actionFengniaoAuthCallback()
  774. {
  775. $callbackData = Yii::$app->request->post();
  776. if (empty($callbackData)) {
  777. Yii::error('回调请求的数据为空');
  778. }
  779. Yii::info('蜂鸟授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
  780. $get = Yii::$app->request->get();
  781. if (!isset($get['main_id'])) {
  782. Yii::error('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id');
  783. noticeUtil::push('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id,回调数据:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
  784. return;
  785. }
  786. $mainId = $get['main_id'];
  787. $code = $callbackData['code'];
  788. $merchantId = $callbackData['merchant_id'];
  789. $scope = $callbackData['scope'];
  790. $state = $callbackData['state'];
  791. // 获取AccessToken
  792. $auth = new \common\components\delivery\platform\fengniao\Auth();
  793. $result = $auth->getAccessToken($code, $merchantId);
  794. if (!$result['success']) {
  795. noticeUtil::push("mainId=" . $mainId . ' 授权时,获取token失败,请让其重新发起授权');
  796. Yii::error(json_encode($result));
  797. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  798. }
  799. $result = $result['data'];
  800. $exist = DeliveryAuthTokenClass::exists(['mainId' => $mainId, 'platform' => 'fengniao']);
  801. if ($exist) {
  802. noticeUtil::push("mainId=" . $mainId . ' 已成功授权了。如果蜂鸟不能正确使用,请查询数据库进行检查。');
  803. } else {
  804. // 保存授权信息到数据库
  805. $data = [
  806. 'mainId' => $mainId,
  807. 'merchantId' => $merchantId,
  808. 'shopId' => '',
  809. 'accessToken' => $result['access_token'],
  810. 'refreshToken' => $result['refresh_token'],
  811. 'expiresAt' => $result['expire_in'] + time(),
  812. 'authType' => 'all_store', //即 scope='all'
  813. 'platform' => 'fengniao'
  814. ];
  815. DeliveryAuthTokenClass::add($data);
  816. }
  817. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  818. }
  819. /**
  820. * 达达授权回调接口
  821. */
  822. public function actionDadaAuthCallback()
  823. {
  824. $get = Yii::$app->request->get();
  825. $getData = $get;
  826. Yii::info(json_encode($get, JSON_UNESCAPED_UNICODE));
  827. // {"sourceId":"1003654","ticket":"b8b4e56a86934b73a512ea9994e7774e","state":"huidiao_biaoshi","shopNo":"1003654-88547413"}
  828. if ($getData['state'] != 'huidiao_biaoshi') {
  829. Yii::error('达达授权回调 state 参数不对');
  830. return;
  831. }
  832. if (!isset($getData['mainId'])) {
  833. Yii::error('达达授权回调缺少必要参数 mainId');
  834. return;
  835. }
  836. try {
  837. // 保存授权信息到数据库
  838. $data = [
  839. 'mainId' => $getData['mainId'],
  840. 'merchantId' => $getData['sourceId'], // 用merchanId 来保存 sourceId
  841. 'shopId' => $getData['shopNo'],
  842. 'accessToken' => '',
  843. 'refreshToken' => '',
  844. 'expiresAt' => 9997773456,
  845. 'authType' => 'all_store', //即 scope='all'
  846. 'platform' => 'dada'
  847. ];
  848. DeliveryAuthTokenClass::add($data);
  849. $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
  850. $template = '';
  851. if (is_file($templatePath) && is_readable($templatePath)) {
  852. $template = file_get_contents($templatePath);
  853. }
  854. if ($template === false || $template === '') {
  855. $template = '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{title}}</title></head><body><h1>{{heading}}</h1><p>{{message}}</p></body></html>';
  856. }
  857. $content = strtr($template, [
  858. '{{title}}' => '授权成功',
  859. '{{heading}}' => '授权成功',
  860. '{{message}}' => '您的达达账号已成功完成授权,现在可以返回使用聚合配送服务。',
  861. ]);
  862. $response = Yii::$app->response;
  863. $response->format = Response::FORMAT_HTML;
  864. $response->content = $content;
  865. Yii::info('达达授权回调保存成功', 'dada');
  866. return $response;
  867. } catch (\Exception $e) {
  868. Yii::error('达达授权回调保存失败' . $e->getMessage(), 'dada');
  869. }
  870. }
  871. public function actionDidiAuthCallback()
  872. {
  873. $callbackData = Yii::$app->request->post();
  874. if (empty($callbackData)) {
  875. Yii::error('回调请求的数据为空');
  876. }
  877. Yii::info('滴滴授权回调:' . json_encode($callbackData), 'didi');
  878. try {
  879. $param = json_decode($callbackData['logisticsParam'], true);
  880. // 保存授权信息到数据库
  881. $data = [
  882. 'mainId' => $param['thirdUid'],
  883. 'merchantId' => '',
  884. 'shopId' => '',
  885. 'accessToken' => $param['token'],
  886. 'refreshToken' => '',
  887. 'expiresAt' => 9997773456,
  888. 'authType' => 'all_store', //即 scope='all'
  889. 'platform' => 'didi'
  890. ];
  891. DeliveryAuthTokenClass::add($data);
  892. Yii::info('滴滴授权回调保存成功', 'didi');
  893. return $this->asJson(['code' => 200, 'msg' => 'auth success', 'data' => ['msg'=>'success']]);
  894. } catch (\Exception $e) {
  895. Yii::error('滴滴授权回调保存失败' . $e->getMessage(), 'didi');
  896. }
  897. }
  898. }