IntraCityController.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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, '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, '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, '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, '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. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  193. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  194. if ($shopExt['wxStoreId'] == '') {
  195. util::fail('微信门店编号为空');
  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 = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  241. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  242. if (empty($shopExt)) {
  243. util::fail("微信门店不存在");
  244. }
  245. $itemInfoList = OrderItemClass::getListBySn($sn);
  246. $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
  247. if (empty($itemInfoList)) {
  248. $orderType = 1;
  249. }
  250. $cargoName = '花材'; // 商品名称,默认是花材
  251. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  252. if (count($goodsInfoList) == 1) {
  253. $goodsInfo = $goodsInfoList[0];
  254. $cargoName = $goodsInfo['name'];
  255. } else {
  256. if ($orderType != 2) {
  257. util::fail("订单商品数量不正确");
  258. }
  259. }
  260. $cargo = [
  261. 'cargo_name' => $cargoName, // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  262. 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克
  263. 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
  264. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  265. 'cargo_num' => intval($post['packageNum'])
  266. ];
  267. $originalLng = doubleval($post['user_lng']);
  268. $originalLat = doubleval($post['user_lat']);
  269. $orderData = [
  270. //'out_store_id' => $shopId,
  271. 'wx_store_id' => $shopExt['wxStoreId'],
  272. 'user_name' => $post['user_name'],
  273. 'user_phone' => $post['user_phone'],
  274. 'user_lng' => $originalLng,
  275. 'user_lat' => $originalLat,
  276. 'user_address' => $post['user_address'],
  277. 'cargo' => $cargo,
  278. //'use_sandbox' => 1 // 如果不需要沙箱,use_sandbox就不传就好了 -- 踩坑人的经验
  279. //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1 // 根据环境变量判断是否使用沙盒环境 -- 没用,不生效
  280. ];
  281. $result = IntraCityExpress::preAddOrder($orderData);
  282. if ($result['errcode'] === 0) {
  283. util::success($result, "运费查询成功");
  284. } else {
  285. Yii::error("运费查询失败:" . json_encode($result));
  286. util::fail('运费查询失败' . json_encode($result));
  287. }
  288. }
  289. /**
  290. * 创建订单
  291. * POST /intra-city/create-order
  292. */
  293. public function actionCreateOrder()
  294. {
  295. try {
  296. $post = Yii::$app->request->post();
  297. $orderId = $post['orderId'];
  298. $order = OrderClass::getById($orderId);
  299. if (empty($order)) {
  300. util::fail('订单出错');
  301. }
  302. if ($order['mainId'] != $this->mainId) {
  303. util::fail('订单出错');
  304. }
  305. if ($order['repeat'] == 1) {
  306. util::fail('收款码订单不支持跑腿');
  307. }
  308. if ($order['forward'] == 1) {
  309. util::fail('售后付款单不支持跑腿');
  310. }
  311. $sn = $order['orderSn'];
  312. $itemInfoList = OrderItemClass::getListBySn($sn, 'id, name, cover, num');
  313. $itemList = [];
  314. $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
  315. if (empty($itemInfoList)) {
  316. $orderType = 1; // 花束订单
  317. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  318. $itemCount = 0;
  319. foreach ($goodsInfoList as $itemInfo) {
  320. $itemList[] = [
  321. 'item_name' => $itemInfo['name'],
  322. 'item_pic_url' => $itemInfo['bigCover'],
  323. 'count' => $itemInfo['num'],
  324. ];
  325. $itemCount += $itemInfo['num'];
  326. }
  327. $post['packageNum'] = $itemCount;
  328. } else {
  329. $itemCount = 0;
  330. foreach ($itemInfoList as $itemInfo) {
  331. $itemList[] = [
  332. 'item_name' => $itemInfo['name'],
  333. 'item_pic_url' => $itemInfo['bigCover'],
  334. 'count' => $itemInfo['num'],
  335. ];
  336. $itemCount += $itemInfo['num'];
  337. }
  338. $post['packageNum'] = $itemCount;
  339. }
  340. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  341. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  342. if (empty($shopExt)) {
  343. util::fail("微信门店不存在");
  344. }
  345. $cargoName = '花材'; // 商品名称,默认是花材
  346. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  347. if (count($goodsInfoList) == 1) {
  348. $goodsInfo = $goodsInfoList[0];
  349. $cargoName = $goodsInfo['name'];
  350. } else {
  351. if ($orderType != 2) {
  352. Yii::error('订单商品数量不正确');
  353. util::fail("订单商品数量不正确");
  354. }
  355. }
  356. // 通过 userId 获取 openid(小程序OpenId)
  357. $user = UserClass::getById($order['userId'], false, 'id, miniOpenId');
  358. if (empty($user)) {
  359. Yii::error('获取用户openId出错');
  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($post['packageNum']),
  367. 'cargo_price' => intval($order['actPrice'] * 100), // $order 中有各个价格,请注意
  368. 'item_list' => $itemList,
  369. ];
  370. //生成 store_order_id
  371. $storeOrderId = $orderId;
  372. if ($post['isNew'] == 0) { // 如果不是首次用 $orderId 创建快递配送,则要生成新 store_order_id
  373. // store_order_id 门店订单编号, 即 orderId。如果是重新配送的第n次,订单编号的命名规则为:orderId_copy_n
  374. $query = (new Query())
  375. ->from('xhExpressOrder')
  376. ->where(new \yii\db\Expression('storeOrderId LIKE CONCAT(:prefix, "%")', [':prefix' => $orderId . '_copy_%']));
  377. // $command = $query->createCommand();
  378. // $sql = $command->sql;
  379. $copyOrderCount = $query->count();
  380. $copyOrderCount += 1;
  381. $storeOrderId = $orderId . '_copy_' . $copyOrderCount;
  382. }
  383. $callbackUrl = Yii::$app->params['hdHost'] . '/intra-city/callback';
  384. $orderData = [
  385. 'wx_store_id' => $shopExt['wxStoreId'],
  386. 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
  387. 'user_openid' => $user['miniOpenId'],
  388. 'user_lng' => $post['user_lng'],
  389. 'user_lat' => $post['user_lat'],
  390. 'user_address' => $post['user_address'],
  391. 'user_name' => $post['user_name'],
  392. 'user_phone' => $post['user_phone'],
  393. 'order_seq' => $order['sendNum'], // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
  394. 'verify_code_type' => 0,
  395. 'order_detail_path' => '/admin/order/detail?id=' . $orderId, // TODO 使用花掌柜的地址,后期要重新选个地址
  396. 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
  397. //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 是否使用沙箱(非必传)
  398. 'cargo' => $cargo
  399. ];
  400. $result = IntraCityExpress::createOrder($orderData);
  401. if (isset($result['errcode']) && $result['errcode'] === 0) {
  402. OrderClass::updateById($orderId, ['sendStatus' => 1]); // 更新订单状态为配送中
  403. // 保存进 xhExpressOrder 表
  404. $orderData = [
  405. 'mainId' => $this->mainId,
  406. 'shopId' => $this->shopId,
  407. 'deliveryId' => isset($result['service_trans_id']) ? $result['service_trans_id'] : '',
  408. 'wxOrderId' => isset($result['wx_order_id']) ? $result['wx_order_id'] : '',
  409. 'wxStoreId' => isset($result['wx_store_id']) ? $result['wx_store_id'] : '',
  410. 'storeOrderId' => isset($result['store_order_id']) ? $result['store_order_id'] : '',
  411. 'transOrderId' => isset($result['trans_order_id']) ? $result['trans_order_id'] : '',
  412. 'distance' => isset($result['distance']) ? $result['distance'] : 0,
  413. 'fee' => isset($result['fee']) ? $result['fee'] : 0,
  414. 'fetchCode' => isset($result['fetch_code']) ? $result['fetch_code'] : '',
  415. 'orderSeq' => isset($result['order_seq']) ? $result['order_seq'] : ''
  416. ];
  417. ExpressOrderClass::add($orderData);
  418. util::success(['fee' => $result['fee']], '订单创建成功');
  419. } else {
  420. noticeUtil::push("门店 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
  421. Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  422. util::fail($result['errmsg'] ?? '订单创建失败', $result['errcode'] ?? -1);
  423. }
  424. } catch (\Exception $e) {
  425. Yii::error("订单创建异常:" . $e->getMessage(), 'intracity');
  426. util::fail("系统出错");
  427. }
  428. }
  429. /**
  430. * 查询订单
  431. * GET /intra-city/get-order
  432. */
  433. public function actionGetOrder()
  434. {
  435. try {
  436. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  437. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  438. if (empty($shopExt)) {
  439. util::fail("微信门店不存在");
  440. }
  441. $post = Yii::$app->request->post();
  442. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  443. $orderId = $post['orderId'];
  444. //$wxStoreId = isset($post['wx_store_id']) ? $post['wx_order_id'] : $shopExt['wxStoreId'];
  445. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  446. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  447. util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
  448. }
  449. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  450. if ($order['mainId'] != $this->mainId) {
  451. util::fail('订单未找到');
  452. }
  453. // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
  454. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  455. $query = (new Query())
  456. ->from('xhExpressOrder')
  457. ->where(['and',
  458. new \yii\db\Expression('storeOrderId LIKE CONCAT(:prefix, "%")', [':prefix' => $orderId . '_copy_']),
  459. ['status' => 1]
  460. ])->orderBy('addTime DESC');
  461. $esDatas = $query->all();
  462. $count = count($esDatas);
  463. if ($count > 0) {
  464. $es = $esDatas[0];
  465. $storeOrderId = $es['storeOrderId'];
  466. if ($count > 1) {
  467. noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $orderId . ',wx_store_id:' . $wxStoreId);
  468. }
  469. }
  470. $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
  471. if (isset($result['errcode']) && $result['errcode'] === 0) {
  472. util::success($result, "查询成功");
  473. } else {
  474. Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  475. util::fail('订单查询失败: ' . $result['errcode']);
  476. }
  477. } catch (\Exception $e) {
  478. Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
  479. util::fail("系统出错");
  480. }
  481. }
  482. /**
  483. * 取消订单
  484. * POST /intra-city/cancel-order
  485. */
  486. public function actionCancelOrder()
  487. {
  488. try {
  489. $post = Yii::$app->request->post();
  490. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  491. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  492. if (empty($shopExt)) {
  493. util::fail("微信门店不存在");
  494. }
  495. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  496. $orderId = $post['orderId']; //配送订单创建成功后,也会返回的 store_order_id。 即 orderId
  497. //$wxStoreId = isset($post['wx_store_id']) ? $post['wx_order_id'] : $shopExt['wxStoreId'];
  498. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  499. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  500. util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
  501. }
  502. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  503. if ($order['mainId'] != $this->mainId) {
  504. util::fail('订单未找到');
  505. }
  506. if ($order['sendStatus'] != 1) {
  507. util::fail('配送单状态不是配送中');
  508. }
  509. // 检查是否存在重复的订单,如果存在,则使用最后一个订单的 store_order_id
  510. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  511. $query = (new Query())
  512. ->from('xhExpressOrder')
  513. ->where(['and',
  514. new \yii\db\Expression('storeOrderId LIKE CONCAT(:prefix, "%")', [':prefix' => $orderId . '_copy_']),
  515. ['status' => 1]
  516. ])->orderBy('addTime DESC');
  517. // $command = $query->createCommand();
  518. // $sql = $command->sql;
  519. $esDatas = $query->all();
  520. $count = count($esDatas);
  521. if ($count > 0) {
  522. $es = $esDatas[0];
  523. $storeOrderId = $es['storeOrderId'];
  524. if ($count > 1) {
  525. noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $orderId . ',wx_store_id:' . $wxStoreId);
  526. }
  527. }
  528. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  529. if (isset($result['errcode']) && $result['errcode'] === 0) {
  530. // 更新订单状态
  531. OrderClass::updateById($orderId, ['sendStatus' => OrderClass::ORDER_STATUS_CANCEL]);//设置为取消状态
  532. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true);
  533. if (!empty($eo)) {
  534. $eo->status = ExpressOrder::STATUS_CANCELED;
  535. $eo->cancelTime = date('Y-m-d H:i:s');
  536. $eo->deductfee = $result['deductfee'];
  537. $eo->save();
  538. }
  539. util::success($result, "订单取消成功");
  540. } else {
  541. if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
  542. // 更新订单状态
  543. OrderClass::updateById($orderId, ['sendStatus' => OrderClass::ORDER_STATUS_CANCEL]);//设置为取消状态
  544. util::success($result, "订单取消成功");
  545. }
  546. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  547. util::fail('订单取消失败: ' . $result['errcode']);
  548. }
  549. } catch (\Exception $e) {
  550. Yii::error("订单取消异常:" . $e->getMessage(), 'intracity');
  551. util::fail("系统出错");
  552. }
  553. }
  554. /**
  555. * 获取订单列表
  556. * GET /intra-city/order-list
  557. */
  558. public function actionOrderList()
  559. {
  560. }
  561. /**
  562. * 微信回调接口
  563. * POST /intra-city/callback
  564. */
  565. public function actionCallback()
  566. {
  567. try {
  568. $callbackData = Yii::$app->request->post();
  569. if (empty($callbackData)) {
  570. $postStr = file_get_contents('php://input');
  571. // 处理转义字符,将JSON字符串正确解析为数组
  572. $postStr = stripslashes($postStr);
  573. $callbackData = json_decode($postStr, true);
  574. if (empty($callbackData)) {
  575. util::fail('回调请求的数据为空');
  576. }
  577. }
  578. // 从配置中获取安全token
  579. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  580. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  581. // 记录回调日志
  582. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  583. $storeOrderId = isset($callbackData['store_order_id']) ? $callbackData['store_order_id'] : 0;
  584. $wxStoreId = $callbackData['wx_store_id'];
  585. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  586. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  587. if (empty($eo)) {
  588. Yii::error('订单不存在.store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  589. echo Json::encode([
  590. 'return_code' => 1,
  591. 'return_msg' => '系统错误'
  592. ]);
  593. exit();
  594. }
  595. // 从 $storeOrderId 提取 orderId
  596. $arr = explode('_', $storeOrderId);
  597. $orderId = intval($arr[0]);
  598. $orderStatus = intval($callbackData['order_status']);
  599. switch ($orderStatus) {
  600. // 订单创建成功
  601. case IntraCityExpress::ORDER_STATUS_CREATED:
  602. $eo->orderStatus = ExpressOrder::ORDER_STATUS_CREATED;
  603. $eo->status = ExpressOrder::STATUS_CREATED;
  604. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  605. OrderClass::updateById($orderId, ['status' => OrderClass::ORDER_STATUS_SENDING, 'sendStatus' => OrderClass::SEND_STATUS_SENDING]);
  606. break;
  607. // 商家取消订单
  608. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  609. $eo->orderStatus = ExpressOrder::ORDER_STATUS_CANCELED_BY_MERCHANT;
  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_CANCELED_BY_DELIVERY:
  615. $eo->orderStatus = ExpressOrder::ORDER_STATUS_CANCELED_BY_DELIVERY;
  616. $eo->status = ExpressOrder::STATUS_CANCELED;
  617. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
  618. OrderClass::updateById($orderId, ['status' => OrderClass::ORDER_STATUS_UN_SEND, 'sendStatus' => OrderClass::SEND_STATUS_CANCEL]);
  619. break;
  620. // 配送员接单
  621. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  622. $eo->orderStatus = ExpressOrder::ORDER_STATUS_ACCEPTED;
  623. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  624. OrderClass::updateById($orderId, ['status' => OrderClass::ORDER_STATUS_SENDING, 'sendStatus' => OrderClass::SEND_STATUS_SENDING]); //订单创建时已执行了,这儿重复更新
  625. break;
  626. // 配送员到店
  627. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  628. $eo->orderStatus = ExpressOrder::ORDER_STATUS_ARRIVED;
  629. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  630. OrderClass::updateById($orderId, ['status' => OrderClass::ORDER_STATUS_SENDING, 'sendStatus' => OrderClass::SEND_STATUS_SENDING]); //订单创建时已执行了,这儿重复更新
  631. break;
  632. // 配送中
  633. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  634. $eo->orderStatus = ExpressOrder::ORDER_STATUS_DELIVERING;
  635. break;
  636. // 配送员撤单
  637. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  638. $eo->orderStatus = ExpressOrder::ORDER_STATUS_WITHDRAWN;
  639. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
  640. OrderClass::updateById($orderId, ['status' => OrderClass::ORDER_STATUS_UN_SEND, 'sendStatus' => OrderClass::SEND_STATUS_UNSEND]);
  641. break;
  642. // 配送完成
  643. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  644. $eo->orderStatus = ExpressOrder::ORDER_STATUS_COMPLETED;
  645. $eo->status = ExpressOrder::STATUS_COMPLETED;
  646. // 更新 xhOrder 表的订单状态与配送状态 -- 已完成|已送达
  647. OrderClass::updateById($orderId, ['status' => OrderClass::ORDER_STATUS_COMPLETE, 'sendStatus' => OrderClass::SEND_STATUS_COMPLETED]);
  648. break;
  649. // 配送异常
  650. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  651. $eo->orderStatus = ExpressOrder::ORDER_STATUS_EXCEPTION;
  652. noticeUtil::push('同城配送异常 --- store_order_id(orderId):' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
  653. break;
  654. }
  655. $re = $eo->save();
  656. if (!$re) {
  657. noticeUtil::push('同城配送回调更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  658. Yii::error('更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  659. $re = [
  660. 'return_code' => 0,
  661. 'return_msg' => 'OK'
  662. ];
  663. echo Json::encode($re);
  664. exit();
  665. }
  666. $result = [
  667. 'return_code' => 0,
  668. 'return_msg' => 'OK'
  669. ];
  670. echo Json::encode($result);
  671. exit();
  672. } catch (\Exception $e) {
  673. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  674. echo Json::encode([
  675. 'return_code' => 1,
  676. 'return_msg' => '系统错误'
  677. ]);
  678. exit();
  679. }
  680. }
  681. }