IntraCityController.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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 as ExpressOrderClass;
  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('运费查询失败' . json_encode($result));
  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. $useSandBox = getenv('YII_ENV') == 'production' ? 0 : 1;
  334. $orderData = [
  335. 'wx_store_id' => $wxStoreId,
  336. 'user_name' => $customName,
  337. 'user_phone' => $customMobile,
  338. 'user_lng' => $originalLng,
  339. 'user_lat' => $originalLat,
  340. 'user_address' => $address,
  341. 'cargo' => $cargo,
  342. 'use_sandbox' => $useSandBox,
  343. ];
  344. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  345. $result = IntraCityExpress::preAddOrder($orderData);
  346. if ($result['errcode'] === 0) {
  347. util::success($result, "查询成功");
  348. } else {
  349. Yii::error("运费查询失败:" . json_encode($result));
  350. util::fail('查询失败');
  351. }
  352. }
  353. /**
  354. * 创建订单
  355. * POST /intra-city/create-order
  356. */
  357. public function actionCreateOrder()
  358. {
  359. $post = Yii::$app->request->post();
  360. $adminId = $this->adminId;
  361. util::checkRepeatCommit($adminId, 4);
  362. $orderId = intval($post['orderId']);
  363. $order = OrderClass::getById($orderId);
  364. if (empty($order)) {
  365. util::fail('没有找到订单');
  366. }
  367. if ($order['mainId'] != $this->mainId) {
  368. util::fail('不是你的订单');
  369. }
  370. $packageNum = $post['packageNum'] ?? 0;
  371. if ($packageNum <= 0) {
  372. util::fail('请填写包裹数量');
  373. }
  374. $weight = $post['weight'] ?? 0;
  375. if ($weight <= 0) {
  376. util::fail('请填写重量');
  377. }
  378. $actPrice = $order['actPrice'] ?? 0;
  379. if ($actPrice <= 0) {
  380. util::fail('订单没有价格,不需要发跑腿');
  381. }
  382. $sn = $order['orderSn'];
  383. $itemInfo = OrderItemClass::getByCondition(['orderSn' => $sn], null, 'id, name, cover, num');
  384. $num = intval($order['itemNum']);
  385. $itemList[] = [
  386. 'item_name' => '花材',
  387. 'item_pic_url' => imgUtil::groupImg($itemInfo['cover']) . "?x-oss-process=image/resize,m_fill,h_130,w_130",
  388. 'count' => $num,
  389. ];
  390. $main = $this->main;
  391. $wxStoreId = $main->wxStoreId ?? '';
  392. if (empty($wxStoreId)) {
  393. util::fail('你还没有开通跑腿功能');
  394. }
  395. $cgId = $order['purchaseId'] ?? 0;
  396. if (empty($cgId)) {
  397. util::fail('没有找到采购信息');
  398. }
  399. $miniOpenId = '';
  400. $customShopAdminId = $order['customShopAdminId'] ?? 0;
  401. if (!empty($customShopAdminId)) {
  402. $customStaff = StaffClass::getById($customShopAdminId, true);
  403. $customStaffAdminId = $customStaff->adminId ?? '';
  404. if (!empty($customStaffAdminId)) {
  405. $customAdmin = AdminClass::getById($customStaffAdminId, true);
  406. $miniOpenId = $customAdmin->miniOpenId ?? '';
  407. }
  408. }
  409. if (empty($miniOpenId)) {
  410. $admin = $this->admin;
  411. $miniOpenId = $admin->miniOpenId ?? '';
  412. }
  413. if (empty($miniOpenId)) {
  414. util::fail('没有找到微信登录信息,无法呼叫跑腿');
  415. }
  416. $cargoName = '鲜花花材';//商品名称
  417. $cargo = [
  418. 'cargo_name' => $cargoName,
  419. 'cargo_weight' => intval($weight * 1000),
  420. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  421. 'cargo_num' => intval($packageNum),
  422. 'cargo_price' => intval($actPrice * 100), // $order 中有各个价格,请注意
  423. 'item_list' => $itemList,
  424. ];
  425. $shopId = $this->shopId;
  426. $mainId = $this->mainId;
  427. $snData = ['shopId' => $shopId, 'mainId' => $mainId];
  428. $storeOrderId = orderSn::getGhsExpressSn($snData);
  429. $sendNum = $order['sendNum'] ?? '';
  430. $customName = $order['customName'] ?? '';
  431. if (empty($customName)) {
  432. util::fail('客户名称无效');
  433. }
  434. $customMobile = $order['customMobile'] ?? '';
  435. if (empty($customMobile)) {
  436. util::fail('客户手机号无效');
  437. }
  438. $long = $order['long'] ?? '';
  439. $lat = $order['lat'] ?? '';
  440. if (empty($long) || empty($lat)) {
  441. util::fail('客户地址无效');
  442. }
  443. $address = $order['address'] ?? '';
  444. if (empty($address)) {
  445. util::fail('客户地址无效呢');
  446. }
  447. $callbackUrl = Yii::$app->params['ghsHost'] . '/intra-city/callback';
  448. $orderData = [
  449. 'wx_store_id' => $wxStoreId,
  450. 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
  451. 'user_openid' => $miniOpenId,
  452. 'user_lng' => (float)$long,
  453. 'user_lat' => (float)$lat,
  454. 'user_address' => $address,
  455. 'user_name' => $customName,
  456. 'user_phone' => $customMobile,
  457. 'order_seq' => $sendNum, // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
  458. 'verify_code_type' => 0,
  459. 'order_detail_path' => '/admin/order/detail?id=' . $cgId,
  460. 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
  461. 'use_sandbox' => 0,
  462. 'cargo' => $cargo
  463. ];
  464. $result = IntraCityExpress::createOrder($orderData);
  465. if (isset($result['errcode']) && $result['errcode'] === 0) {
  466. // 保存进 xhGhsExpressOrder 表
  467. $data = [
  468. 'mainId' => $this->mainId,
  469. 'shopId' => $this->shopId,
  470. 'deliveryId' => $result['service_trans_id'] ?? '',
  471. 'wxOrderId' => $result['wx_order_id'] ?? '',
  472. 'wxStoreId' => $result['wx_store_id'] ?? '',
  473. 'storeOrderId' => $result['store_order_id'] ?? '',
  474. 'orderId' => $orderId,
  475. 'transOrderId' => $result['trans_order_id'] ?? '',
  476. 'distance' => $result['distance'] ?? 0,
  477. 'fee' => $result['fee'] ?? 0,
  478. 'fetchCode' => $result['fetch_code'] ?? '',
  479. 'orderSeq' => $result['order_seq'] ?? ''
  480. ];
  481. ExpressOrderClass::add($data);
  482. $updateData = [
  483. 'sendDistance' => $data['distance'],
  484. 'sendStatus' => 0,
  485. 'deliveryId' => $data['deliveryId'],
  486. ];
  487. //更新订单状态为配送中
  488. OrderClass::updateById($orderId, $updateData);
  489. util::success(['fee' => $data['fee']], '订单创建成功');
  490. } else {
  491. noticeUtil::push("批发 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
  492. Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
  493. util::fail('提交失败,请确认余额是否充足');
  494. }
  495. }
  496. /**
  497. * 查询订单
  498. * GET /intra-city/get-order
  499. */
  500. public function actionGetOrder()
  501. {
  502. try {
  503. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  504. if (empty($shopExt)) {
  505. util::fail("微信门店不存在");
  506. }
  507. $post = Yii::$app->request->post();
  508. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  509. $orderId = $post['orderId'];
  510. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  511. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  512. util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
  513. }
  514. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  515. if ($order['mainId'] != $this->mainId) {
  516. util::fail('订单未找到');
  517. }
  518. // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
  519. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  520. $query = (new Query())
  521. ->from('xhGhsExpressOrder')
  522. ->where(['orderId' => $orderId])
  523. ->andWhere(['mainId' => $this->mainId]);
  524. $esDatas = $query->all();
  525. $count = count($esDatas);
  526. if ($count > 0) {
  527. $es = $esDatas[0];
  528. $storeOrderId = $es['storeOrderId'];
  529. }
  530. $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
  531. if (isset($result['errcode']) && $result['errcode'] === 0) {
  532. util::success($result, "查询成功");
  533. } else {
  534. Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  535. util::fail('订单查询失败: ' . $result['errcode']);
  536. }
  537. } catch (\Exception $e) {
  538. Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
  539. util::fail("系统出错");
  540. }
  541. }
  542. /**
  543. * 取消订单
  544. * POST /intra-city/cancel-order
  545. */
  546. public function actionCancelOrder()
  547. {
  548. try {
  549. $post = Yii::$app->request->post();
  550. $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  551. if (empty($main)) {
  552. util::fail("微信门店不存在");
  553. }
  554. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  555. $orderId = $post['orderId']; //配送订单创建成功后,也会返回的 store_order_id。 即 orderId
  556. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $main['wxStoreId'];
  557. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  558. util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
  559. }
  560. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  561. if ($order['mainId'] != $this->mainId) {
  562. util::fail('订单未找到');
  563. }
  564. if (!in_array($order['sendStatus'], [0, 1, 4, 5])) {
  565. util::fail('配送单当前状态不能取消');
  566. }
  567. // 检查是否存在重复的订单,如果存在,则使用最后一个订单的 store_order_id
  568. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  569. $query = (new Query())
  570. ->from('xhGhsExpressOrder')
  571. ->where(['orderId' => $orderId])
  572. ->andWhere(['status' => 1])
  573. ->orderBy('addTime DESC');
  574. // $command = $query->createCommand();
  575. // $sql = $command->sql;
  576. $esDatas = $query->all();
  577. $count = count($esDatas);
  578. if ($count > 0) {
  579. $es = $esDatas[0];
  580. $storeOrderId = $es['storeOrderId'];
  581. if ($count > 1) {
  582. noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
  583. }
  584. }
  585. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  586. if (isset($result['errcode']) && $result['errcode'] === 0) {
  587. // 更新订单状态
  588. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  589. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true);
  590. if (!empty($eo)) {
  591. $eo->status = 3;
  592. $eo->cancelTime = date('Y-m-d H:i:s');
  593. $eo->deductfee = $result['deductfee'];
  594. $eo->save();
  595. }
  596. util::success($result, "订单取消成功");
  597. } else {
  598. if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
  599. // 更新订单状态
  600. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  601. util::success($result, "订单取消成功");
  602. }
  603. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  604. util::fail('订单取消失败: ' . $result['errcode']);
  605. }
  606. } catch (\Exception $e) {
  607. Yii::error("订单取消异常:" . $e->getMessage(), 'intraCity');
  608. util::fail("系统出错");
  609. }
  610. }
  611. /**
  612. * 微信回调接口
  613. */
  614. public function actionCallback()
  615. {
  616. $callbackData = Yii::$app->request->post();
  617. if (empty($callbackData)) {
  618. $postStr = file_get_contents('php://input');
  619. $callbackData = json_decode($postStr, true);
  620. if (empty($callbackData)) {
  621. util::fail('回调请求的数据为空');
  622. }
  623. }
  624. // 从配置中获取安全token
  625. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  626. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  627. // 记录回调日志
  628. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'intraCity');
  629. $storeOrderId = $callbackData['store_order_id'] ?? 0;
  630. $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
  631. if (empty($storeOrderId) || empty($wxStoreId)) {
  632. Yii::error("配送单回调接口的请求参数出错,storeOrderId = $storeOrderId, wxStoreId = $wxStoreId");
  633. return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
  634. }
  635. try {
  636. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  637. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  638. if (empty($eo)) {
  639. Yii::error('订单不存在. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  640. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  641. }
  642. $orderId = $eo->orderId ?? 0;
  643. if (empty($orderId)) {
  644. $errRemind = '订单号为空,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  645. Yii::error($errRemind, 'intracity');
  646. noticeUtil::push($errRemind, '15280215347');
  647. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误2']);
  648. }
  649. $order = OrderClass::getById($orderId, true, 'id, mainId, sendStatus,status');
  650. if (empty($order)) {
  651. $errRemind = '没有找到订单,store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId;
  652. Yii::error($errRemind, 'intracity');
  653. noticeUtil::push($errRemind, '15280215347');
  654. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误3']);
  655. }
  656. $orderStatus = intval($callbackData['order_status']);
  657. //同个配送单,同个状态的,5秒内不允许重复请求,重要勿删
  658. $uniqueId = $storeOrderId . '_' . $orderStatus;
  659. util::checkRepeatCommit($uniqueId, 5);
  660. // ====================== 开启事务
  661. $tx = Yii::$app->db->beginTransaction();
  662. $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
  663. switch ($orderStatus) {
  664. // 订单创建成功,已叫跑腿,等跑腿接单
  665. case IntraCityExpress::ORDER_STATUS_CREATED:
  666. if ($order->status == 2) {
  667. $eo->orderStatus = 1;//已叫跑腿,等跑腿接单
  668. $eo->save();
  669. $order->sendStatus = 0;//已叫跑腿,等跑腿接单
  670. $order->save();
  671. $params = [
  672. 'fhType' => 0,
  673. 'fhWl' => '',
  674. 'fhWlNo' => '',
  675. 'staffId' => 0,
  676. 'staffName' => '',
  677. ];
  678. //花店会增加路上库存
  679. OrderClass::orderSend($order, $params);
  680. }
  681. break;
  682. // 配送员接单
  683. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  684. if ($order->status == 3) {
  685. $eo->orderStatus = 4;//跑腿已接单
  686. $eo->save();
  687. $order->sendStatus = 1;//跑腿已接单
  688. $order->save();
  689. }
  690. break;
  691. // 配送员到店
  692. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  693. if ($order->status == 3) {
  694. $eo->orderStatus = 5;//跑腿到店
  695. $eo->save();
  696. $order->sendStatus = 4;//跑腿到店
  697. $order->save();
  698. }
  699. break;
  700. // 配送中
  701. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  702. if ($order->status == 3) {
  703. $eo->orderStatus = 6;//跑腿配送中
  704. $eo->save();
  705. $order->sendStatus = 5;//跑腿配送中
  706. $order->save();
  707. }
  708. break;
  709. // 配送完成
  710. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  711. if ($order->status == 3) {
  712. $eo->orderStatus = 8;//配送完成
  713. $eo->save();
  714. $order->sendStatus = 2;//已送达
  715. $order->save();
  716. $params = ['staffId' => 0, 'staffName' => ''];
  717. OrderClass::confirmReach($order, $params);
  718. }
  719. break;
  720. // 商家取消订单
  721. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  722. //取消已发货,回滚到待发货
  723. if ($order->status == 3) {
  724. $eo->orderStatus = 2;
  725. $eo->save();
  726. $order->sendStatus = 3;
  727. $order->save();
  728. $params = ['staffId' => 0, 'staffName' => ''];
  729. OrderClass::cancelOrderSend($order, $params);
  730. }
  731. $msg = '取消配送,订单编号 ';
  732. break;
  733. // 配送方取消订单
  734. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
  735. //取消已发货,回滚到待发货
  736. if ($order->status == 3) {
  737. $eo->orderStatus = 3;
  738. $eo->status = 0;
  739. $eo->save();
  740. $order->sendStatus = 3;
  741. $order->save();
  742. $params = ['staffId' => 0, 'staffName' => ''];
  743. OrderClass::cancelOrderSend($order, $params);
  744. }
  745. $msg = '配送方取消配送,订单编号 ';
  746. break;
  747. // 配送员撤单
  748. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  749. //todo 配送员撤单,目前我们认为会重新派单,先不要有任何操作!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  750. $msg = '跑腿取消配送,订单编号 ';
  751. break;
  752. // 配送异常
  753. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  754. //取消已发货,回滚到待发货
  755. if ($order->status == 3) {
  756. $eo->orderStatus = 9;
  757. $eo->status = 0;
  758. $eo->save();
  759. $order->sendStatus = 3;
  760. $order->save();
  761. $params = ['staffId' => 0, 'staffName' => ''];
  762. OrderClass::cancelOrderSend($order, $params);
  763. }
  764. $msg = '订单配送异常,订单编号 ';
  765. break;
  766. }
  767. // ====================== 事务提交
  768. $tx->commit();
  769. if (!empty($msg)) {
  770. $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
  771. $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
  772. $result = $msg . $order->sendNum;
  773. WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
  774. }
  775. // 成功状态的返回数据
  776. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
  777. } catch (\Exception $e) {
  778. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  779. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  780. }
  781. }
  782. //模拟接口回调 ssh 20250826
  783. public function actionMockNotify()
  784. {
  785. if (getenv('YII_ENV') != 'production') {
  786. $post = Yii::$app->request->post();
  787. $orderStatus = $post['orderStatus'] ?? 0;
  788. $wxOrderId = $post['wxOrderId'] ?? '';
  789. $ptStyle = dict::getDict('ptStyle', 'hd');
  790. $merchant = WxOpenClass::getWxInfo();
  791. $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
  792. util::success($ret);
  793. }
  794. util::complete();
  795. }
  796. }