DeliveryController.php 31 KB

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