DeliveryController.php 35 KB

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