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