IntraCityController.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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\purchase\classes\PurchaseClass;
  10. use bizHd\saas\classes\StaffClass;
  11. use common\components\dict;
  12. use common\components\imgUtil;
  13. use common\components\orderSn;
  14. use hd\models\IntraCity\StoreFeeForm;
  15. // 以上类来自零售端
  16. use bizGhs\order\classes\OrderClass;
  17. use biz\shop\classes\MainClass;
  18. use biz\shop\classes\ShopClass;
  19. use common\components\noticeUtil;
  20. use common\components\util;
  21. use common\components\IntraCityExpress;
  22. use yii\helpers\Json;
  23. use yii\db\Query;
  24. use Yii;
  25. /**
  26. * 同城配送控制器
  27. * 提供同城配送相关的API接口
  28. */
  29. class IntraCityController extends BaseController
  30. {
  31. public $guestAccess = ['callback'];
  32. /**
  33. * 创建门店
  34. * POST /intra-city/create-store
  35. */
  36. public function actionCreateStore()
  37. {
  38. try {
  39. $shop = $this->shop;
  40. $shopName = $shop->shopName ?? '';
  41. $sjName = $shop->merchantName ?? '';
  42. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  43. $storeData = [
  44. 'out_store_id' => $this->mainId, //自定义门店编号
  45. 'store_name' => $name,
  46. 'address_info' => [
  47. 'province' => $shop->province,
  48. 'city' => $shop->city,
  49. 'area' => $shop->dist,
  50. 'street' => '',
  51. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  52. 'lat' => $shop->lat,
  53. 'lng' => $shop->long,
  54. 'phone' => $shop->telephone
  55. ]
  56. ];
  57. // 验证必填参数
  58. $requiredFields = ['out_store_id', 'store_name', 'address_info'];
  59. foreach ($requiredFields as $field) {
  60. if (empty($storeData[$field])) {
  61. util::fail("缺少必填参数:{$field}");
  62. }
  63. }
  64. // 创建门店前,检查是否已经 开通门店权限 (有wxStoreId,即说明开通了)
  65. $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  66. // 查询是否存在 wx_store_id,不存在则执行apply
  67. if ($main->wxStoreId == '') {
  68. $re = IntraCityExpress::applyStore();
  69. if (!is_array($re)) {
  70. $re = Json::decode($re, true);
  71. }
  72. if ($re['errcode'] != 0) {
  73. Yii::error("开通门店权限失败:" . $re['errmsg']);
  74. util::fail('开通门店权限失败');
  75. }
  76. }
  77. $result = IntraCityExpress::createStore($storeData);
  78. if ($result['errcode'] === 0) {
  79. // 保存微信门店编号(wx_store_id)
  80. $main->wxStoreId = $result['wx_store_id'];
  81. $main->save();
  82. util::success($result, "门店创建成功");
  83. } else {
  84. Yii::error("门店创建失败:" . $result['errmsg']);
  85. util::fail($result['errmsg']);
  86. }
  87. } catch (\Exception $e) {
  88. Yii::error("门店创建失败:" . $e->getMessage());
  89. util::fail("系统出错");
  90. }
  91. }
  92. /**
  93. * 查询门店创建情况
  94. */
  95. public function actionStore()
  96. {
  97. $shopId = $this->shopId;
  98. // 首先从门店扩展表查询是否已经创建
  99. $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  100. if ($main->wxStoreId == '') { // 不存在,则从微信接口查询
  101. $result = IntraCityExpress::getStore($this->mainId);
  102. if ($result['errcode'] === 0) {
  103. $store = $result['store_list'][0];
  104. // 保存 wx_store_id
  105. $main->wxStoreId = $store['wx_store_id'];
  106. $main->save();
  107. util::success($store, "门店查询成功");
  108. } else {
  109. Yii::error("门店查询失败:" . $result['errmsg']);
  110. util::error(-1, '门店查询失败');
  111. }
  112. } else {
  113. $field = 'province, city, dist, lat, long, floor, address';
  114. $shop = ShopClass::getById($shopId, false, $field);
  115. $data = array_merge($shop, $main->toArray());
  116. util::success($data, "门店查询成功");
  117. }
  118. }
  119. /**
  120. * 更新门店
  121. */
  122. public function actionUpdateStore()
  123. {
  124. // 首先从门店扩展表查询是否已经创建
  125. $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  126. if ($main['wxStoreId'] == '') {
  127. util::fail('未创建门店,请先创建');
  128. }
  129. $shop = $this->shop;
  130. $shopName = $shop->shopName ?? '';
  131. $sjName = $shop->merchantName ?? '';
  132. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  133. $storeData = [
  134. 'keys' => ['wx_store_id' => $main['wxStoreId']],
  135. 'content' => [
  136. 'store_name' => $name,
  137. 'address_info' => [
  138. 'province' => $shop->province,
  139. 'city' => $shop->city,
  140. 'area' => $shop->dist,
  141. 'street' => '',
  142. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  143. 'lat' => $shop->lat,
  144. 'lng' => $shop->long,
  145. 'phone' => $shop->telephone
  146. ],
  147. //"order_pattern" => 2,
  148. //"service_trans_prefer" => "SFTC" //order_pattern = 2时必填
  149. ]
  150. ];
  151. $result = IntraCityExpress::updateStore($storeData);
  152. if ($result['errcode'] === 0) {
  153. util::success($result, "门店更新成功");
  154. } else {
  155. Yii::error("门店更新失败:" . $result['errmsg']);
  156. util::fail($result['errmsg']);
  157. }
  158. }
  159. /**
  160. * 门店运费充值
  161. */
  162. public function actionStoreCharge()
  163. {
  164. $post = Yii::$app->request->post();
  165. $amount = floatval($post['amount']);
  166. $amountTurnFen = $amount * 100;
  167. if ($amountTurnFen < 5000) {
  168. util::fail('50元起充');
  169. }
  170. $expressId = $post['expressId'];
  171. $serviceTransIds = ['SFTC', 'DADA'];
  172. if (!in_array($expressId, $serviceTransIds)) {
  173. util::fail('快递动力ID出错');
  174. }
  175. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  176. if ($shopExt['wxStoreId'] == '') {
  177. util::fail('微信门店编号为空');
  178. }
  179. $wxStoreId = $shopExt['wxStoreId'];
  180. $result = IntraCityExpress::storeCharge($wxStoreId, $expressId, $amountTurnFen);
  181. if ($result['errcode'] === 0) {
  182. util::success($result, "门店余额充值单已生成");
  183. } else {
  184. Yii::error("门店余额充值失败:" . $result['errmsg']);
  185. util::fail('门店余额充值失败');
  186. }
  187. }
  188. /**
  189. * 门店余额查询
  190. */
  191. public function actionStoreBalance()
  192. {
  193. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  194. if ($shopExt['wxStoreId'] == '') {
  195. util::error(-1, '微信门店编号为空');
  196. }
  197. $wxStoreId = $shopExt['wxStoreId'];
  198. $result = IntraCityExpress::getBalance($wxStoreId);
  199. if ($result['errcode'] === 0) {
  200. $data = ['all_balance' => $result['all_balance'] / 100.0];
  201. foreach ($result['balance_detail'] as $item) {
  202. if ($item['service_trans_id'] == 'DADA') {
  203. $data['dada_balance'] = $item['balance'] / 100.0;
  204. }
  205. if ($item['service_trans_id'] == 'SFTC') {
  206. $data['sf_balance'] = $item['balance'] / 100.0;
  207. }
  208. }
  209. util::success($data, "门店余额查询成功");
  210. } else {
  211. Yii::error("门店余额查询失败:" . $result['errmsg']);
  212. util::fail('门店余额查询失败');
  213. }
  214. }
  215. /**
  216. * 查询运费
  217. */
  218. public function actionStoreFee()
  219. {
  220. $post = Yii::$app->request->post();
  221. // 创建表单验证模型
  222. $form = new StoreFeeForm();
  223. $form->setScenario('store_fee');
  224. $form->load($post, ''); // 直接从 post 数据加载,不使用模型名作为前缀
  225. // 执行表单验证
  226. $form->validateForm();
  227. $orderId = $post['orderId'];
  228. $order = OrderClass::getById($orderId);
  229. if (empty($order)) {
  230. util::fail('订单出错');
  231. }
  232. if ($order['mainId'] != $this->mainId) {
  233. util::fail('订单出错');
  234. }
  235. $sn = $order['orderSn'];
  236. $shopId = intval($this->shopId);
  237. if (empty($shopId)) {
  238. util::fail("门店不存在");
  239. }
  240. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  241. if (empty($shopExt)) {
  242. util::fail("微信门店不存在");
  243. }
  244. $itemInfoList = OrderItemClass::getAllByCondition(['orderSn' => $sn], null, 'id, name, cover, num');
  245. $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
  246. if (empty($itemInfoList)) {
  247. $orderType = 1;
  248. }
  249. $cargoName = '花材'; // 商品名称,默认是花材
  250. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  251. if (count($goodsInfoList) == 1) {
  252. $goodsInfo = $goodsInfoList[0];
  253. $cargoName = $goodsInfo['name'];
  254. } else {
  255. if ($orderType != 2) {
  256. util::fail("订单商品数量不正确");
  257. }
  258. }
  259. $cargo = [
  260. 'cargo_name' => $cargoName, // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  261. 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克
  262. 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
  263. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  264. 'cargo_num' => intval($post['packageNum'])
  265. ];
  266. $originalLng = doubleval($post['user_lng']);
  267. $originalLat = doubleval($post['user_lat']);
  268. $orderData = [
  269. //'out_store_id' => $shopId,
  270. 'wx_store_id' => $shopExt['wxStoreId'],
  271. 'user_name' => $post['user_name'],
  272. 'user_phone' => $post['user_phone'],
  273. 'user_lng' => $originalLng,
  274. 'user_lat' => $originalLat,
  275. 'user_address' => $post['user_address'],
  276. 'cargo' => $cargo,
  277. 'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 开发环境默认使用沙箱
  278. ];
  279. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  280. $result = IntraCityExpress::preAddOrder($orderData);
  281. if ($result['errcode'] === 0) {
  282. util::success($result, "查询成功");
  283. } else {
  284. Yii::error("运费查询失败:" . json_encode($result));
  285. util::fail('运费查询失败,编号56698');
  286. }
  287. }
  288. //根据订单查询运费 ssh
  289. public function actionGetOrderFee()
  290. {
  291. $post = Yii::$app->request->post();
  292. $orderId = $post['id'];
  293. $order = OrderClass::getById($orderId, true);
  294. if (empty($order)) {
  295. util::fail('没有找到订单');
  296. }
  297. if ($order->mainId != $this->mainId) {
  298. util::fail('不是你的订单');
  299. }
  300. $main = $this->main;
  301. $wxStoreId = $main->wxStoreId ?? '';
  302. if (empty($wxStoreId)) {
  303. util::fail('你还没有开通跑腿');
  304. }
  305. $weight = $post['weight'] ?? 0;
  306. if ($weight <= 0) {
  307. util::fail('请填写重量');
  308. }
  309. $packageNum = $post['packageNum'] ?? 1;
  310. $price = $order->actPrice ?? 0;
  311. $cargo = [
  312. 'cargo_name' => '鲜花花材', // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  313. 'cargo_weight' => intval($weight * 1000), // 单位:克 -- 把千克转换为克
  314. 'cargo_price' => intval($price * 100), // 单位:分 -- 把元转换为分
  315. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  316. 'cargo_num' => intval($packageNum)
  317. ];
  318. $originalLng = $order->long;
  319. $originalLat = $order->lat;
  320. if (empty($originalLng) || empty($originalLat)) {
  321. util::fail('客户地址不完整');
  322. }
  323. $customName = $order->customName ?? '';
  324. $customMobile = $order->customMobile ?? '';
  325. if (empty($customMobile)) {
  326. util::fail('客户手机缺失');
  327. }
  328. $address = $order->address ?? '';
  329. if (empty($address)) {
  330. util::fail('客户地址缺失');
  331. }
  332. //查询运费可以不用沙箱
  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' => 0,
  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. $cgId = $order->purchaseId ?? 0;
  575. $cg = PurchaseClass::getById($cgId, true);
  576. if (empty($cg)) {
  577. util::fail('没有采购单信息');
  578. }
  579. $main = $this->main;
  580. $wxStoreId = $main->wxStoreId ?? '';
  581. $express = GhsExpressOrderClass::getByCondition(['orderId' => $orderId, 'status' => 1], true);
  582. if (empty($express)) {
  583. util::fail('没有找到有效配送单');
  584. }
  585. $wxOrderId = $express->wxOrderId ?? '';
  586. $storeOrderId = $express->storeOrderId ?? '';
  587. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  588. if (isset($result['errcode']) && $result['errcode'] === 0) {
  589. // 更新订单状态
  590. $order->sendStatus = 3;
  591. $order->save();
  592. $cg->sendStatus = 3;
  593. $cg->save();
  594. $params = ['staffId' => 0, 'staffName' => ''];
  595. OrderClass::cancelOrderSend($order, $params);
  596. $deductFee = $result['deductfee'] ?? 0;
  597. $express->status = 0;
  598. $express->cancelTime = date('Y-m-d H:i:s');
  599. $express->deductfee = $deductFee;
  600. $express->save();
  601. util::success($result, "订单取消成功");
  602. } else {
  603. if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
  604. // 更新订单状态
  605. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  606. util::success($result, "订单取消成功");
  607. }
  608. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  609. util::fail('订单取消失败: ' . $result['errcode']);
  610. }
  611. } catch (\Exception $e) {
  612. Yii::error("订单取消异常:" . $e->getMessage(), 'intraCity');
  613. util::fail("系统出错");
  614. }
  615. }
  616. /**
  617. * 微信回调接口
  618. */
  619. public function actionCallback()
  620. {
  621. $callbackData = Yii::$app->request->post();
  622. if (empty($callbackData)) {
  623. $postStr = file_get_contents('php://input');
  624. $callbackData = json_decode($postStr, true);
  625. if (empty($callbackData)) {
  626. util::fail('回调请求的数据为空');
  627. }
  628. }
  629. // 从配置中获取安全token
  630. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  631. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  632. // 记录回调日志
  633. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'intraCity');
  634. $storeOrderId = $callbackData['store_order_id'] ?? 0;
  635. $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
  636. if (empty($storeOrderId) || empty($wxStoreId)) {
  637. Yii::error("配送单回调接口的请求参数出错,storeOrderId = $storeOrderId, wxStoreId = $wxStoreId");
  638. return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
  639. }
  640. try {
  641. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  642. $eo = GhsExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  643. if (empty($eo)) {
  644. Yii::error('订单不存在. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  645. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  646. }
  647. $orderId = $eo->orderId ?? 0;
  648. if (empty($orderId)) {
  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' => '系统错误2']);
  653. }
  654. $order = OrderClass::getById($orderId, true);//todo 注意,这里必须取全部字段,否则下面发错会出错!!!!!!!!
  655. if (empty($order)) {
  656. $errRemind = '没有找到订单,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  657. Yii::error($errRemind, 'intracity');
  658. noticeUtil::push($errRemind, '15280215347');
  659. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误3']);
  660. }
  661. $cgId = $order->purchaseId ?? 0;
  662. $cg = PurchaseClass::getById($cgId, true);
  663. if (empty($cg)) {
  664. $errRemind = '没有找到采购单,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  665. Yii::error($errRemind, 'intracity');
  666. noticeUtil::push($errRemind, '15280215347');
  667. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误4']);
  668. }
  669. $orderStatus = intval($callbackData['order_status']);
  670. //同个配送单,同个状态的,5秒内不允许重复请求,重要勿删
  671. $uniqueId = $storeOrderId . '_' . $orderStatus;
  672. util::checkRepeatCommit($uniqueId, 5);
  673. // ====================== 开启事务
  674. $tx = Yii::$app->db->beginTransaction();
  675. $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
  676. switch ($orderStatus) {
  677. // 订单创建成功,已叫跑腿,等跑腿接单
  678. case IntraCityExpress::ORDER_STATUS_CREATED:
  679. if ($order->status == 2) {
  680. $eo->orderStatus = 1;//已叫跑腿,等跑腿接单
  681. $eo->save();
  682. $order->sendStatus = 0;//已叫跑腿,等跑腿接单
  683. $order->save();
  684. $cg->sendStatus = 0;//已叫跑腿,等跑腿接单
  685. $cg->save();
  686. $params = [
  687. 'fhType' => 0,
  688. 'fhWl' => '',
  689. 'fhWlNo' => '',
  690. 'staffId' => 0,
  691. 'staffName' => '',
  692. ];
  693. //花店会增加路上库存
  694. OrderClass::orderSend($order, $params);
  695. }
  696. break;
  697. // 配送员接单
  698. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  699. if ($order->status == 3) {
  700. $eo->orderStatus = 4;//跑腿已接单
  701. $eo->save();
  702. $order->sendStatus = 1;//跑腿已接单
  703. $order->save();
  704. $cg->sendStatus = 1;//跑腿已接单
  705. $cg->save();
  706. }
  707. break;
  708. // 配送员到店
  709. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  710. if ($order->status == 3) {
  711. $eo->orderStatus = 5;//跑腿到店
  712. $eo->save();
  713. $order->sendStatus = 4;//跑腿到店
  714. $order->save();
  715. $cg->sendStatus = 4;//跑腿到店
  716. $cg->save();
  717. }
  718. break;
  719. // 配送中
  720. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  721. if ($order->status == 3) {
  722. $eo->orderStatus = 6;//跑腿配送中
  723. $eo->save();
  724. $order->sendStatus = 5;//跑腿配送中
  725. $order->save();
  726. $cg->sendStatus = 5;//跑腿配送中
  727. $cg->save();
  728. }
  729. break;
  730. // 配送完成
  731. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  732. if ($order->status == 3) {
  733. $eo->orderStatus = 8;//配送完成
  734. $eo->save();
  735. $order->sendStatus = 2;//已送达
  736. $order->save();
  737. $cg->sendStatus = 2;//已送达
  738. $cg->save();
  739. $params = ['staffId' => 0, 'staffName' => ''];
  740. OrderClass::confirmReach($order, $params);
  741. }
  742. break;
  743. // 商家取消订单
  744. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  745. //取消已发货,回滚到待发货
  746. if ($order->status == 3) {
  747. $eo->orderStatus = 2;
  748. $eo->save();
  749. $order->sendStatus = 3;
  750. $order->save();
  751. $cg->sendStatus = 3;
  752. $cg->save();
  753. $params = ['staffId' => 0, 'staffName' => ''];
  754. OrderClass::cancelOrderSend($order, $params);
  755. }
  756. $msg = '取消配送,订单编号 ';
  757. break;
  758. // 配送方取消订单
  759. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
  760. //取消已发货,回滚到待发货
  761. if ($order->status == 3) {
  762. $eo->orderStatus = 3;
  763. $eo->status = 0;
  764. $eo->save();
  765. $order->sendStatus = 3;
  766. $order->save();
  767. $cg->sendStatus = 3;
  768. $cg->save();
  769. $params = ['staffId' => 0, 'staffName' => ''];
  770. OrderClass::cancelOrderSend($order, $params);
  771. }
  772. $msg = '配送方取消配送,订单编号 ';
  773. break;
  774. // 配送员撤单
  775. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  776. //todo 配送员撤单,目前我们认为会重新派单,先不要有任何操作!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  777. $msg = '跑腿取消配送,订单编号 ';
  778. break;
  779. // 配送异常
  780. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  781. //取消已发货,回滚到待发货
  782. if ($order->status == 3) {
  783. $eo->orderStatus = 9;
  784. $eo->status = 0;
  785. $eo->save();
  786. $order->sendStatus = 3;
  787. $order->save();
  788. $cg->sendStatus = 3;
  789. $cg->save();
  790. $params = ['staffId' => 0, 'staffName' => ''];
  791. OrderClass::cancelOrderSend($order, $params);
  792. }
  793. $msg = '订单配送异常,订单编号 ';
  794. break;
  795. }
  796. // ====================== 事务提交
  797. $tx->commit();
  798. if (!empty($msg)) {
  799. $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
  800. $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
  801. $result = $msg . $order->sendNum;
  802. WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
  803. }
  804. // 成功状态的返回数据
  805. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  806. } catch (\Exception $e) {
  807. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  808. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  809. }
  810. }
  811. //模拟接口回调 ssh 20250826
  812. public function actionMockNotify()
  813. {
  814. if (getenv('YII_ENV') != 'production') {
  815. $post = Yii::$app->request->post();
  816. $orderStatus = $post['orderStatus'] ?? 0;
  817. $wxOrderId = $post['wxOrderId'] ?? '';
  818. $ptStyle = dict::getDict('ptStyle', 'hd');
  819. $merchant = WxOpenClass::getWxInfo();
  820. $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
  821. util::success($ret);
  822. }
  823. util::complete();
  824. }
  825. }