DeliveryController.php 38 KB

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