DeliveryController.php 32 KB

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