DeliveryController.php 32 KB

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