DeliveryController.php 35 KB

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