DeliveryController.php 38 KB

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