IntraCityController.php 33 KB

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