DeliveryController.php 32 KB

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