DeliveryController.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. <?php
  2. namespace ghs\controllers;
  3. use Yii;
  4. use biz\shop\classes\ShopClass;
  5. use bizGhs\express\classes\GhsDeliveryOrderClass;
  6. use bizGhs\express\classes\DeliveryAuthTokenClass;
  7. use bizGhs\order\classes\OrderClass;
  8. use common\components\delivery\services\adapter\HuolalaAdapter;
  9. use common\components\noticeUtil;
  10. use common\components\util;
  11. use common\components\delivery\services\DispatchService;
  12. use ghs\models\delivery\CancelOrderForm;
  13. use ghs\models\delivery\CreateOrderForm;
  14. use ghs\models\delivery\OrderDetailForm;
  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. 'dada' => ['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, $this->shopId);
  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['weight'] = $post['weight'];
  214. $params['remark'] = $post['remark'];
  215. $params['total_price_fen'] = $post['price'];
  216. $params['pickupTime'] = $pickupTime['value'];
  217. $ghsOrder = OrderClass::getById($orderId, true);
  218. if(!in_array($ghsOrder['sendStatus'], [-4, -1])) {
  219. Yii::error('订单已经发过跑腿');
  220. util::fail('订单已经发过跑腿');
  221. }
  222. $ds = new DispatchService($this->mainId, $platform);
  223. $ret = $ds->createOrder($ghsOrder, 'xhGhsOrder', $this->shopId, $params);
  224. if (isset($ret['code']) && $ret['code'] == 0) {
  225. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId'=>$this->mainId, 'orderId'=>$ret['data']['order_id']]);
  226. if (empty($gdo)) {
  227. $data = [
  228. 'mainId' => $this->mainId,
  229. 'shopId' => $this->shopId,
  230. 'deliveryId' => $ret['platform'],
  231. 'ghsOrderId' => $orderId,
  232. 'orderId' => $ret['data']['order_id'],
  233. 'distance' => $ret['data']['distance'],
  234. 'fee' => $ret['data']['fee'],
  235. 'orderStatus' => 0
  236. ];
  237. GhsDeliveryOrderClass::add($data);
  238. } else {
  239. Yii::info('重复创建订单');
  240. }
  241. //更新订单
  242. $ghsOrder->sendDistance = $ret['data']['distance'];
  243. $ghsOrder->sendStatus = 0;
  244. $ghsOrder->deliveryId = $ret['platform'];
  245. $ghsOrder->sendType = 2;// 2指跑腿
  246. $ghsOrder->save();
  247. OrderClass::hasSend($ghsOrder);// 更新 status
  248. util::success($ret, "success");
  249. } else {
  250. if(isset($ret['msg'])){
  251. util::fail($ret['msg']);
  252. }
  253. util::fail('创建跑腿失败');
  254. }
  255. }
  256. /**
  257. * 查询订单详情
  258. *
  259. * 1. 蜂鸟平台 orderId 可以使用 "XSD_CS26322799" (即:表 xhGhsOrder.orderSn)
  260. */
  261. public function actionOrderDetail()
  262. {
  263. $form = new OrderDetailForm();
  264. $form->loadAndValidate();
  265. $post = $form->getAttributes();
  266. $platform = $post['platform'];
  267. $orderId = $post['orderId'];
  268. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : '';
  269. $ds = new DispatchService($this->mainId, $platform);
  270. $ret = $ds->selectOrder($orderId, $orderSn);
  271. $return = isset($ret['ret']) ? $ret['ret'] : $ret['code']; // 各平台兼容处理
  272. if($return == 0) {
  273. util::success($ret, "success");
  274. }
  275. util::fail('查询失败');
  276. }
  277. // 取消订单
  278. public function actionCancelOrder()
  279. {
  280. $form = new CancelOrderForm();
  281. $form->loadAndValidate();
  282. $post = $form->getAttributes();
  283. $orderId = $post['orderId'] ?? 0; // 平台的orderId,
  284. $platform = $post['platform'] ?? '';
  285. $ghsOrderId = $post['ghsOrderId'];
  286. // 先获取配送订单,确保 $gdo 始终可用
  287. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId'=>$this->mainId, 'ghsOrderId'=>$ghsOrderId, 'orderStatus!='=> -1], true);
  288. if(empty($gdo)) {
  289. util::fail('未找到对应订单: ' . $ghsOrderId);
  290. }
  291. // 如果没有提供平台和订单ID,从配送订单中获取
  292. if($platform == '' || $orderId == 0) {
  293. $orderId = $gdo->orderId;
  294. $platform = $gdo->deliveryId;
  295. }
  296. $ds = new DispatchService($this->mainId, $platform);
  297. $cancelCostCent = 0;
  298. if($platform == 'fengniao') {
  299. //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
  300. $cancelParams = ['order_id'=>$orderId, 'order_cancel_code'=>$post['order_cancel_code']];
  301. $res = $ds->getAdapter()->preCancelOrder($cancelParams);
  302. if($res['code'] != 0){
  303. util::fail('运单状态不允许取消');
  304. }
  305. $cancelCostCent = $res['data']['actual_cancel_cost_cent']; //取消实际需金额(单位:分)
  306. }
  307. if($platform == 'shunfeng') {
  308. //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
  309. $cancelParams = ['order_id'=>$orderId, 'order_cancel_code'=>$post['order_cancel_code']];
  310. $res = $ds->getAdapter()->preCancelOrder($cancelParams);
  311. if($res['code'] != 0){
  312. util::fail('运单状态不允许取消');
  313. }
  314. $post['order_type'] = 1; //查询订单ID类型 1、顺丰订单号 2、商家订单号
  315. }
  316. $post['order_cancel_role'] = 1; //1:商户取消, 2:用户取消
  317. $ret = $ds->cancelOrder($orderId, $post);
  318. if($ret['code'] == 0) {
  319. // 更新跑腿订单与批发订单状态
  320. $gdo->orderStatus = -1;
  321. $gdo->cancelCost = $ret['platform'] !== 'fengniao' ? $ret['data']['deductionFee'] : $cancelCostCent; // 由于蜂鸟平台返回的扣费不一样造成
  322. if(!$gdo->save()) {
  323. Yii::error('保存配送订单失败: ' . json_encode($gdo->errors));
  324. util::fail('保存配送订单失败');
  325. }
  326. $ghsOrder = OrderClass::getById($ghsOrderId, true, 'id, sendDistance, sendStatus, deliveryId, purchaseId, status');
  327. $ghsOrder->sendDistance = 0;
  328. $ghsOrder->sendStatus = -1;
  329. // $ghsOrder->deliveryId = ''; // 为了获取上一次的配送记录,不要置空
  330. $ghsOrder->sendTip = 0;
  331. if(!$ghsOrder->save()) {
  332. Yii::error('保存批发订单失败: ' . json_encode($ghsOrder->errors));
  333. util::fail('保存批发订单失败');
  334. }
  335. OrderClass::cancelOrderSend($ghsOrder, ['staffId'=>0, 'staffName'=>'']);
  336. util::success($ret['data'], "success");
  337. }
  338. util::fail('取消失败');
  339. }
  340. /**
  341. * 获取订单取消原因
  342. */
  343. public function actionCancelReason()
  344. {
  345. $post = Yii::$app->request->post();
  346. $ghsOrderId = $post['ghsOrderId'];
  347. $platform = $post['platform'];
  348. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId'=>$this->mainId, 'ghsOrderId'=>$ghsOrderId, 'orderStatus!='=>-1], true);
  349. if(!empty($gdo)) {
  350. $orderId = $gdo->orderId;
  351. //$platform = $gdo->deliveryId;
  352. } else {
  353. util::fail('未找到对应订单: ' . $ghsOrderId);
  354. }
  355. $ds = new DispatchService($this->mainId, $platform);
  356. $ret = $ds->getCancelReasonList($orderId);
  357. if($ret['code'] == 0){
  358. util::success($ret['data']);
  359. }else{
  360. Yii::error('获取订单取消原因:'.json_encode($ret));
  361. util::fail($ret['msg']);
  362. }
  363. }
  364. /**
  365. * 添加小费
  366. */
  367. public function actionAddTip()
  368. {
  369. $post = Yii::$app->request->post();
  370. $ghsOrderId = $post['ghsOrderId'];
  371. $platform = $post['platform'];
  372. $tips = intval($post['tips']);
  373. if($tips < 0) {
  374. util::fail('小费金额至少为1元');
  375. }
  376. $tips *= 100;
  377. $gdo = GhsDeliveryOrderClass::getByCondition(['mainId'=>$this->mainId, 'ghsOrderId'=>$ghsOrderId, 'orderStatus'=>['in',[0,1,2,10]]], true);
  378. if($gdo == null){
  379. util::fail('当前配送状态无法加小费');
  380. }
  381. $ds = new DispatchService($this->mainId, $platform);
  382. $ret = $ds->addTip(['orderId'=>$gdo->orderId, 'tips'=>$tips]);
  383. if($ret['code'] == 0){
  384. $gdo->tip = $tips + $gdo->tip;
  385. $gdo->save();
  386. $orderObj = OrderClass::getById($gdo->ghsOrderId, true, 'id,sendTip');
  387. $orderObj->sendTip = $tips/100 + $orderObj->sendTip;
  388. $orderObj->save();
  389. util::success($ret['data']);
  390. }else{
  391. Yii::error('添加小费请求失败,请求数据是:'.json_encode($ret));
  392. util::fail($ret['msg']);
  393. }
  394. }
  395. // ---------------------------------------------------- 普通回调接口 ----------------------------------------------------------
  396. // 第三方回调入口
  397. /**
  398. * 回调接口
  399. */
  400. public function actionCallback()
  401. {
  402. $callbackData = Yii::$app->request->post();
  403. if (empty($callbackData)) {
  404. $postStr = file_get_contents('php://input');
  405. $callbackData = json_decode($postStr, true);
  406. if (empty($callbackData)) {
  407. util::fail('回调请求的数据为空');
  408. }
  409. }
  410. // 从配置中获取安全token
  411. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  412. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  413. // 记录回调日志
  414. Yii::info('聚合配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'delivery');
  415. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  416. }
  417. /**
  418. * 闪送回调接口
  419. * 回调返回的格式必须是{"status":200,"msg":"","data":null}格式,当status为200表示回调成功,否则,回调失败。当回调失败时,间隔一分钟重试一次,最多重试五次。
  420. */
  421. public function actionShansongCallback()
  422. {
  423. $callbackData = Yii::$app->request->post();
  424. if (empty($callbackData)) {
  425. $postStr = file_get_contents('php://input');
  426. $callbackData = json_decode($postStr, true);
  427. }
  428. Yii::info('shansong 回调 -- post: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  429. $obj = new \common\components\delivery\platform\shansong\OrderStatusCallBack();
  430. $ret = $obj->handle($callbackData);
  431. if($ret) {
  432. return $this->asJson(['status' => 200, 'msg' => 'OK', "data"=> null]);
  433. } else {
  434. Yii::error('闪送回调失败: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  435. return $this->asJson(['status' => 200, 'msg' => '回调失败', "data"=> null]);
  436. }
  437. }
  438. /**
  439. * 蜂鸟回调接口
  440. */
  441. public function actionFengniaoCallback()
  442. {
  443. $callbackData = Yii::$app->request->post();
  444. // 逆向回调接口结果的加签
  445. $param = [
  446. 'app_id' => $callbackData['app_id'],
  447. 'timestamp' => $callbackData['timestamp'],
  448. 'business_data' => $callbackData['business_data']
  449. ];
  450. $fa = new \common\components\delivery\services\adapter\FengniaoAdapter();
  451. $paramSign = $fa->generateSignature($param);
  452. if($paramSign == $callbackData['signature']){
  453. $businessData = isset($callbackData['business_data']) ? $callbackData['business_data'] : '';
  454. if(empty($businessData)){
  455. $this->asJson(['return_code' => -1, 'return_msg' => 'business data is empty']);
  456. }
  457. $businessData = json_decode($businessData, true);
  458. $cbnObj = new \common\components\delivery\platform\fengniao\CallBackNotify();
  459. $ret = $cbnObj->handle($businessData['callback_business_type'], $businessData['param']);
  460. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  461. }else{
  462. Yii::error('蜂鸟回调接口签名出错');
  463. }
  464. }
  465. /**
  466. * 货拉拉回调接口
  467. */
  468. public function actionHuolalaCallback()
  469. {
  470. $post = Yii::$app->request->post();
  471. Yii::info('货拉拉回调接口post:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'delivery');
  472. $action = $post['action'] ?? '';
  473. if($action != 'order_update') {
  474. Yii::error('当前接口只处理货拉拉订单状态变更事件');
  475. return $this->asJson(['return_code' => 0, 'msg' => '当前接口只处理货拉拉订单状态变更事件']);
  476. }
  477. $param = $post;
  478. unset($param['signature']);
  479. $huolala = new \common\components\delivery\platform\huolala\Huolala();
  480. $paramSign = $huolala->generateSignatureWithoutAppSecret($param); //注意:不用拼接secret,所有的参数都参与计算,包含空值。
  481. if($paramSign == $post['signature']){
  482. $cbh = new \common\components\delivery\platform\huolala\CallBackHandler();
  483. $ret = $cbh->handler($post);
  484. if($ret) {
  485. return $this->asJson(['serial_no' => $post['serial_no']]);
  486. } else {
  487. Yii::error('货拉拉回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
  488. return $this->asJson(['return_code' => -1, 'return_msg' => 'failed']);
  489. }
  490. }else{
  491. Yii::error('蜂鸟回调接口签名出错');
  492. return $this->asJson(['return_code' => -1, 'return_msg' => 'signature error']);
  493. }
  494. }
  495. /**
  496. * 顺丰回调接口
  497. */
  498. public function actionShunfengCallback()
  499. {
  500. $post = Yii::$app->request->post();
  501. $cbh = new \common\components\delivery\platform\shunfeng\CallBackHandler();
  502. $ret = $cbh->handle($post);// 各回调处理
  503. if($ret) {
  504. return $this->asJson(['error_code' => 0, 'error_msg' => 'success']);
  505. } else {
  506. Yii::error('顺丰回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
  507. return $this->asJson(['error_code' => -1, 'error_msg' => 'failed']);
  508. }
  509. }
  510. // ---------------------------------------------------- 授权回调接口 ----------------------------------------------------------
  511. /**
  512. * 闪送授权回调接口
  513. */
  514. public function actionShansongAuthCallback()
  515. {
  516. $code = Yii::$app->request->get('code');
  517. $state = Yii::$app->request->get('state');
  518. $shopId = Yii::$app->request->get('shopId');
  519. $isAllStoreAuth = Yii::$app->request->get('isAllStoreAuth');
  520. $thirdStoreId = Yii::$app->request->get('thirdStoreId');
  521. $storeId = Yii::$app->request->get('storeId');
  522. // 验证state参数(防止CSRF)
  523. //if ($state != $yourUserId) {
  524. //throw new \yii\web\BadRequestHttpException('Invalid state parameter');
  525. //}
  526. // 获取AccessToken
  527. $auth = new \common\components\delivery\platform\shansong\Auth();
  528. $result = $auth->getAccessToken($code);
  529. if (!$result['success']) {
  530. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  531. }
  532. // 保存授权信息到数据库
  533. $data = [
  534. 'mainId' => $state,
  535. 'shopId' => $shopId, //闪送商户ID
  536. 'accessToken' => $result['access_token'],
  537. 'refreshToken' => $result['refresh_token'],
  538. 'expiresAt' => time() + $result['expires_in'],
  539. 'authType' => $isAllStoreAuth ? 'all_store' : 'single_store',
  540. 'platform' => 'shansong'
  541. ];
  542. if (!$isAllStoreAuth) {
  543. $data['third_store_id'] = $thirdStoreId;
  544. $data['shans_store_id'] = $storeId;
  545. }
  546. DeliveryAuthTokenClass::add($data);
  547. if (false) {
  548. throw new \yii\web\HttpException(500, '保存授权信息失败');
  549. }
  550. //return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  551. $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
  552. $template = '';
  553. if (is_file($templatePath) && is_readable($templatePath)) {
  554. $template = file_get_contents($templatePath);
  555. }
  556. if ($template === false || $template === '') {
  557. throw new \yii\web\HttpException(500, '返回h5页面不存在');
  558. }
  559. $content = strtr($template, [
  560. '{{title}}' => '授权成功',
  561. '{{heading}}' => '授权成功',
  562. '{{message}}' => '您的闪送账号已成功完成授权,现在可以返回系统继续使用聚合配送服务。',
  563. ]);
  564. $response = Yii::$app->response;
  565. $response->format = Response::FORMAT_HTML;
  566. $response->content = $content;
  567. return $response;
  568. }
  569. /**
  570. * 货拉拉授权回调接口
  571. */
  572. public function actionHuolalaAuthCallback()
  573. {
  574. $get = Yii::$app->request->get();
  575. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  576. Yii::info($getData);
  577. $code = $get['code'];
  578. $mainId = $get['mainId'];
  579. // 获取AccessToken
  580. $auth = new \common\components\delivery\platform\huolala\Auth();
  581. $result = $auth->getAccessToken($code);
  582. if (!$result['success']) {
  583. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  584. }
  585. // 保存授权信息到数据库
  586. $data = [
  587. 'mainId' => $mainId,
  588. 'shopId' => '',
  589. 'accessToken' => $result['access_token'],
  590. 'refreshToken' => $result['refresh_token'],
  591. 'expiresAt' => strtotime($result['auth_end_time']),
  592. 'authType' => 'all_store',
  593. 'platform' => 'huolala'
  594. ];
  595. DeliveryAuthTokenClass::add($data);
  596. $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
  597. $template = '';
  598. if (is_file($templatePath) && is_readable($templatePath)) {
  599. $template = file_get_contents($templatePath);
  600. }
  601. if ($template === false || $template === '') {
  602. $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>';
  603. }
  604. $content = strtr($template, [
  605. '{{title}}' => '授权成功',
  606. '{{heading}}' => '授权成功',
  607. '{{message}}' => '您的货拉拉账号已成功完成授权,现在可以返回系统继续使用聚合配送服务。',
  608. ]);
  609. $response = Yii::$app->response;
  610. $response->format = Response::FORMAT_HTML;
  611. $response->content = $content;
  612. return $response;
  613. }
  614. /**
  615. * 蜂鸟授权回调接口
  616. */
  617. public function actionFengniaoAuthCallback()
  618. {
  619. $callbackData = Yii::$app->request->post();
  620. if (empty($callbackData)) {
  621. Yii::error('回调请求的数据为空');
  622. }
  623. Yii::info('蜂鸟授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
  624. $get = Yii::$app->request->get();
  625. if(!isset($get['main_id'])){
  626. Yii::error('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id');
  627. noticeUtil::push('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id,回调数据:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
  628. return;
  629. }
  630. $mainId = $get['main_id'];
  631. $code = $callbackData['code'];
  632. $merchantId = $callbackData['merchant_id'];
  633. $scope = $callbackData['scope'];
  634. $state = $callbackData['state'];
  635. // 获取AccessToken
  636. $auth = new \common\components\delivery\platform\fengniao\Auth();
  637. $result = $auth->getAccessToken($code, $merchantId);
  638. if (!$result['success']) {
  639. noticeUtil::push("mainId=" . $mainId . ' 授权时,获取token失败,请让其重新发起授权');
  640. Yii::error(json_encode($result));
  641. throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
  642. }
  643. $result = $result['data'];
  644. $exist = DeliveryAuthTokenClass::exists(['mainId' => $mainId, 'platform' => 'fengniao']);
  645. if($exist){
  646. noticeUtil::push("mainId=" . $mainId . ' 已成功授权了。如果蜂鸟不能正确使用,请查询数据库进行检查。');
  647. }else{
  648. // 保存授权信息到数据库
  649. $data = [
  650. 'mainId' => $mainId,
  651. 'merchantId' => $merchantId,
  652. 'shopId' => '',
  653. 'accessToken' => $result['access_token'],
  654. 'refreshToken' => $result['refresh_token'],
  655. 'expiresAt' => $result['expire_in'] + time(),
  656. 'authType' => 'all_store', //即 scope='all'
  657. 'platform' => 'fengniao'
  658. ];
  659. DeliveryAuthTokenClass::add($data);
  660. }
  661. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  662. }
  663. /**
  664. * 达达授权回调接口
  665. */
  666. public function actionDadaAuthCallback()
  667. {
  668. $get = Yii::$app->request->get();
  669. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  670. Yii::info($getData);
  671. // // 用merchanId 来保存 sourceId
  672. $callbackData = Yii::$app->request->post();
  673. if (empty($callbackData)) {
  674. $postStr = file_get_contents('php://input');
  675. $callbackData = json_decode($postStr, true);
  676. if (empty($callbackData)) {
  677. Yii::info('回调请求的数据为空');
  678. }
  679. }
  680. Yii::info('达达授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'dada');
  681. }
  682. /**
  683. * 达达回调接口
  684. */
  685. public function actionDadaCallback()
  686. {
  687. $post = Yii::$app->request->post();
  688. Yii::info('达达回调:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'dada');
  689. return $this->asJson(['status' => 'ok']);
  690. }
  691. /**
  692. * 顺丰授权与取消授权回调接口
  693. */
  694. public function actionShunfengAuthCallback()
  695. {
  696. $get = Yii::$app->request->get();
  697. $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
  698. Yii::info($getData);
  699. $callbackData = Yii::$app->request->post();
  700. if (empty($callbackData)) {
  701. $postStr = file_get_contents('php://input');
  702. $callbackData = json_decode($postStr, true);
  703. if (empty($callbackData)) {
  704. Yii::info('回调请求的数据为空');
  705. }
  706. }
  707. Yii::info('顺丰授权与取消授权回调接口:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'dada');
  708. }
  709. }