DeliveryController.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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\delivery\services\adapter\HuolalaAdapter;
  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. use yii\helpers\ArrayHelper;
  17. /**
  18. * 聚合配送(自配 + 聚合动力)
  19. * Class DeliveryController
  20. * @package ghs\controllers
  21. */
  22. class DeliveryController extends BaseController
  23. {
  24. public $guestAccess = [
  25. 'callback',
  26. 'shansong-auth-callback', 'shansong-callback',
  27. 'huolala-auth-callback', 'huolala-callback',
  28. 'fengniao-auth-callback', 'fengniao-callback',
  29. 'shunfeng-callback',
  30. 'dada-auth-callback', 'dada-callback',
  31. 'didi-auth-callback', 'didi-callback',
  32. ];
  33. public function actionList()
  34. {
  35. $platformList = [];
  36. $platformLogos = [
  37. 'dada' => ['name' => '达达', 'logo' => '📦'],
  38. 'shunfeng' => ['name' => '顺丰同城', 'logo' => '🚚'],
  39. 'meituan' => ['name' => '美团', 'logo' => '🍱'],
  40. 'fengniao' => ['name' => '蜂鸟', 'logo' => '🍜'],
  41. 'huolala' => ['name' => '货拉拉跑腿', 'logo' => '🚛'],
  42. 'shansong' => ['name' => '闪送', 'logo' => '⚡'],
  43. 'didi' => ['name' => '滴滴', 'logo' => '🚗'],
  44. 'uu' => ['name' => 'UU跑腿', 'logo' => '🛵']
  45. ];
  46. $allDeliveries = DeliveryAuthTokenClass::getAllByCondition(['mainId' => $this->mainId]);
  47. foreach ($allDeliveries as $d) {
  48. $item = [
  49. 'id' => $d['platform'],
  50. 'logo' => $platformLogos[$d['platform']]['logo'],
  51. 'name' => $platformLogos[$d['platform']]['name'],
  52. 'is_authorized' => true,
  53. 'balance' => $d['balance'] / 100.0,
  54. 'access_type' => 'oauth'
  55. ];
  56. $platformList[] = $item;
  57. }
  58. util::success(['platformList' => $platformList]);
  59. }
  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. public function actionCancelAuth()
  90. {
  91. // 有平台有对应的取消授权接口,有的没有。
  92. // 有的就对接下,然后再删除数据。没有的直接删除数据就行。
  93. $platform = Yii::$app->request->get('platform');
  94. $delivery = DeliveryAuthTokenClass::getByCondition(['mainId' => $this->mainId, 'platform' => $platform]);
  95. if ($delivery) {
  96. if ($platform == 'shansong') {
  97. $auth = new \common\components\delivery\platform\shansong\Auth();
  98. $result = $auth->cancelAuthorization($delivery['accessToken']);
  99. if ($result['success']) {
  100. // 授权已取消
  101. } else {
  102. if ($result['message'] == '商户未授权,请授权后再次尝试') {
  103. Yii::info($this->mainId . '--商户未授权,请授权后再次尝试');
  104. } else {
  105. util::fail('取消授权失败:' . $result['message']);
  106. }
  107. }
  108. }
  109. } else {
  110. util::fail('取消授权失败,数据未找到');
  111. }
  112. $ret = DeliveryAuthTokenClass::deleteByCondition(['mainId' => $this->mainId, 'platform' => $platform]);
  113. if ($ret > 0) {
  114. util::success([], '取消授权成功');
  115. } else {
  116. util::fail('取消授权失败');
  117. }
  118. }
  119. // --------------------------------------------------------------------------------------------------------------
  120. public function actionHuolalaVehicle()
  121. {
  122. $mainId = $this->mainId;
  123. $authPlatforms = DeliveryAuthTokenClass::getByCondition(['mainId' => $mainId, 'platform' => 'huolala']);
  124. $huolalaAdapter = new HuolalaAdapter($authPlatforms['access_token']);
  125. $cities = $huolalaAdapter->getCityVehicleList(1006);
  126. return $this->asJson($cities);
  127. }
  128. /**
  129. * @deprecated
  130. *
  131. * 查询开通城市
  132. * @return array
  133. */
  134. public function actionOpenCitiesLists()
  135. {
  136. $platform = Yii::$app->request->get('platform');
  137. $ds = new DispatchService($this->mainId);
  138. $cities = $ds->openCitiesLists($platform);
  139. if ($platform == 'shansong') {
  140. $newCitiesArr = [];
  141. $citiesArr = $cities['data'];
  142. foreach ($citiesArr as $block) {
  143. foreach ($block['cities'] as $city) {
  144. $newCitiesArr[$city['name']] = $city;
  145. }
  146. }
  147. return $newCitiesArr;
  148. } else if ($platform == 'huolala') {
  149. $citiesArr = $cities['data']['city_list'];
  150. $newCitiesArr = [
  151. 'expire' => $cities['data']['expire'],
  152. ];
  153. foreach ($citiesArr as $city) {
  154. $newCitiesArr[$city['name']] = [
  155. 'city_id' => $city['city_id'],
  156. 'city_name' => $city['name'],
  157. ];
  158. }
  159. return $newCitiesArr;
  160. }
  161. return $cities;
  162. }
  163. public function actionAddress()
  164. {
  165. $post = Yii::$app->request->post();
  166. $adminId = $this->adminId;
  167. util::checkRepeatCommit($adminId, 4);
  168. $orderId = intval($post['orderId']);
  169. $order = OrderClass::getById($orderId, false, 'fullAddress');
  170. $shop = ShopClass::getById($this->shopId, false, 'fullAddress');
  171. $ret = [
  172. "send_address" => $shop['fullAddress'],
  173. "receive_address" => $order['fullAddress']
  174. ];
  175. util::success($ret, "success");
  176. }
  177. // 获取多个平台报价
  178. public function actionAllDeliveryQuotes()
  179. {
  180. $post = Yii::$app->request->post();
  181. $orderTime = $post['pickupTime'];
  182. $weight = $post['weight'];
  183. $remark = $post['remark'] ?? '';
  184. $adminId = $this->adminId;
  185. util::checkRepeatCommit($adminId, 3);
  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. $shop = ShopClass::getById($this->shopId);
  201. $order['weight'] = $weight;
  202. $order['remark'] = $remark;
  203. $ds = new DispatchService($this->mainId);
  204. $platformQuotes = $ds->getAllPlatformPrice($order, $shop, $orderTime);
  205. if (isset($platformQuotes['error'])) {
  206. util::fail($platformQuotes['error']);
  207. }
  208. // 格式化各平台报价为前端展示格式
  209. $deliveryList = $ds->formatPlatformQuotesForDisplay($platformQuotes);
  210. // 按 price 从低到高排序
  211. ArrayHelper::multisort($deliveryList, 'price', SORT_ASC);
  212. $ret['deliveryList'] = $deliveryList;
  213. util::success($ret, "success");
  214. }
  215. // 创建订单(真实下单)
  216. public function actionCreateOrder()
  217. {
  218. $form = new CreateOrderForm();
  219. $form->loadAndValidate();
  220. $post = $form->getAttributes();
  221. $orderId = $post['orderId'] ?? 0; // xhGhsOrder.id
  222. $params = $post['allParams'] ?? '';
  223. $platform = $params['en_name'] ?? '';// 平台英文名,$post['platform'] 是中文
  224. if (empty($platform)) {
  225. util::fail('请选择跑腿');
  226. }
  227. $pickupTime = $post['pickupTime'] ?? '';
  228. $params['mainId'] = $this->mainId;
  229. $params['ip'] = Yii::$app->request->userIP;
  230. $params['weight'] = $post['weight'] ?? 1;
  231. $params['remark'] = $post['remark'] ?? '';
  232. $params['total_price_fen'] = $post['price'] ?? 1;
  233. $params['pickupTime'] = $pickupTime['value'] ?? '';
  234. $ghsOrder = OrderClass::getById($orderId, true);
  235. if (empty($ghsOrder)) {
  236. util::fail('没有找到订单');
  237. }
  238. if ($ghsOrder->mainId != $this->mainId) {
  239. util::fail('不是你的订单');
  240. }
  241. if (!in_array($ghsOrder['sendStatus'], [-4, -1])) {
  242. Yii::error('订单已经发过跑腿');
  243. util::fail('订单已经发过跑腿');
  244. }
  245. //避免连续点击的重复提交 ssh
  246. $adminId = $this->adminId;
  247. util::checkRepeatCommit($adminId, 3);
  248. $ds = new DispatchService($this->mainId, $platform);
  249. $ret = $ds->createOrder($ghsOrder, 'xhGhsOrder', $this->shopId, $params);
  250. if (isset($ret['code']) && $ret['code'] == 0) {
  251. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'orderId' => $ret['data']['order_id']]);
  252. if (empty($gdo)) {
  253. $data = [
  254. 'mainId' => $this->mainId,
  255. 'shopId' => $this->shopId,
  256. 'deliveryId' => $ret['platform'],
  257. 'ghsOrderId' => $orderId,
  258. 'orderId' => $ret['data']['order_id'],
  259. 'distance' => $ret['data']['distance'],
  260. 'fee' => $ret['data']['fee'],
  261. 'orderStatus' => 0
  262. ];
  263. GhsDeliveryOrderClass::add($data);
  264. } else {
  265. Yii::info('重复创建订单');
  266. }
  267. //更新订单
  268. $ghsOrder->sendDistance = $ret['data']['distance'];
  269. $ghsOrder->sendStatus = 0;
  270. $ghsOrder->deliveryId = $ret['platform'];
  271. $ghsOrder->sendType = 2;// 2指跑腿
  272. $ghsOrder->save();
  273. //OrderClass::hasSend($ghsOrder);// 更新 status (不正确的,暂留做为对比)
  274. //发货
  275. $params = ['fhType' => 0, 'fhWl' => '', 'fhWlNo' => '', 'staffId' => 0, 'staffName' => ''];
  276. OrderClass::orderSend($ghsOrder, $params);
  277. util::success($ret, "success");
  278. } else {
  279. if (isset($ret['msg'])) {
  280. util::fail($ret['msg']);
  281. }
  282. util::fail('创建跑腿失败');
  283. }
  284. }
  285. /**
  286. * 查询订单详情
  287. *
  288. * 1. 蜂鸟平台 orderId 可以使用 "XSD_CS26322799" (即:表 xhGhsOrder.orderSn)
  289. */
  290. public function actionOrderDetail()
  291. {
  292. $form = new OrderDetailForm();
  293. $form->loadAndValidate();
  294. $post = $form->getAttributes();
  295. $platform = $post['platform'];
  296. $orderId = $post['orderId'];
  297. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : '';
  298. $ds = new DispatchService($this->mainId, $platform);
  299. $ret = $ds->selectOrder($orderId, $orderSn);
  300. $return = isset($ret['ret']) ? $ret['ret'] : $ret['code']; // 各平台兼容处理
  301. if ($return == 0) {
  302. util::success($ret, "success");
  303. }
  304. util::fail('查询失败');
  305. }
  306. // 取消订单
  307. public function actionCancelOrder()
  308. {
  309. $form = new CancelOrderForm();
  310. $form->loadAndValidate();
  311. $post = $form->getAttributes();
  312. $orderId = $post['orderId'] ?? 0; // 平台的orderId,
  313. $platform = $post['platform'] ?? '';
  314. $ghsOrderId = $post['ghsOrderId'];
  315. // 先获取配送订单,确保 $gdo 始终可用
  316. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus!=' => -1], true);
  317. if (empty($gdo)) {
  318. util::fail('未找到对应订单: ' . $ghsOrderId);
  319. }
  320. // 如果没有提供平台和订单ID,从配送订单中获取
  321. if ($platform == '' || $orderId == 0) {
  322. $orderId = $gdo->orderId;
  323. $platform = $gdo->deliveryId;
  324. }
  325. $ds = new DispatchService($this->mainId, $platform);
  326. $cancelCostCent = 0;
  327. if ($platform == 'fengniao') {
  328. //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
  329. $cancelParams = ['order_id' => $orderId, 'order_cancel_code' => $post['order_cancel_code']];
  330. $res = $ds->getAdapter()->preCancelOrder($cancelParams);
  331. if ($res['code'] != 0) {
  332. util::fail('运单状态不允许取消');
  333. }
  334. $cancelCostCent = $res['data']['actual_cancel_cost_cent']; //取消实际需金额(单位:分)
  335. }
  336. if ($platform == 'shunfeng') {
  337. //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
  338. $cancelParams = ['order_id' => $orderId, 'order_cancel_code' => $post['order_cancel_code']];
  339. $res = $ds->getAdapter()->preCancelOrder($cancelParams);
  340. if ($res['code'] != 0) {
  341. util::fail('运单状态不允许取消');
  342. }
  343. $post['order_type'] = 1; //查询订单ID类型 1、顺丰订单号 2、商家订单号
  344. }
  345. $post['order_cancel_role'] = 1; //1:商户取消, 2:用户取消
  346. $ret = $ds->cancelOrder($orderId, $post);
  347. if ($ret['code'] == 0) {
  348. // 更新跑腿订单与批发订单状态
  349. $gdo->orderStatus = -1;
  350. $gdo->cancelCost = $ret['platform'] !== 'fengniao' ? $ret['data']['deductionFee'] : $cancelCostCent; // 由于蜂鸟平台返回的扣费不一样造成
  351. if (!$gdo->save()) {
  352. Yii::error('保存配送订单失败: ' . json_encode($gdo->errors));
  353. util::fail('保存配送订单失败');
  354. }
  355. $ghsOrder = OrderClass::getById($ghsOrderId, true, 'id, sendDistance, sendStatus, deliveryId, purchaseId, status');
  356. $ghsOrder->sendDistance = 0;
  357. $ghsOrder->sendStatus = -1;
  358. // $ghsOrder->deliveryId = ''; // 为了获取上一次的配送记录,不要置空
  359. $ghsOrder->sendTip = 0;
  360. if (!$ghsOrder->save()) {
  361. Yii::error('保存批发订单失败: ' . json_encode($ghsOrder->errors));
  362. util::fail('保存批发订单失败');
  363. }
  364. OrderClass::cancelOrderSend($ghsOrder, ['staffId' => 0, 'staffName' => '']);
  365. util::success($ret['data'], "success");
  366. }
  367. util::fail('取消失败');
  368. }
  369. /**
  370. * 获取订单取消原因
  371. */
  372. public function actionCancelReason()
  373. {
  374. $post = Yii::$app->request->post();
  375. $ghsOrderId = $post['ghsOrderId'];
  376. $platform = $post['platform'];
  377. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus!=' => -1], true);
  378. if (!empty($gdo)) {
  379. $orderId = $gdo->orderId;
  380. //$platform = $gdo->deliveryId;
  381. } else {
  382. util::fail('未找到对应订单: ' . $ghsOrderId);
  383. }
  384. $ds = new DispatchService($this->mainId, $platform);
  385. $ret = $ds->getCancelReasonList($orderId);
  386. if ($ret['code'] == 0) {
  387. util::success($ret['data']);
  388. } else {
  389. Yii::error('获取订单取消原因:' . json_encode($ret));
  390. util::fail($ret['msg']);
  391. }
  392. }
  393. /**
  394. * 添加小费
  395. */
  396. public function actionAddTip()
  397. {
  398. $post = Yii::$app->request->post();
  399. $ghsOrderId = $post['ghsOrderId'];
  400. $platform = $post['platform'];
  401. $tips = intval($post['tips']);
  402. if ($tips < 0) {
  403. util::fail('小费金额至少为1元');
  404. }
  405. $tips *= 100;
  406. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus' => ['in', [0, 1, 2, 10]]], true);
  407. if ($gdo == null) {
  408. util::fail('当前配送状态无法加小费');
  409. }
  410. $ds = new DispatchService($this->mainId, $platform);
  411. $ret = $ds->addTip(['orderId' => $gdo->orderId, 'tips' => $tips]);
  412. if ($ret['code'] == 0) {
  413. $gdo->tip = $tips + $gdo->tip;
  414. $gdo->save();
  415. $orderObj = OrderClass::getById($gdo->ghsOrderId, true, 'id,sendTip');
  416. $orderObj->sendTip = $tips / 100 + $orderObj->sendTip;
  417. $orderObj->save();
  418. util::success($ret['data']);
  419. } else {
  420. Yii::error('添加小费请求失败,请求数据是:' . json_encode($ret));
  421. util::fail($ret['msg']);
  422. }
  423. }
  424. // ---------------------------------------------------- 普通回调接口 ----------------------------------------------------------
  425. // 第三方回调入口
  426. /**
  427. * 回调接口
  428. */
  429. public function actionCallback()
  430. {
  431. $callbackData = Yii::$app->request->post();
  432. if (empty($callbackData)) {
  433. $postStr = file_get_contents('php://input');
  434. $callbackData = json_decode($postStr, true);
  435. if (empty($callbackData)) {
  436. util::fail('回调请求的数据为空');
  437. }
  438. }
  439. // 从配置中获取安全token
  440. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  441. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  442. // 记录回调日志
  443. Yii::info('聚合配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'delivery');
  444. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  445. }
  446. /**
  447. * 闪送回调接口
  448. * 回调返回的格式必须是{"status":200,"msg":"","data":null}格式,当status为200表示回调成功,否则,回调失败。当回调失败时,间隔一分钟重试一次,最多重试五次。
  449. */
  450. public function actionShansongCallback()
  451. {
  452. $callbackData = Yii::$app->request->post();
  453. if (empty($callbackData)) {
  454. $postStr = file_get_contents('php://input');
  455. $callbackData = json_decode($postStr, true);
  456. }
  457. Yii::info('shansong 回调 -- post: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  458. $obj = new \common\components\delivery\platform\shansong\OrderStatusCallBack();
  459. $ret = $obj->handle($callbackData);
  460. if ($ret) {
  461. return $this->asJson(['status' => 200, 'msg' => 'OK', "data" => null]);
  462. } else {
  463. Yii::error('闪送回调失败: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  464. return $this->asJson(['status' => 200, 'msg' => '回调失败', "data" => null]);
  465. }
  466. }
  467. /**
  468. * 蜂鸟回调接口
  469. */
  470. public function actionFengniaoCallback()
  471. {
  472. $callbackData = Yii::$app->request->post();
  473. // 逆向回调接口结果的加签
  474. $param = [
  475. 'app_id' => $callbackData['app_id'],
  476. 'timestamp' => $callbackData['timestamp'],
  477. 'business_data' => $callbackData['business_data']
  478. ];
  479. $fa = new \common\components\delivery\services\adapter\FengniaoAdapter();
  480. $paramSign = $fa->generateSignature($param);
  481. if ($paramSign == $callbackData['signature']) {
  482. $businessData = isset($callbackData['business_data']) ? $callbackData['business_data'] : '';
  483. if (empty($businessData)) {
  484. $this->asJson(['return_code' => -1, 'return_msg' => 'business data is empty']);
  485. }
  486. $businessData = json_decode($businessData, true);
  487. $cbnObj = new \common\components\delivery\platform\fengniao\CallBackNotify();
  488. $ret = $cbnObj->handle($businessData['callback_business_type'], $businessData['param']);
  489. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  490. } else {
  491. Yii::error('蜂鸟回调接口签名出错');
  492. }
  493. }
  494. /**
  495. * 货拉拉回调接口
  496. */
  497. public function actionHuolalaCallback()
  498. {
  499. $post = Yii::$app->request->post();
  500. Yii::info('货拉拉回调接口post:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'delivery');
  501. $action = $post['action'] ?? '';
  502. if ($action != 'order_update') {
  503. Yii::error('当前接口只处理货拉拉订单状态变更事件');
  504. return $this->asJson(['return_code' => 0, 'msg' => '当前接口只处理货拉拉订单状态变更事件']);
  505. }
  506. $param = $post;
  507. unset($param['signature']);
  508. $huolala = new \common\components\delivery\platform\huolala\Huolala();
  509. $paramSign = $huolala->generateSignatureWithoutAppSecret($param); //注意:不用拼接secret,所有的参数都参与计算,包含空值。
  510. if ($paramSign == $post['signature']) {
  511. $cbh = new \common\components\delivery\platform\huolala\CallBackHandler();
  512. $ret = $cbh->handler($post);
  513. if ($ret) {
  514. return $this->asJson(['serial_no' => $post['serial_no']]);
  515. } else {
  516. Yii::error('货拉拉回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
  517. return $this->asJson(['return_code' => -1, 'return_msg' => 'failed']);
  518. }
  519. } else {
  520. Yii::error('蜂鸟回调接口签名出错');
  521. return $this->asJson(['return_code' => -1, 'return_msg' => 'signature error']);
  522. }
  523. }
  524. /**
  525. * 顺丰回调接口
  526. */
  527. public function actionShunfengCallback()
  528. {
  529. $post = Yii::$app->request->post();
  530. $cbh = new \common\components\delivery\platform\shunfeng\CallBackHandler();
  531. $ret = $cbh->handle($post);// 各回调处理
  532. if ($ret) {
  533. return $this->asJson(['error_code' => 0, 'error_msg' => 'success']);
  534. } else {
  535. Yii::error('顺丰回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
  536. return $this->asJson(['error_code' => -1, 'error_msg' => 'failed']);
  537. }
  538. }
  539. // ---------------------------------------------------- 授权回调接口 ----------------------------------------------------------
  540. /**
  541. * 闪送授权回调接口
  542. */
  543. public function actionShansongAuthCallback()
  544. {
  545. $code = Yii::$app->request->get('code');
  546. $state = Yii::$app->request->get('state');
  547. $shopId = Yii::$app->request->get('shopId');
  548. $isAllStoreAuth = Yii::$app->request->get('isAllStoreAuth');
  549. $thirdStoreId = Yii::$app->request->get('thirdStoreId');
  550. $storeId = Yii::$app->request->get('storeId');
  551. // 验证state参数(防止CSRF)
  552. //if ($state != $yourUserId) {
  553. //throw new \yii\web\BadRequestHttpException('Invalid state parameter');
  554. //}
  555. // 获取AccessToken
  556. $auth = new \common\components\delivery\platform\shansong\Auth();
  557. $result = $auth->getAccessToken($code);
  558. if (!$result['success']) {
  559. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  560. }
  561. // 保存授权信息到数据库
  562. $data = [
  563. 'mainId' => $state,
  564. 'shopId' => $shopId, //闪送商户ID
  565. 'accessToken' => $result['access_token'],
  566. 'refreshToken' => $result['refresh_token'],
  567. 'expiresAt' => time() + $result['expires_in'],
  568. 'authType' => $isAllStoreAuth ? 'all_store' : 'single_store',
  569. 'platform' => 'shansong'
  570. ];
  571. if (!$isAllStoreAuth) {
  572. $data['third_store_id'] = $thirdStoreId;
  573. $data['shans_store_id'] = $storeId;
  574. }
  575. DeliveryAuthTokenClass::add($data);
  576. if (false) {
  577. throw new \yii\web\HttpException(500, '保存授权信息失败');
  578. }
  579. //return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  580. $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
  581. $template = '';
  582. if (is_file($templatePath) && is_readable($templatePath)) {
  583. $template = file_get_contents($templatePath);
  584. }
  585. if ($template === false || $template === '') {
  586. throw new \yii\web\HttpException(500, '返回h5页面不存在');
  587. }
  588. $content = strtr($template, [
  589. '{{title}}' => '授权成功',
  590. '{{heading}}' => '授权成功',
  591. '{{message}}' => '您的闪送账号已成功完成授权,现在可以返回系统继续使用聚合配送服务。',
  592. ]);
  593. $response = Yii::$app->response;
  594. $response->format = Response::FORMAT_HTML;
  595. $response->content = $content;
  596. return $response;
  597. }
  598. /**
  599. * 货拉拉授权回调接口
  600. */
  601. public function actionHuolalaAuthCallback()
  602. {
  603. $get = Yii::$app->request->get();
  604. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  605. Yii::info($getData);
  606. $code = $get['code'];
  607. $mainId = $get['mainId'];
  608. // 获取AccessToken
  609. $auth = new \common\components\delivery\platform\huolala\Auth();
  610. $result = $auth->getAccessToken($code);
  611. if (!$result['success']) {
  612. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  613. }
  614. // 保存授权信息到数据库
  615. $data = [
  616. 'mainId' => $mainId,
  617. 'shopId' => '',
  618. 'accessToken' => $result['access_token'],
  619. 'refreshToken' => $result['refresh_token'],
  620. 'expiresAt' => strtotime($result['auth_end_time']),
  621. 'authType' => 'all_store',
  622. 'platform' => 'huolala'
  623. ];
  624. DeliveryAuthTokenClass::add($data);
  625. $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
  626. $template = '';
  627. if (is_file($templatePath) && is_readable($templatePath)) {
  628. $template = file_get_contents($templatePath);
  629. }
  630. if ($template === false || $template === '') {
  631. $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>';
  632. }
  633. $content = strtr($template, [
  634. '{{title}}' => '授权成功',
  635. '{{heading}}' => '授权成功',
  636. '{{message}}' => '您的货拉拉账号已成功完成授权,现在可以返回系统继续使用聚合配送服务。',
  637. ]);
  638. $response = Yii::$app->response;
  639. $response->format = Response::FORMAT_HTML;
  640. $response->content = $content;
  641. return $response;
  642. }
  643. /**
  644. * 蜂鸟授权回调接口
  645. */
  646. public function actionFengniaoAuthCallback()
  647. {
  648. $callbackData = Yii::$app->request->post();
  649. if (empty($callbackData)) {
  650. Yii::error('回调请求的数据为空');
  651. }
  652. Yii::info('蜂鸟授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
  653. $get = Yii::$app->request->get();
  654. if (!isset($get['main_id'])) {
  655. Yii::error('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id');
  656. noticeUtil::push('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id,回调数据:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
  657. return;
  658. }
  659. $mainId = $get['main_id'];
  660. $code = $callbackData['code'];
  661. $merchantId = $callbackData['merchant_id'];
  662. $scope = $callbackData['scope'];
  663. $state = $callbackData['state'];
  664. // 获取AccessToken
  665. $auth = new \common\components\delivery\platform\fengniao\Auth();
  666. $result = $auth->getAccessToken($code, $merchantId);
  667. if (!$result['success']) {
  668. noticeUtil::push("mainId=" . $mainId . ' 授权时,获取token失败,请让其重新发起授权');
  669. Yii::error(json_encode($result));
  670. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  671. }
  672. $result = $result['data'];
  673. $exist = DeliveryAuthTokenClass::exists(['mainId' => $mainId, 'platform' => 'fengniao']);
  674. if ($exist) {
  675. noticeUtil::push("mainId=" . $mainId . ' 已成功授权了。如果蜂鸟不能正确使用,请查询数据库进行检查。');
  676. } else {
  677. // 保存授权信息到数据库
  678. $data = [
  679. 'mainId' => $mainId,
  680. 'merchantId' => $merchantId,
  681. 'shopId' => '',
  682. 'accessToken' => $result['access_token'],
  683. 'refreshToken' => $result['refresh_token'],
  684. 'expiresAt' => $result['expire_in'] + time(),
  685. 'authType' => 'all_store', //即 scope='all'
  686. 'platform' => 'fengniao'
  687. ];
  688. DeliveryAuthTokenClass::add($data);
  689. }
  690. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  691. }
  692. /**
  693. * 达达授权回调接口
  694. */
  695. public function actionDadaAuthCallback()
  696. {
  697. $get = Yii::$app->request->get();
  698. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  699. Yii::info($getData);
  700. // {"sourceId":"1003654","ticket":"b8b4e56a86934b73a512ea9994e7774e","state":"huidiao_biaoshi","shopNo":"1003654-88547413"}
  701. // 用merchanId 来保存 sourceId
  702. if ($getData['state'] != 'huidiao_biaoshi') {
  703. Yii::error('达达授权回调 state 参数不对');
  704. return;
  705. }
  706. if (!isset($getData['mainId'])) {
  707. Yii::error('达达授权回调缺少必要参数 mainId');
  708. return;
  709. }
  710. try {
  711. // 保存授权信息到数据库
  712. $data = [
  713. 'mainId' => $getData['mainId'],
  714. 'merchantId' => $getData['sourceId'], // 用merchanId 来保存 sourceId
  715. 'shopId' => $getData['shopNo'],
  716. 'accessToken' => '',
  717. 'refreshToken' => '',
  718. 'expiresAt' => 9997773456,
  719. 'authType' => 'all_store', //即 scope='all'
  720. 'platform' => 'dada'
  721. ];
  722. DeliveryAuthTokenClass::add($data);
  723. Yii::info('达达授权回调保存成功', 'dada');
  724. } catch (\Exception $e) {
  725. Yii::error('达达授权回调保存失败' . $e->getMessage(), 'dada');
  726. }
  727. }
  728. /**
  729. * 达达回调接口
  730. */
  731. public function actionDadaCallback()
  732. {
  733. $post = Yii::$app->request->post();
  734. Yii::info('达达回调:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'dada');
  735. return $this->asJson(['status' => 'ok']);
  736. }
  737. /**
  738. * 顺丰授权与取消授权回调接口
  739. */
  740. public function actionShunfengAuthCallback()
  741. {
  742. $get = Yii::$app->request->get();
  743. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  744. Yii::info($getData);
  745. $callbackData = Yii::$app->request->post();
  746. if (empty($callbackData)) {
  747. $postStr = file_get_contents('php://input');
  748. $callbackData = json_decode($postStr, true);
  749. if (empty($callbackData)) {
  750. Yii::info('回调请求的数据为空');
  751. }
  752. }
  753. Yii::info('顺丰授权与取消授权回调接口:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'dada');
  754. }
  755. }