IntraCityController.php 33 KB

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