IntraCityController.php 32 KB

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