DeliveryController.php 30 KB

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