DeliveryController.php 29 KB

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