DeliveryController.php 35 KB

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