DeliveryController.php 35 KB

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