IntraCityController.php 33 KB

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