IntraCityController.php 33 KB

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