IntraCityController.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. <?php
  2. namespace hd\controllers;
  3. use bizHd\express\classes\ExpressOrderClass;
  4. use bizHd\order\classes\OrderClass;
  5. use bizHd\order\classes\OrderGoodsClass;
  6. use bizHd\order\classes\OrderItemClass;
  7. use bizHd\shop\classes\MainClass;
  8. use bizHd\user\classes\UserClass;
  9. use bizHd\wx\classes\WxOpenClass;
  10. use common\components\dict;
  11. use common\components\noticeUtil;
  12. use common\components\util;
  13. use hd\models\IntraCity\StoreFeeForm;
  14. use Yii;
  15. use biz\shop\classes\ShopClass;
  16. use yii\helpers\Json;
  17. use common\components\IntraCityExpress;
  18. use yii\db\Query;
  19. use biz\wx\classes\WxMessageClass;
  20. /**
  21. * 同城配送控制器
  22. *
  23. * 提供同城配送相关的API接口
  24. */
  25. class IntraCityController extends BaseController
  26. {
  27. public $guestAccess = ['callback'];
  28. /**
  29. * 创建门店
  30. * POST /intra-city/create-store
  31. */
  32. public function actionCreateStore()
  33. {
  34. try {
  35. $shop = $this->shop;
  36. $shopName = $shop->shopName ?? '';
  37. $sjName = $shop->merchantName ?? '';
  38. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  39. $adminId = $this->adminId;
  40. util::checkRepeatCommit($adminId, 4);
  41. $storeData = [
  42. 'out_store_id' => $this->mainId, //自定义门店编号 -- 从 shopId 改为 dmainId
  43. 'store_name' => $name,
  44. 'address_info' => [
  45. 'province' => $shop->province,
  46. 'city' => $shop->city,
  47. 'area' => $shop->dist,
  48. 'street' => '',
  49. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  50. 'lat' => $shop->lat,
  51. 'lng' => $shop->long,
  52. 'phone' => $shop->telephone
  53. ]
  54. ];
  55. // 验证必填参数
  56. $requiredFields = ['out_store_id', 'store_name', 'address_info'];
  57. foreach ($requiredFields as $field) {
  58. if (empty($storeData[$field])) {
  59. util::fail("缺少必填参数:{$field}");
  60. }
  61. }
  62. // 创建门店前,检查是否已经 开通门店权限 (有wxStoreId,即说明开通了)
  63. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true, false, 'id, wxStoreId');
  64. $shopExt = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  65. // 查询是否存在 wx_store_id,不存在则执行apply
  66. if ($shopExt->wxStoreId == '') {
  67. $re = IntraCityExpress::applyStore();
  68. if (!is_array($re)) {
  69. $re = Json::decode($re, true);
  70. }
  71. if ($re['errcode'] != 0) {
  72. Yii::error("开通门店权限失败:" . $re['errmsg']);
  73. util::fail('开通门店权限失败');
  74. }
  75. }
  76. $result = IntraCityExpress::createStore($storeData);
  77. if ($result['errcode'] === 0) {
  78. // 保存微信门店编号(wx_store_id)
  79. $shopExt->wxStoreId = $result['wx_store_id'];
  80. $shopExt->save();
  81. util::success($result, "门店创建成功");
  82. } else {
  83. Yii::error("门店创建失败:" . $result['errmsg']);
  84. util::fail($result['errmsg']);
  85. }
  86. } catch (\Exception $e) {
  87. Yii::error("门店创建失败:" . $e->getMessage());
  88. util::fail("系统出错");
  89. }
  90. }
  91. /**
  92. * 查询门店创建情况
  93. */
  94. public function actionStore()
  95. {
  96. $shopId = $this->shopId;
  97. // 首先从门店扩展表查询是否已经创建
  98. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true, false, 'id, wxStoreId');
  99. $shopExt = MainClass::getById($this->mainId, true, 'id, wxStoreId');
  100. if ($shopExt->wxStoreId == '') { // 不存在,则从微信接口查询
  101. $result = IntraCityExpress::getStore($this->mainId);
  102. if ($result['errcode'] === 0) {
  103. $store = $result['store_list'][0];
  104. // 保存 wx_store_id
  105. $shopExt->wxStoreId = $store['wx_store_id'];
  106. $shopExt->save();
  107. util::success($store, "门店查询成功");
  108. } else {
  109. Yii::error("门店查询失败:" . $result['errmsg']);
  110. util::fail('门店查询失败');
  111. }
  112. } else {
  113. $field = 'province, city, dist, lat, long, floor, address';
  114. $shop = ShopClass::getById($shopId, false, $field);
  115. $data = array_merge($shop, $shopExt->toArray());
  116. util::success($data, "门店查询成功");
  117. }
  118. }
  119. /**
  120. * 更新门店
  121. */
  122. public function actionUpdateStore()
  123. {
  124. // 首先从门店扩展表查询是否已经创建
  125. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  126. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  127. if ($shopExt['wxStoreId'] == '') {
  128. util::fail('未创建门店,请先创建');
  129. }
  130. $adminId = $this->adminId;
  131. util::checkRepeatCommit($adminId, 4);
  132. $shop = $this->shop;
  133. $shopName = $shop->shopName ?? '';
  134. $sjName = $shop->merchantName ?? '';
  135. $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  136. $storeData = [
  137. 'keys' => ['wx_store_id' => $shopExt['wxStoreId']],
  138. 'content' => [
  139. 'store_name' => $name,
  140. 'address_info' => [
  141. 'province' => $shop->province,
  142. 'city' => $shop->city,
  143. 'area' => $shop->dist,
  144. 'street' => '',
  145. 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
  146. 'lat' => $shop->lat,
  147. 'lng' => $shop->long,
  148. 'phone' => $shop->telephone
  149. ],
  150. //"order_pattern" => 2,
  151. //"service_trans_prefer" => "SFTC" //order_pattern = 2时必填
  152. ]
  153. ];
  154. $result = IntraCityExpress::updateStore($storeData);
  155. if ($result['errcode'] === 0) {
  156. util::success($result, "门店更新成功");
  157. } else {
  158. Yii::error("门店更新失败:" . $result['errmsg']);
  159. util::fail($result['errmsg']);
  160. //util::fail('门店更新失败');
  161. }
  162. }
  163. /**
  164. * 门店运费充值
  165. */
  166. public function actionStoreCharge()
  167. {
  168. $post = Yii::$app->request->post();
  169. $amount = floatval($post['amount']);
  170. $amountTurnFen = $amount * 100;
  171. if ($amountTurnFen < 5000) {
  172. util::fail('50元起充');
  173. }
  174. $expressId = $post['expressId'];
  175. $serviceTransIds = ['SFTC', 'DADA'];
  176. if (!in_array($expressId, $serviceTransIds)) {
  177. util::fail('快递动力ID出错');
  178. }
  179. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  180. $shopExt = MainClass::getById($this->mainId, 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. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  199. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  200. if ($shopExt['wxStoreId'] == '') {
  201. util::fail('微信门店编号为空');
  202. }
  203. $wxStoreId = $shopExt['wxStoreId'];
  204. $result = IntraCityExpress::getBalance($wxStoreId);
  205. if ($result['errcode'] === 0) {
  206. $data = ['all_balance' => $result['all_balance'] / 100.0];
  207. foreach ($result['balance_detail'] as $item) {
  208. if ($item['service_trans_id'] == 'DADA') {
  209. $data['dada_balance'] = $item['balance'] / 100.0;
  210. }
  211. if ($item['service_trans_id'] == 'SFTC') {
  212. $data['sf_balance'] = $item['balance'] / 100.0;
  213. }
  214. }
  215. util::success($data, "门店余额查询成功");
  216. } else {
  217. Yii::error("门店余额查询失败:" . $result['errmsg']);
  218. util::fail('门店余额查询失败');
  219. }
  220. }
  221. /**
  222. * 查询运费
  223. */
  224. public function actionStoreFee()
  225. {
  226. $post = Yii::$app->request->post();
  227. // 创建表单验证模型
  228. $form = new StoreFeeForm();
  229. $form->setScenario('store_fee');
  230. $form->load($post, ''); // 直接从 post 数据加载,不使用模型名作为前缀
  231. // 执行表单验证
  232. $form->validateForm();
  233. $orderId = $post['orderId'];
  234. $order = OrderClass::getById($orderId);
  235. if (empty($order)) {
  236. util::fail('订单出错');
  237. }
  238. if ($order['mainId'] != $this->mainId) {
  239. util::fail('不是你的订单哈。');
  240. }
  241. $sn = $order['orderSn'];
  242. $shopId = intval($this->shopId);
  243. if (empty($shopId)) {
  244. util::fail("门店不存在");
  245. }
  246. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  247. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  248. if (empty($shopExt)) {
  249. util::fail("微信门店不存在");
  250. }
  251. $itemInfoList = OrderItemClass::getListBySn($sn);
  252. $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
  253. if (empty($itemInfoList)) {
  254. $orderType = 1;
  255. }
  256. $cargoName = '花材'; // 商品名称,默认是花材
  257. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  258. if (count($goodsInfoList) == 1) {
  259. $goodsInfo = $goodsInfoList[0];
  260. $cargoName = $goodsInfo['name'];
  261. } else {
  262. if ($orderType != 2) {
  263. util::fail("订单商品数量不正确");
  264. }
  265. }
  266. $cargo = [
  267. 'cargo_name' => $cargoName, // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  268. 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克
  269. 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
  270. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  271. 'cargo_num' => intval($post['packageNum'])
  272. ];
  273. $originalLng = doubleval($post['user_lng']);
  274. $originalLat = doubleval($post['user_lat']);
  275. $orderData = [
  276. //'out_store_id' => $shopId,
  277. 'wx_store_id' => $shopExt['wxStoreId'],
  278. 'user_name' => $post['user_name'],
  279. 'user_phone' => $post['user_phone'],
  280. 'user_lng' => $originalLng,
  281. 'user_lat' => $originalLat,
  282. 'user_address' => $post['user_address'],
  283. 'cargo' => $cargo,
  284. //'use_sandbox' => 1 // 如果不需要沙箱,use_sandbox就不传就好了 -- 踩坑人的经验
  285. //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1 // 根据环境变量判断是否使用沙盒环境 -- 没用,不生效
  286. ];
  287. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  288. $result = IntraCityExpress::preAddOrder($orderData);
  289. if ($result['errcode'] === 0) {
  290. util::success($result, "查询成功");
  291. } else {
  292. Yii::error("运费查询失败:" . json_encode($result));
  293. util::fail('运费查询失败' . json_encode($result));
  294. }
  295. }
  296. /**
  297. * 创建订单
  298. * POST /intra-city/create-order
  299. */
  300. public function actionCreateOrder()
  301. {
  302. try {
  303. $post = Yii::$app->request->post();
  304. $adminId = $this->adminId;
  305. util::checkRepeatCommit($adminId, 4);
  306. $orderId = intval($post['orderId']);
  307. $field = 'mainId, status, sendStatus, repeat, forward, orderSn, userId, actPrice, sendNum, salt';
  308. $order = OrderClass::getById($orderId, false, $field);
  309. if (empty($order)) {
  310. util::fail('没有找到订单');
  311. }
  312. if ($order['mainId'] != $this->mainId) {
  313. util::fail('不是你的订单');
  314. }
  315. // 不能创建配送的几种订单状态
  316. if ($order['status'] != 2) {
  317. util::fail('已不能叫跑腿,请刷新页面哈');
  318. }
  319. // 不能创建配送的几种配送状态
  320. $notCanCreateSendStatus = [-1, 3];
  321. if (!in_array($order['sendStatus'], $notCanCreateSendStatus)) {
  322. util::fail('已不能叫跑腿,请刷新页面');
  323. }
  324. if ($order['repeat'] == 1) {
  325. util::fail('收款码订单不支持跑腿');
  326. }
  327. if ($order['forward'] == 1) {
  328. util::fail('售后付款单不支持跑腿');
  329. }
  330. $sn = $order['orderSn'];
  331. $salt = $order['salt'] ?? "";
  332. $itemInfoList = OrderItemClass::getListBySn($sn, 'id, name, cover, num');
  333. $itemList = [];
  334. $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
  335. if (empty($itemInfoList)) {
  336. $orderType = 1; // 花束订单
  337. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  338. $itemCount = 0;
  339. foreach ($goodsInfoList as $itemInfo) {
  340. $itemList[] = [
  341. 'item_name' => $itemInfo['name'],
  342. 'item_pic_url' => $itemInfo['bigCover'],
  343. 'count' => intval($itemInfo['num']),
  344. ];
  345. $itemCount += $itemInfo['num'];
  346. }
  347. $post['packageNum'] = $itemCount;
  348. } else {
  349. $itemCount = 0;
  350. foreach ($itemInfoList as $itemInfo) {
  351. $itemList[] = [
  352. 'item_name' => $itemInfo['name'],
  353. 'item_pic_url' => $itemInfo['bigCover'],
  354. 'count' => intval($itemInfo['num']),
  355. ];
  356. $itemCount += $itemInfo['num'];
  357. }
  358. $post['packageNum'] = $itemCount;
  359. }
  360. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  361. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  362. if (empty($shopExt)) {
  363. util::fail("微信门店不存在");
  364. }
  365. $cargoName = '花材'; // 商品名称,默认是花材
  366. $goodsInfoList = OrderGoodsClass::getListBySn($sn);
  367. if (count($goodsInfoList) == 1) {
  368. $goodsInfo = $goodsInfoList[0];
  369. $cargoName = $goodsInfo['name'];
  370. } else {
  371. if ($orderType != 2) {
  372. Yii::error('订单商品数量不正确');
  373. util::fail("订单商品数量不正确");
  374. }
  375. }
  376. // 通过 userId 获取 openid(小程序OpenId)
  377. $user = UserClass::getById($order['userId'], false, 'id, miniOpenId');
  378. if (empty($user)) {
  379. util::fail('用户信息缺失');
  380. }
  381. $miniOpenId = $user['miniOpenId'] ?? '';
  382. if (empty($miniOpenId)) {
  383. util::fail('没有找到用户的微信数据');
  384. }
  385. $cargo = [
  386. 'cargo_name' => $cargoName,
  387. 'cargo_weight' => intval($post['weight'] * 1000),
  388. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  389. 'cargo_num' => intval($post['packageNum']),
  390. 'cargo_price' => intval($order['actPrice'] * 100), // $order 中有各个价格,请注意
  391. 'item_list' => $itemList,
  392. ];
  393. //生成 store_order_id,加统一后缀,避免线上线下ID命中
  394. $storeOrderId = $orderId . '_exp';
  395. if ($order['sendStatus'] == 3) { // 如果不是首次用 $orderId 创建快递配送,则要生成新 store_order_id
  396. // store_order_id 门店订单编号, 即 orderId。如果是重新配送的第n次,订单编号的命名规则为:orderId_cp_n
  397. $query = (new Query())
  398. ->from('xhExpressOrder')
  399. ->where(['orderId' => $orderId]);
  400. // $command = $query->createCommand();
  401. // $sql = $command->sql;
  402. $copyOrderCount = $query->count();
  403. $copyOrderCount += 1;
  404. //区分线上线下
  405. if (getenv('YII_ENV') == 'production') {
  406. $storeOrderId = $storeOrderId . '_cp_' . $copyOrderCount;
  407. } else {
  408. $storeOrderId = $storeOrderId . '_cs_cp_' . $copyOrderCount;
  409. }
  410. }
  411. $callbackUrl = Yii::$app->params['hdHost'] . '/intra-city/callback';
  412. $orderData = [
  413. 'wx_store_id' => $shopExt['wxStoreId'],
  414. 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
  415. 'user_openid' => $miniOpenId,
  416. 'user_lng' => $post['user_lng'],
  417. 'user_lat' => $post['user_lat'],
  418. 'user_address' => $post['user_address'],
  419. 'user_name' => $post['user_name'],
  420. 'user_phone' => $post['user_phone'],
  421. 'order_seq' => $order['sendNum'], // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
  422. 'verify_code_type' => 0,
  423. 'order_detail_path' => '/admin/order/info?id=' . $orderId . '&salt=' . $salt,
  424. 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
  425. //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 是否使用沙箱(非必传)
  426. 'cargo' => $cargo
  427. ];
  428. $result = IntraCityExpress::createOrder($orderData);
  429. if (isset($result['errcode']) && $result['errcode'] === 0) {
  430. $deliveryId = $result['service_trans_id'] ?? '';
  431. // 更新订单状态为配送中,已呼叫小哥,等小哥接单;有可能到店自取的转跑腿,sendType要变化
  432. OrderClass::updateById($orderId, ['sendStatus' => 0, 'status' => 3, 'deliveryId' => $deliveryId, 'sendType' => 2]);
  433. // 保存进 xhExpressOrder 表
  434. $orderData = [
  435. 'mainId' => $this->mainId,
  436. 'shopId' => $this->shopId,
  437. 'deliveryId' => $deliveryId,
  438. 'wxOrderId' => $result['wx_order_id'] ?? '',
  439. 'wxStoreId' => $result['wx_store_id'] ?? '',
  440. 'storeOrderId' => $result['store_order_id'] ?? '',
  441. 'orderId' => $orderId,
  442. 'transOrderId' => $result['trans_order_id'] ?? '',
  443. 'distance' => $result['distance'] ?? 0,
  444. 'fee' => $result['fee'] ?? 0,
  445. 'fetchCode' => $result['fetch_code'] ?? '',
  446. 'orderSeq' => $result['order_seq'] ?? ''
  447. ];
  448. ExpressOrderClass::add($orderData);
  449. util::success(['fee' => $result['fee']], '订单创建成功');
  450. } else {
  451. noticeUtil::push("门店 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
  452. Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  453. $errorMsg = $result['errmsg'] ?? '';
  454. noticeUtil::push("跑腿单创建失败:" . $errorMsg, '15280215347');
  455. util::fail('提交失败,请确认余额是否充足');
  456. }
  457. } catch (\Exception $e) {
  458. Yii::error("订单创建异常:" . $e->getMessage(), 'intracity');
  459. util::fail("系统出错");
  460. }
  461. }
  462. /**
  463. * 查询订单
  464. * GET /intra-city/get-order
  465. */
  466. public function actionGetOrder()
  467. {
  468. try {
  469. //$shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], false, false, 'id, wxStoreId');
  470. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  471. if (empty($shopExt)) {
  472. util::fail("微信门店不存在");
  473. }
  474. $post = Yii::$app->request->post();
  475. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  476. $orderId = $post['orderId'];
  477. //$wxStoreId = isset($post['wx_store_id']) ? $post['wx_order_id'] : $shopExt['wxStoreId'];
  478. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  479. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  480. util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
  481. }
  482. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  483. if ($order['mainId'] != $this->mainId) {
  484. util::fail('不是你的订单!');
  485. }
  486. // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
  487. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  488. $query = (new Query())
  489. ->from('xhExpressOrder')
  490. ->where(['orderId' => $orderId])
  491. ->andWhere(['status' => 1])
  492. ->orderBy('addTime DESC');
  493. $esDatas = $query->all();
  494. $count = count($esDatas);
  495. if ($count > 0) {
  496. $es = $esDatas[0];
  497. $storeOrderId = $es['storeOrderId'];
  498. if ($count > 1) {
  499. noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $orderId . ',wx_store_id:' . $wxStoreId);
  500. }
  501. }
  502. $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
  503. if (isset($result['errcode']) && $result['errcode'] === 0) {
  504. util::success($result, "查询成功");
  505. } else {
  506. Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  507. util::fail('订单查询失败: ' . $result['errcode']);
  508. }
  509. } catch (\Exception $e) {
  510. Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
  511. util::fail("系统出错");
  512. }
  513. }
  514. /**
  515. * 取消订单
  516. * POST /intra-city/cancel-order
  517. */
  518. public function actionCancelOrder()
  519. {
  520. try {
  521. $post = Yii::$app->request->post();
  522. $adminId = $this->adminId;
  523. util::checkRepeatCommit($adminId, 4);
  524. $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  525. if (empty($main)) {
  526. util::fail("微信门店不存在");
  527. }
  528. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  529. $orderId = $post['orderId']; //配送订单创建成功后,也会返回的 store_order_id。 即 orderId
  530. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $main['wxStoreId'];
  531. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  532. util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
  533. }
  534. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  535. if ($order['mainId'] != $this->mainId) {
  536. util::fail('订单未找到');
  537. }
  538. if ($order['sendStatus'] != 1 && $order['sendStatus'] != 0) {
  539. util::fail('不能取消,请刷新页面');
  540. }
  541. // 检查是否存在重复的订单,如果存在,则使用最后一个订单的 store_order_id
  542. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  543. $query = (new Query())
  544. ->from('xhExpressOrder')
  545. ->where(['orderId' => $orderId])
  546. ->andWhere(['status' => 1])
  547. ->orderBy('addTime DESC');
  548. // $command = $query->createCommand();
  549. // $sql = $command->sql;
  550. $esDatas = $query->all();
  551. $count = count($esDatas);
  552. if ($count > 0) {
  553. $es = $esDatas[0];
  554. $storeOrderId = $es['storeOrderId'];
  555. if ($count > 1) {
  556. noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $orderId . ',wx_store_id:' . $wxStoreId);
  557. }
  558. }
  559. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  560. if (isset($result['errcode']) && $result['errcode'] === 0) {
  561. // 更新订单状态
  562. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  563. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true);
  564. if (!empty($eo)) {
  565. $eo->status = 3;
  566. $eo->cancelTime = date('Y-m-d H:i:s');
  567. $eo->deductfee = $result['deductfee'];
  568. $eo->save();
  569. }
  570. util::success($result, "订单取消成功");
  571. } else {
  572. if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
  573. // 更新订单状态
  574. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  575. util::success($result, "订单取消成功");
  576. }
  577. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  578. util::fail('订单取消失败: ' . $result['errcode']);
  579. }
  580. } catch (\Exception $e) {
  581. Yii::error("订单取消异常:" . $e->getMessage(), 'intracity');
  582. util::fail("系统出错");
  583. }
  584. }
  585. /**
  586. * 获取订单列表
  587. * GET /intra-city/order-list
  588. */
  589. public function actionOrderList()
  590. {
  591. }
  592. /**
  593. * 微信回调接口
  594. * POST /intra-city/callback
  595. */
  596. public function actionCallback()
  597. {
  598. $callbackData = Yii::$app->request->post();
  599. if (empty($callbackData)) {
  600. $postStr = file_get_contents('php://input');
  601. // 处理转义字符,将JSON字符串正确解析为数组
  602. $postStr = stripslashes($postStr);
  603. $callbackData = json_decode($postStr, true);
  604. if (empty($callbackData)) {
  605. util::fail('回调请求的数据为空');
  606. }
  607. }
  608. // 从配置中获取安全token
  609. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  610. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  611. // 记录回调日志
  612. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
  613. $storeOrderId = $callbackData['store_order_id'] ?? 0;
  614. $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
  615. if (empty($storeOrderId) || empty($wxStoreId)) {
  616. return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
  617. }
  618. try {
  619. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  620. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  621. if (empty($eo)) {
  622. Yii::error('订单不存在.store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  623. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  624. }
  625. // 从 $storeOrderId 提取 orderId
  626. $arr = explode('_', $storeOrderId);
  627. $orderId = intval($arr[0]);
  628. if ($orderId == 0) {
  629. Yii::error('订单号为0. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  630. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  631. }
  632. $tx = Yii::$app->db->beginTransaction(); // ====================== 开启事务
  633. $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
  634. $orderStatus = intval($callbackData['order_status']);
  635. switch ($orderStatus) {
  636. // 订单创建成功
  637. case IntraCityExpress::ORDER_STATUS_CREATED:
  638. $eo->orderStatus = 1;
  639. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  640. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 0]);
  641. break;
  642. // 商家取消订单
  643. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  644. $eo->orderStatus = 2;
  645. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
  646. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  647. $msg = '取消配送,订单编号 ';
  648. break;
  649. // 配送方取消订单
  650. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
  651. $eo->orderStatus = 3;
  652. $eo->status = 0;
  653. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
  654. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  655. $msg = '配送方取消配送,订单编号 ';
  656. break;
  657. // 配送员接单
  658. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  659. $eo->orderStatus = 4;
  660. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  661. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 1]); //订单创建时已执行了,这儿重复更新
  662. break;
  663. // 配送员到店
  664. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  665. $eo->orderStatus = 5;
  666. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  667. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 4]); //订单创建时已执行了,这儿重复更新
  668. break;
  669. // 配送中
  670. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  671. $eo->orderStatus = 6;
  672. OrderClass::updateById($orderId, ['sendStatus' => 5]);
  673. break;
  674. // 配送员撤单
  675. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  676. $eo->orderStatus = 7;
  677. $eo->status = 0;
  678. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
  679. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  680. $msg = '跑腿取消配送,订单编号 ';
  681. break;
  682. // 配送完成
  683. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  684. $eo->orderStatus = 8;
  685. // 更新 xhOrder 表的订单状态与配送状态 -- 已完成|已送达
  686. OrderClass::updateById($orderId, ['status' => 4, 'sendStatus' => 2]);
  687. break;
  688. // 配送异常
  689. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  690. $eo->orderStatus = 9;
  691. $eo->status = 0;
  692. noticeUtil::push('同城配送异常 --- store_order_id(orderId):' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
  693. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
  694. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  695. $msg = '订单配送异常,订单编号 ';
  696. break;
  697. }
  698. if ($msg != '') { // $msg 不为空,则发通知
  699. $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
  700. $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
  701. $result = $msg . $order->sendNum;
  702. WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
  703. }
  704. $re = $eo->save();
  705. if (!$re) {
  706. noticeUtil::push('同城配送回调更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  707. Yii::error('更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  708. $tx->rollBack(); // ====================== 事务回滚
  709. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  710. }
  711. $tx->commit(); // ====================== 事务提交
  712. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']); // 成功状态的返回数据
  713. } catch (\Exception $e) {
  714. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  715. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  716. }
  717. }
  718. //模拟接口回调 ssh 20250826
  719. public function actionMockNotify()
  720. {
  721. if (getenv('YII_ENV') != 'production') {
  722. $post = Yii::$app->request->post();
  723. $orderStatus = $post['orderStatus'] ?? 0;
  724. $wxOrderId = $post['wxOrderId'] ?? '';
  725. $ptStyle = dict::getDict('ptStyle', 'hd');
  726. $merchant = WxOpenClass::getWxInfo();
  727. $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
  728. util::success($ret);
  729. }
  730. util::complete();
  731. }
  732. }