IntraCityController.php 32 KB

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