DeliveryController.php 36 KB

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