IntraCityController.php 32 KB

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