IntraCityController.php 34 KB

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