IntraCityController.php 32 KB

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