DeliveryController.php 30 KB

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