IntraCityController.php 31 KB

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