IntraCityController.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. <?php
  2. namespace ghs\controllers;
  3. use biz\wx\classes\WxMessageClass;
  4. use biz\wx\classes\WxOpenClass;
  5. use bizGhs\admin\classes\AdminClass;
  6. use bizGhs\express\classes\GhsExpressOrderClass;
  7. use bizHd\order\classes\OrderGoodsClass;
  8. use bizGhs\order\classes\OrderItemClass;
  9. use bizHd\saas\classes\StaffClass;
  10. use common\components\dict;
  11. use common\components\imgUtil;
  12. use common\components\orderSn;
  13. use hd\models\IntraCity\StoreFeeForm;
  14. // 以上类来自零售端
  15. use bizGhs\order\classes\OrderClass;
  16. use biz\shop\classes\MainClass;
  17. use biz\shop\classes\ShopClass;
  18. use common\components\noticeUtil;
  19. use common\components\util;
  20. use common\components\IntraCityExpress;
  21. use yii\helpers\Json;
  22. use yii\db\Query;
  23. use Yii;
  24. /**
  25. * 同城配送控制器
  26. * 提供同城配送相关的API接口
  27. */
  28. class IntraCityController extends BaseController
  29. {
  30. public $guestAccess = ['callback'];
  31. /**
  32. * 创建门店
  33. * POST /intra-city/create-store
  34. */
  35. public function actionCreateStore()
  36. {
  37. try {
  38. $shop = $this->shop;
  39. $shopName = $shop->shopName ?? '';
  40. $sjName = $shop->merchantName ?? '';
  41. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  42. $storeData = [
  43. 'out_store_id' => $this->mainId, //自定义门店编号
  44. 'store_name' => $name,
  45. 'address_info' => [
  46. 'province' => $shop->province,
  47. 'city' => $shop->city,
  48. 'area' => $shop->dist,
  49. 'street' => '',
  50. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  51. 'lat' => $shop->lat,
  52. 'lng' => $shop->long,
  53. 'phone' => $shop->telephone
  54. ]
  55. ];
  56. // 验证必填参数
  57. $requiredFields = ['out_store_id', 'store_name', 'address_info'];
  58. foreach ($requiredFields as $field) {
  59. if (empty($storeData[$field])) {
  60. util::fail("缺少必填参数:{$field}");
  61. }
  62. }
  63. // 创建门店前,检查是否已经 开通门店权限 (有wxStoreId,即说明开通了)
  64. $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  65. // 查询是否存在 wx_store_id,不存在则执行apply
  66. if ($main->wxStoreId == '') {
  67. $re = IntraCityExpress::applyStore();
  68. if (!is_array($re)) {
  69. $re = Json::decode($re, true);
  70. }
  71. if ($re['errcode'] != 0) {
  72. Yii::error("开通门店权限失败:" . $re['errmsg']);
  73. util::fail('开通门店权限失败');
  74. }
  75. }
  76. $result = IntraCityExpress::createStore($storeData);
  77. if ($result['errcode'] === 0) {
  78. // 保存微信门店编号(wx_store_id)
  79. $main->wxStoreId = $result['wx_store_id'];
  80. $main->save();
  81. util::success($result, "门店创建成功");
  82. } else {
  83. Yii::error("门店创建失败:" . $result['errmsg']);
  84. util::fail($result['errmsg']);
  85. }
  86. } catch (\Exception $e) {
  87. Yii::error("门店创建失败:" . $e->getMessage());
  88. util::fail("系统出错");
  89. }
  90. }
  91. /**
  92. * 查询门店创建情况
  93. */
  94. public function actionStore()
  95. {
  96. $shopId = $this->shopId;
  97. // 首先从门店扩展表查询是否已经创建
  98. $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  99. if ($main->wxStoreId == '') { // 不存在,则从微信接口查询
  100. $result = IntraCityExpress::getStore($this->mainId);
  101. if ($result['errcode'] === 0) {
  102. $store = $result['store_list'][0];
  103. // 保存 wx_store_id
  104. $main->wxStoreId = $store['wx_store_id'];
  105. $main->save();
  106. util::success($store, "门店查询成功");
  107. } else {
  108. Yii::error("门店查询失败:" . $result['errmsg']);
  109. util::error(-1, '门店查询失败');
  110. }
  111. } else {
  112. $field = 'province, city, dist, lat, long, floor, address';
  113. $shop = ShopClass::getById($shopId, false, $field);
  114. $data = array_merge($shop, $main->toArray());
  115. util::success($data, "门店查询成功");
  116. }
  117. }
  118. /**
  119. * 更新门店
  120. */
  121. public function actionUpdateStore()
  122. {
  123. // 首先从门店扩展表查询是否已经创建
  124. $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  125. if ($main['wxStoreId'] == '') {
  126. util::fail('未创建门店,请先创建');
  127. }
  128. $shop = $this->shop;
  129. $shopName = $shop->shopName ?? '';
  130. $sjName = $shop->merchantName ?? '';
  131. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  132. $storeData = [
  133. 'keys' => ['wx_store_id' => $main['wxStoreId']],
  134. 'content' => [
  135. 'store_name' => $name,
  136. 'address_info' => [
  137. 'province' => $shop->province,
  138. 'city' => $shop->city,
  139. 'area' => $shop->dist,
  140. 'street' => '',
  141. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  142. 'lat' => $shop->lat,
  143. 'lng' => $shop->long,
  144. 'phone' => $shop->telephone
  145. ],
  146. //"order_pattern" => 2,
  147. //"service_trans_prefer" => "SFTC" //order_pattern = 2时必填
  148. ]
  149. ];
  150. $result = IntraCityExpress::updateStore($storeData);
  151. if ($result['errcode'] === 0) {
  152. util::success($result, "门店更新成功");
  153. } else {
  154. Yii::error("门店更新失败:" . $result['errmsg']);
  155. util::fail($result['errmsg']);
  156. }
  157. }
  158. /**
  159. * 门店运费充值
  160. */
  161. public function actionStoreCharge()
  162. {
  163. $post = Yii::$app->request->post();
  164. $amount = floatval($post['amount']);
  165. $amountTurnFen = $amount * 100;
  166. if ($amountTurnFen < 5000) {
  167. util::fail('50元起充');
  168. }
  169. $expressId = $post['expressId'];
  170. $serviceTransIds = ['SFTC', 'DADA'];
  171. if (!in_array($expressId, $serviceTransIds)) {
  172. util::fail('快递动力ID出错');
  173. }
  174. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  175. if ($shopExt['wxStoreId'] == '') {
  176. util::fail('微信门店编号为空');
  177. }
  178. $wxStoreId = $shopExt['wxStoreId'];
  179. $result = IntraCityExpress::storeCharge($wxStoreId, $expressId, $amountTurnFen);
  180. if ($result['errcode'] === 0) {
  181. util::success($result, "门店余额充值单已生成");
  182. } else {
  183. Yii::error("门店余额充值失败:" . $result['errmsg']);
  184. util::fail('门店余额充值失败');
  185. }
  186. }
  187. /**
  188. * 门店余额查询
  189. */
  190. public function actionStoreBalance()
  191. {
  192. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  193. if ($shopExt['wxStoreId'] == '') {
  194. util::error(-1, '微信门店编号为空');
  195. }
  196. $wxStoreId = $shopExt['wxStoreId'];
  197. $result = IntraCityExpress::getBalance($wxStoreId);
  198. if ($result['errcode'] === 0) {
  199. $data = ['all_balance' => $result['all_balance'] / 100.0];
  200. foreach ($result['balance_detail'] as $item) {
  201. if ($item['service_trans_id'] == 'DADA') {
  202. $data['dada_balance'] = $item['balance'] / 100.0;
  203. }
  204. if ($item['service_trans_id'] == 'SFTC') {
  205. $data['sf_balance'] = $item['balance'] / 100.0;
  206. }
  207. }
  208. util::success($data, "门店余额查询成功");
  209. } else {
  210. Yii::error("门店余额查询失败:" . $result['errmsg']);
  211. util::fail('门店余额查询失败');
  212. }
  213. }
  214. /**
  215. * 查询运费
  216. */
  217. public function actionStoreFee()
  218. {
  219. $post = Yii::$app->request->post();
  220. // 创建表单验证模型
  221. $form = new StoreFeeForm();
  222. $form->setScenario('store_fee');
  223. $form->load($post, ''); // 直接从 post 数据加载,不使用模型名作为前缀
  224. // 执行表单验证
  225. $form->validateForm();
  226. $orderId = $post['orderId'];
  227. $order = OrderClass::getById($orderId);
  228. if (empty($order)) {
  229. util::fail('订单出错');
  230. }
  231. if ($order['mainId'] != $this->mainId) {
  232. util::fail('订单出错');
  233. }
  234. $sn = $order['orderSn'];
  235. $shopId = intval($this->shopId);
  236. if (empty($shopId)) {
  237. util::fail("门店不存在");
  238. }
  239. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  240. if (empty($shopExt)) {
  241. util::fail("微信门店不存在");
  242. }
  243. $itemInfoList = OrderItemClass::getAllByCondition(['orderSn' => $sn], null, 'id, name, cover, num');
  244. $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
  245. if (empty($itemInfoList)) {
  246. $orderType = 1;
  247. }
  248. $cargoName = '花材'; // 商品名称,默认是花材
  249. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  250. if (count($goodsInfoList) == 1) {
  251. $goodsInfo = $goodsInfoList[0];
  252. $cargoName = $goodsInfo['name'];
  253. } else {
  254. if ($orderType != 2) {
  255. util::fail("订单商品数量不正确");
  256. }
  257. }
  258. $cargo = [
  259. 'cargo_name' => $cargoName, // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  260. 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克
  261. 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
  262. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  263. 'cargo_num' => intval($post['packageNum'])
  264. ];
  265. $originalLng = doubleval($post['user_lng']);
  266. $originalLat = doubleval($post['user_lat']);
  267. $orderData = [
  268. //'out_store_id' => $shopId,
  269. 'wx_store_id' => $shopExt['wxStoreId'],
  270. 'user_name' => $post['user_name'],
  271. 'user_phone' => $post['user_phone'],
  272. 'user_lng' => $originalLng,
  273. 'user_lat' => $originalLat,
  274. 'user_address' => $post['user_address'],
  275. 'cargo' => $cargo,
  276. 'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 开发环境默认使用沙箱
  277. ];
  278. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  279. $result = IntraCityExpress::preAddOrder($orderData);
  280. if ($result['errcode'] === 0) {
  281. util::success($result, "查询成功");
  282. } else {
  283. Yii::error("运费查询失败:" . json_encode($result));
  284. util::fail('运费查询失败' . json_encode($result));
  285. }
  286. }
  287. //根据订单查询运费 ssh
  288. public function actionGetOrderFee()
  289. {
  290. $post = Yii::$app->request->post();
  291. $orderId = $post['id'];
  292. $order = OrderClass::getById($orderId, true);
  293. if (empty($order)) {
  294. util::fail('没有找到订单');
  295. }
  296. if ($order->mainId != $this->mainId) {
  297. util::fail('不是你的订单');
  298. }
  299. $main = $this->main;
  300. $wxStoreId = $main->wxStoreId ?? '';
  301. if (empty($wxStoreId)) {
  302. util::fail('你还没有开通跑腿');
  303. }
  304. $weight = $post['weight'] ?? 0;
  305. if ($weight <= 0) {
  306. util::fail('请填写重量');
  307. }
  308. $packageNum = $post['packageNum'] ?? 1;
  309. $price = $order->actPrice ?? 0;
  310. $cargo = [
  311. 'cargo_name' => '鲜花花材', // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  312. 'cargo_weight' => intval($weight * 1000), // 单位:克 -- 把千克转换为克
  313. 'cargo_price' => intval($price * 100), // 单位:分 -- 把元转换为分
  314. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  315. 'cargo_num' => intval($packageNum)
  316. ];
  317. $originalLng = $order->long;
  318. $originalLat = $order->lat;
  319. if (empty($originalLng) || empty($originalLat)) {
  320. util::fail('客户地址不完整');
  321. }
  322. $customName = $order->customName ?? '';
  323. $customMobile = $order->customMobile ?? '';
  324. if (empty($customMobile)) {
  325. util::fail('客户手机缺失');
  326. }
  327. $address = $order->address ?? '';
  328. if (empty($address)) {
  329. util::fail('客户地址缺失');
  330. }
  331. //根据环境变量判断是否使用沙盒环境
  332. $useSandBox = getenv('YII_ENV') == 'production' ? 0 : 1;
  333. $orderData = [
  334. 'wx_store_id' => $wxStoreId,
  335. 'user_name' => $customName,
  336. 'user_phone' => $customMobile,
  337. 'user_lng' => $originalLng,
  338. 'user_lat' => $originalLat,
  339. 'user_address' => $address,
  340. 'cargo' => $cargo,
  341. 'use_sandbox' => $useSandBox,
  342. ];
  343. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  344. $result = IntraCityExpress::preAddOrder($orderData);
  345. if ($result['errcode'] === 0) {
  346. util::success($result, "查询成功");
  347. } else {
  348. Yii::error("运费查询失败:" . json_encode($result));
  349. util::fail('查询失败');
  350. }
  351. }
  352. /**
  353. * 创建订单
  354. * POST /intra-city/create-order
  355. */
  356. public function actionCreateOrder()
  357. {
  358. $post = Yii::$app->request->post();
  359. $adminId = $this->adminId;
  360. util::checkRepeatCommit($adminId, 4);
  361. $orderId = intval($post['orderId']);
  362. $order = OrderClass::getById($orderId);
  363. if (empty($order)) {
  364. util::fail('没有找到订单');
  365. }
  366. if ($order['mainId'] != $this->mainId) {
  367. util::fail('不是你的订单');
  368. }
  369. $packageNum = $post['packageNum'] ?? 0;
  370. if ($packageNum <= 0) {
  371. util::fail('请填写包裹数量');
  372. }
  373. $weight = $post['weight'] ?? 0;
  374. if ($weight <= 0) {
  375. util::fail('请填写重量');
  376. }
  377. $actPrice = $order['actPrice'] ?? 0;
  378. if ($actPrice <= 0) {
  379. util::fail('订单没有价格,不能发跑腿');
  380. }
  381. if ($order['status'] != 2) {
  382. util::fail('待发货订单才能发跑腿,请刷新页面');
  383. }
  384. // 不能创建配送的几种配送状态
  385. $notCanCreateSendStatus = [-1, 3];
  386. if (!in_array($order['sendStatus'], $notCanCreateSendStatus)) {
  387. util::fail('不能叫跑腿,请刷新页面');
  388. }
  389. $sn = $order['orderSn'];
  390. $itemInfo = OrderItemClass::getByCondition(['orderSn' => $sn], null, 'id, name, cover, num');
  391. $num = intval($order['itemNum']);
  392. $itemList[] = [
  393. 'item_name' => '花材',
  394. 'item_pic_url' => imgUtil::groupImg($itemInfo['cover']) . "?x-oss-process=image/resize,m_fill,h_130,w_130",
  395. 'count' => $num,
  396. ];
  397. $main = $this->main;
  398. $wxStoreId = $main->wxStoreId ?? '';
  399. if (empty($wxStoreId)) {
  400. util::fail('你还没有开通跑腿功能');
  401. }
  402. $cgId = $order['purchaseId'] ?? 0;
  403. if (empty($cgId)) {
  404. util::fail('没有找到采购信息');
  405. }
  406. $miniOpenId = '';
  407. $customShopAdminId = $order['customShopAdminId'] ?? 0;
  408. if (!empty($customShopAdminId)) {
  409. $customStaff = StaffClass::getById($customShopAdminId, true);
  410. $customStaffAdminId = $customStaff->adminId ?? '';
  411. if (!empty($customStaffAdminId)) {
  412. $customAdmin = AdminClass::getById($customStaffAdminId, true);
  413. $miniOpenId = $customAdmin->miniOpenId ?? '';
  414. }
  415. }
  416. if (empty($miniOpenId)) {
  417. $admin = $this->admin;
  418. $miniOpenId = $admin->miniOpenId ?? '';
  419. }
  420. if (empty($miniOpenId)) {
  421. util::fail('没有找到微信登录信息,无法呼叫跑腿');
  422. }
  423. $cargoName = '鲜花花材';//商品名称
  424. $cargo = [
  425. 'cargo_name' => $cargoName,
  426. 'cargo_weight' => intval($weight * 1000),
  427. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  428. 'cargo_num' => intval($packageNum),
  429. 'cargo_price' => intval($actPrice * 100), // $order 中有各个价格,请注意
  430. 'item_list' => $itemList,
  431. ];
  432. $shopId = $this->shopId;
  433. $mainId = $this->mainId;
  434. $snData = ['shopId' => $shopId, 'mainId' => $mainId];
  435. $storeOrderId = orderSn::getGhsExpressSn($snData);
  436. $sendNum = $order['sendNum'] ?? '';
  437. $customName = $order['customName'] ?? '';
  438. if (empty($customName)) {
  439. util::fail('客户名称无效');
  440. }
  441. $customMobile = $order['customMobile'] ?? '';
  442. if (empty($customMobile)) {
  443. util::fail('客户手机号无效');
  444. }
  445. $long = $order['long'] ?? '';
  446. $lat = $order['lat'] ?? '';
  447. if (empty($long) || empty($lat)) {
  448. util::fail('客户地址无效');
  449. }
  450. $address = $order['address'] ?? '';
  451. if (empty($address)) {
  452. util::fail('客户地址无效呢');
  453. }
  454. $callbackUrl = Yii::$app->params['ghsHost'] . '/intra-city/callback';
  455. $orderData = [
  456. 'wx_store_id' => $wxStoreId,
  457. 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
  458. 'user_openid' => $miniOpenId,
  459. 'user_lng' => (float)$long,
  460. 'user_lat' => (float)$lat,
  461. 'user_address' => $address,
  462. 'user_name' => $customName,
  463. 'user_phone' => $customMobile,
  464. 'order_seq' => $sendNum, // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
  465. 'verify_code_type' => 0,
  466. 'order_detail_path' => '/admin/order/detail?id=' . $cgId,
  467. 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
  468. 'use_sandbox' => 0,
  469. 'cargo' => $cargo
  470. ];
  471. $result = IntraCityExpress::createOrder($orderData);
  472. if (isset($result['errcode']) && $result['errcode'] === 0) {
  473. // 保存进 xhGhsExpressOrder 表
  474. $data = [
  475. 'mainId' => $this->mainId,
  476. 'shopId' => $this->shopId,
  477. 'deliveryId' => $result['service_trans_id'] ?? '',
  478. 'wxOrderId' => $result['wx_order_id'] ?? '',
  479. 'wxStoreId' => $result['wx_store_id'] ?? '',
  480. 'storeOrderId' => $result['store_order_id'] ?? '',
  481. 'orderId' => $orderId,
  482. 'transOrderId' => $result['trans_order_id'] ?? '',
  483. 'distance' => $result['distance'] ?? 0,
  484. 'fee' => $result['fee'] ?? 0,
  485. 'fetchCode' => $result['fetch_code'] ?? '',
  486. 'orderSeq' => $result['order_seq'] ?? ''
  487. ];
  488. GhsExpressOrderClass::add($data);
  489. $updateData = [
  490. 'sendDistance' => $data['distance'],
  491. 'sendStatus' => 0,
  492. 'deliveryId' => $data['deliveryId'],
  493. ];
  494. //更新订单状态为配送中
  495. OrderClass::updateById($orderId, $updateData);
  496. util::success(['fee' => $data['fee']], '订单创建成功');
  497. } else {
  498. noticeUtil::push("批发 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
  499. Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
  500. util::fail('提交失败,请确认余额是否充足');
  501. }
  502. }
  503. /**
  504. * 查询订单
  505. * GET /intra-city/get-order
  506. */
  507. public function actionGetOrder()
  508. {
  509. try {
  510. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  511. if (empty($shopExt)) {
  512. util::fail("微信门店不存在");
  513. }
  514. $post = Yii::$app->request->post();
  515. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  516. $orderId = $post['orderId'];
  517. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  518. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  519. util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
  520. }
  521. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  522. if ($order['mainId'] != $this->mainId) {
  523. util::fail('订单未找到');
  524. }
  525. // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
  526. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  527. $query = (new Query())
  528. ->from('xhGhsExpressOrder')
  529. ->where(['orderId' => $orderId])
  530. ->andWhere(['mainId' => $this->mainId]);
  531. $esDatas = $query->all();
  532. $count = count($esDatas);
  533. if ($count > 0) {
  534. $es = $esDatas[0];
  535. $storeOrderId = $es['storeOrderId'];
  536. }
  537. $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
  538. if (isset($result['errcode']) && $result['errcode'] === 0) {
  539. util::success($result, "查询成功");
  540. } else {
  541. Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  542. util::fail('订单查询失败: ' . $result['errcode']);
  543. }
  544. } catch (\Exception $e) {
  545. Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
  546. util::fail("系统出错");
  547. }
  548. }
  549. /**
  550. * 取消订单
  551. * POST /intra-city/cancel-order
  552. */
  553. public function actionCancelOrder()
  554. {
  555. try {
  556. $post = Yii::$app->request->post();
  557. $adminId = $this->adminId;
  558. util::checkRepeatCommit($adminId, 4);
  559. $orderId = $post['orderId'] ?? 0;
  560. $order = OrderClass::getById($orderId, true);//todo 这时必须取全部字段,下面发货要用到,否则会出错,请勿修改
  561. if (empty($order)) {
  562. util::fail('没有找到订单');
  563. }
  564. if ($order->mainId != $this->mainId) {
  565. util::fail('不是你的订单');
  566. }
  567. if ($order->status != 3) {
  568. util::fail('不能取消');
  569. }
  570. if (in_array($order->sendStatus, [-1, 2, 3])) {
  571. //订单 没叫跑腿、已送达、已取消
  572. util::fail('不能取消哈');
  573. }
  574. $main = $this->main;
  575. $wxStoreId = $main->wxStoreId ?? '';
  576. $express = GhsExpressOrderClass::getByCondition(['orderId' => $orderId, 'status' => 1], true);
  577. if (empty($express)) {
  578. util::fail('没有找到有效配送单');
  579. }
  580. $wxOrderId = $express->wxOrderId ?? '';
  581. $storeOrderId = $express->storeOrderId ?? '';
  582. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  583. if (isset($result['errcode']) && $result['errcode'] === 0) {
  584. // 更新订单状态
  585. $order->sendStatus = 3;
  586. $order->save();
  587. $params = ['staffId' => 0, 'staffName' => ''];
  588. OrderClass::cancelOrderSend($order, $params);
  589. $deductFee = $result['deductfee'] ?? 0;
  590. $express->status = 0;
  591. $express->cancelTime = date('Y-m-d H:i:s');
  592. $express->deductfee = $deductFee;
  593. $express->save();
  594. util::success($result, "订单取消成功");
  595. } else {
  596. if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
  597. // 更新订单状态
  598. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  599. util::success($result, "订单取消成功");
  600. }
  601. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  602. util::fail('订单取消失败: ' . $result['errcode']);
  603. }
  604. } catch (\Exception $e) {
  605. Yii::error("订单取消异常:" . $e->getMessage(), 'intraCity');
  606. util::fail("系统出错");
  607. }
  608. }
  609. /**
  610. * 微信回调接口
  611. */
  612. public function actionCallback()
  613. {
  614. $callbackData = Yii::$app->request->post();
  615. if (empty($callbackData)) {
  616. $postStr = file_get_contents('php://input');
  617. $callbackData = json_decode($postStr, true);
  618. if (empty($callbackData)) {
  619. util::fail('回调请求的数据为空');
  620. }
  621. }
  622. // 从配置中获取安全token
  623. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  624. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  625. // 记录回调日志
  626. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'intraCity');
  627. $storeOrderId = $callbackData['store_order_id'] ?? 0;
  628. $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
  629. if (empty($storeOrderId) || empty($wxStoreId)) {
  630. Yii::error("配送单回调接口的请求参数出错,storeOrderId = $storeOrderId, wxStoreId = $wxStoreId");
  631. return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
  632. }
  633. try {
  634. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  635. $eo = GhsExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  636. if (empty($eo)) {
  637. Yii::error('订单不存在. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  638. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  639. }
  640. $orderId = $eo->orderId ?? 0;
  641. if (empty($orderId)) {
  642. $errRemind = '订单号为空,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  643. Yii::error($errRemind, 'intracity');
  644. noticeUtil::push($errRemind, '15280215347');
  645. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误2']);
  646. }
  647. $order = OrderClass::getById($orderId, true);//todo 注意,这里必须取全部字段,否则下面发错会出错!!!!!!!!
  648. if (empty($order)) {
  649. $errRemind = '没有找到订单,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  650. Yii::error($errRemind, 'intracity');
  651. noticeUtil::push($errRemind, '15280215347');
  652. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误3']);
  653. }
  654. $orderStatus = intval($callbackData['order_status']);
  655. //同个配送单,同个状态的,5秒内不允许重复请求,重要勿删
  656. $uniqueId = $storeOrderId . '_' . $orderStatus;
  657. util::checkRepeatCommit($uniqueId, 5);
  658. // ====================== 开启事务
  659. $tx = Yii::$app->db->beginTransaction();
  660. $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
  661. switch ($orderStatus) {
  662. // 订单创建成功,已叫跑腿,等跑腿接单
  663. case IntraCityExpress::ORDER_STATUS_CREATED:
  664. if ($order->status == 2) {
  665. $eo->orderStatus = 1;//已叫跑腿,等跑腿接单
  666. $eo->save();
  667. $order->sendStatus = 0;//已叫跑腿,等跑腿接单
  668. $order->save();
  669. $params = [
  670. 'fhType' => 0,
  671. 'fhWl' => '',
  672. 'fhWlNo' => '',
  673. 'staffId' => 0,
  674. 'staffName' => '',
  675. ];
  676. //花店会增加路上库存
  677. OrderClass::orderSend($order, $params);
  678. }
  679. break;
  680. // 配送员接单
  681. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  682. if ($order->status == 3) {
  683. $eo->orderStatus = 4;//跑腿已接单
  684. $eo->save();
  685. $order->sendStatus = 1;//跑腿已接单
  686. $order->save();
  687. }
  688. break;
  689. // 配送员到店
  690. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  691. if ($order->status == 3) {
  692. $eo->orderStatus = 5;//跑腿到店
  693. $eo->save();
  694. $order->sendStatus = 4;//跑腿到店
  695. $order->save();
  696. }
  697. break;
  698. // 配送中
  699. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  700. if ($order->status == 3) {
  701. $eo->orderStatus = 6;//跑腿配送中
  702. $eo->save();
  703. $order->sendStatus = 5;//跑腿配送中
  704. $order->save();
  705. }
  706. break;
  707. // 配送完成
  708. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  709. if ($order->status == 3) {
  710. $eo->orderStatus = 8;//配送完成
  711. $eo->save();
  712. $order->sendStatus = 2;//已送达
  713. $order->save();
  714. $params = ['staffId' => 0, 'staffName' => ''];
  715. OrderClass::confirmReach($order, $params);
  716. }
  717. break;
  718. // 商家取消订单
  719. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  720. //取消已发货,回滚到待发货
  721. if ($order->status == 3) {
  722. $eo->orderStatus = 2;
  723. $eo->save();
  724. $order->sendStatus = 3;
  725. $order->save();
  726. $params = ['staffId' => 0, 'staffName' => ''];
  727. OrderClass::cancelOrderSend($order, $params);
  728. }
  729. $msg = '取消配送,订单编号 ';
  730. break;
  731. // 配送方取消订单
  732. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
  733. //取消已发货,回滚到待发货
  734. if ($order->status == 3) {
  735. $eo->orderStatus = 3;
  736. $eo->status = 0;
  737. $eo->save();
  738. $order->sendStatus = 3;
  739. $order->save();
  740. $params = ['staffId' => 0, 'staffName' => ''];
  741. OrderClass::cancelOrderSend($order, $params);
  742. }
  743. $msg = '配送方取消配送,订单编号 ';
  744. break;
  745. // 配送员撤单
  746. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  747. //todo 配送员撤单,目前我们认为会重新派单,先不要有任何操作!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  748. $msg = '跑腿取消配送,订单编号 ';
  749. break;
  750. // 配送异常
  751. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  752. //取消已发货,回滚到待发货
  753. if ($order->status == 3) {
  754. $eo->orderStatus = 9;
  755. $eo->status = 0;
  756. $eo->save();
  757. $order->sendStatus = 3;
  758. $order->save();
  759. $params = ['staffId' => 0, 'staffName' => ''];
  760. OrderClass::cancelOrderSend($order, $params);
  761. }
  762. $msg = '订单配送异常,订单编号 ';
  763. break;
  764. }
  765. // ====================== 事务提交
  766. $tx->commit();
  767. if (!empty($msg)) {
  768. $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
  769. $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
  770. $result = $msg . $order->sendNum;
  771. WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
  772. }
  773. // 成功状态的返回数据
  774. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  775. } catch (\Exception $e) {
  776. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  777. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  778. }
  779. }
  780. //模拟接口回调 ssh 20250826
  781. public function actionMockNotify()
  782. {
  783. if (getenv('YII_ENV') != 'production') {
  784. $post = Yii::$app->request->post();
  785. $orderStatus = $post['orderStatus'] ?? 0;
  786. $wxOrderId = $post['wxOrderId'] ?? '';
  787. $ptStyle = dict::getDict('ptStyle', 'hd');
  788. $merchant = WxOpenClass::getWxInfo();
  789. $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
  790. util::success($ret);
  791. }
  792. util::complete();
  793. }
  794. }