DeliveryController.php 32 KB

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