DeliveryController.php 38 KB

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