IntraCityController.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. /**
  287. * 创建订单
  288. * POST /intra-city/create-order
  289. */
  290. public function actionCreateOrder()
  291. {
  292. try {
  293. $post = Yii::$app->request->post();
  294. $orderId = intval($post['orderId']);
  295. $order = OrderClass::getById($orderId);
  296. if (empty($order)) {
  297. util::fail('订单出错');
  298. }
  299. if ($order['mainId'] != $this->mainId) {
  300. util::fail('订单出错');
  301. }
  302. $sn = $order['orderSn'];
  303. $itemInfoList = OrderItemClass::getAllByCondition(['orderSn'=>$sn], null,'id, name, cover, num');
  304. $itemList = [];
  305. $itemCount = 0;
  306. foreach ($itemInfoList as $itemInfo) {
  307. $itemList[] = [
  308. 'item_name' => $itemInfo['name'],
  309. 'item_pic_url' => imgUtil::groupImg($itemInfo['cover']) . "?x-oss-process=image/resize,m_fill,h_130,w_130",
  310. 'count' => intval($itemInfo['num']),
  311. ];
  312. $itemCount += intval($itemInfo['num']);
  313. }
  314. $post['packageNum'] = $itemCount;
  315. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  316. if (empty($shopExt)) {
  317. util::fail("微信门店不存在");
  318. }
  319. // 获取 openid(小程序OpenId)
  320. $user = UserClass::getByCondition(['mobile'=>$order['customMobile']], false, false,'id, miniOpenId');
  321. if (empty($user)) {
  322. noticeUtil::push("通过手机号-".$order['customMobile'].",获取小程序OpenId失败");
  323. Yii::error('获取用户openId出错');
  324. util::fail('数据出错');
  325. }
  326. $cargoName = '花材'; // 商品名称
  327. $cargo = [
  328. 'cargo_name' => $cargoName,
  329. 'cargo_weight' => intval($post['weight'] * 1000),
  330. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  331. 'cargo_num' => intval($post['packageNum']),
  332. 'cargo_price' => intval($order['actPrice'] * 100), // $order 中有各个价格,请注意
  333. 'item_list' => $itemList,
  334. ];
  335. //生成 store_order_id
  336. $storeOrderId = $orderId . '_ghs';;
  337. if (true) { // 如果不是首次用 $orderId 创建快递配送,则要生成新 store_order_id
  338. // store_order_id 门店订单编号, 即 orderId。如果是重新配送的第n次,订单编号的命名规则为:orderId_cp_n
  339. $query = (new Query())
  340. ->from('xhGhsExpressOrder')
  341. ->where(['orderId' => $orderId]);
  342. $copyOrderCount = $query->count();
  343. $copyOrderCount += 1;
  344. //区分线上线下
  345. if (getenv('YII_ENV') == 'production') {
  346. $storeOrderId = $storeOrderId . '_cp_' . $copyOrderCount;
  347. } else {
  348. $storeOrderId = $storeOrderId . '_cs_cp_' . $copyOrderCount;
  349. }
  350. }
  351. $callbackUrl = Yii::$app->params['ghsHost'] . '/intra-city/callback';
  352. $orderData = [
  353. 'wx_store_id' => $shopExt['wxStoreId'],
  354. 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
  355. 'user_openid' => $user['miniOpenId'],//'o-hXO4kkdM2nqORdiII42FlcdeL4'
  356. 'user_lng' => (float)$post['user_lng'],
  357. 'user_lat' => (float)$post['user_lat'],
  358. 'user_address' => $post['user_address'],
  359. 'user_name' => $post['user_name'],
  360. 'user_phone' => (string)$post['user_phone'],
  361. 'order_seq' => $order['sendNum'], // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
  362. 'verify_code_type' => 0,
  363. 'order_detail_path' => '/pagesOrder/detail?id=' . $orderId, // TODO 后期要重新选个地址
  364. 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
  365. //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 是否使用沙箱(非必传)
  366. 'cargo' => $cargo
  367. ];
  368. $result = IntraCityExpress::createOrder($orderData);
  369. if (isset($result['errcode']) && $result['errcode'] === 0) {
  370. try {
  371. // 保存进 xhGhsExpressOrder 表
  372. $data = [
  373. 'mainId' => $this->mainId,
  374. 'shopId' => $this->shopId,
  375. 'deliveryId' => isset($result['service_trans_id']) ? $result['service_trans_id'] : '',
  376. 'wxOrderId' => isset($result['wx_order_id']) ? $result['wx_order_id'] : '',
  377. 'wxStoreId' => isset($result['wx_store_id']) ? $result['wx_store_id'] : '',
  378. 'storeOrderId' => isset($result['store_order_id']) ? $result['store_order_id'] : '',
  379. 'orderId' => $orderId,
  380. 'transOrderId' => isset($result['trans_order_id']) ? $result['trans_order_id'] : '',
  381. 'distance' => isset($result['distance']) ? $result['distance'] : 0,
  382. 'fee' => isset($result['fee']) ? $result['fee'] : 0,
  383. 'fetchCode' => isset($result['fetch_code']) ? $result['fetch_code'] : '',
  384. 'orderSeq' => isset($result['order_seq']) ? $result['order_seq'] : ''
  385. ];
  386. ExpressOrderClass::add($data);
  387. $updateData = [
  388. 'sendDistance' => $data['distance'],
  389. 'sendStatus' => 0,
  390. 'deliveryId' => $data['deliveryId'],
  391. ];
  392. OrderClass::updateById($orderId, $updateData); // 更新订单状态为配送中
  393. util::success(['fee' => $data['fee']], '订单创建成功');
  394. } catch (\Exception $e) {
  395. Yii::error('同城配送创建订单保存数据失败:' . $e->getMessage());
  396. util::fail('订单创建失败');
  397. }
  398. } else if (isset($result['errcode']) && $result['errcode'] === 934002) {
  399. Yii::error("重复创建订单:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
  400. util::fail( '重复创建订单: ' . $result['errcode']);
  401. } else {
  402. noticeUtil::push("批发 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
  403. Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
  404. util::fail( '订单创建失败: ' . $result['errcode']);
  405. }
  406. } catch (\Exception $e) {
  407. Yii::error("订单创建异常:" . $e->getMessage(), 'intraCity');
  408. util::fail("系统出错");
  409. }
  410. }
  411. /**
  412. * 查询订单
  413. * GET /intra-city/get-order
  414. */
  415. public function actionGetOrder()
  416. {
  417. try {
  418. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  419. if (empty($shopExt)) {
  420. util::fail("微信门店不存在");
  421. }
  422. $post = Yii::$app->request->post();
  423. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  424. $orderId = $post['orderId'];
  425. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  426. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  427. util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
  428. }
  429. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  430. if ($order['mainId'] != $this->mainId) {
  431. util::fail('订单未找到');
  432. }
  433. // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
  434. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  435. $query = (new Query())
  436. ->from('xhGhsExpressOrder')
  437. ->where(['orderId' => $orderId])
  438. ->andWhere(['mainId' => $this->mainId]);
  439. $esDatas = $query->all();
  440. $count = count($esDatas);
  441. if ($count > 0) {
  442. $es = $esDatas[0];
  443. $storeOrderId = $es['storeOrderId'];
  444. }
  445. $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
  446. if (isset($result['errcode']) && $result['errcode'] === 0) {
  447. util::success($result, "查询成功");
  448. } else {
  449. Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  450. util::fail( '订单查询失败: ' . $result['errcode']);
  451. }
  452. } catch (\Exception $e) {
  453. Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
  454. util::fail("系统出错");
  455. }
  456. }
  457. /**
  458. * 取消订单
  459. * POST /intra-city/cancel-order
  460. */
  461. public function actionCancelOrder()
  462. {
  463. try {
  464. $post = Yii::$app->request->post();
  465. $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  466. if (empty($main)) {
  467. util::fail("微信门店不存在");
  468. }
  469. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  470. $orderId = $post['orderId']; //配送订单创建成功后,也会返回的 store_order_id。 即 orderId
  471. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $main['wxStoreId'];
  472. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  473. util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
  474. }
  475. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  476. if ($order['mainId'] != $this->mainId) {
  477. util::fail('订单未找到');
  478. }
  479. if (!in_array($order['sendStatus'], [0, 1, 4, 5])) {
  480. util::fail('配送单当前状态不能取消');
  481. }
  482. // 检查是否存在重复的订单,如果存在,则使用最后一个订单的 store_order_id
  483. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  484. $query = (new Query())
  485. ->from('xhGhsExpressOrder')
  486. ->where(['orderId' => $orderId])
  487. ->andWhere(['status' => 1])
  488. ->orderBy('addTime DESC');
  489. // $command = $query->createCommand();
  490. // $sql = $command->sql;
  491. $esDatas = $query->all();
  492. $count = count($esDatas);
  493. if ($count > 0) {
  494. $es = $esDatas[0];
  495. $storeOrderId = $es['storeOrderId'];
  496. if ($count > 1) {
  497. noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
  498. }
  499. }
  500. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  501. if (isset($result['errcode']) && $result['errcode'] === 0) {
  502. // 更新订单状态
  503. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  504. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true);
  505. if (!empty($eo)) {
  506. $eo->status = 3;
  507. $eo->cancelTime = date('Y-m-d H:i:s');
  508. $eo->deductfee = $result['deductfee'];
  509. $eo->save();
  510. }
  511. util::success($result, "订单取消成功");
  512. } else {
  513. if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
  514. // 更新订单状态
  515. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  516. util::success($result, "订单取消成功");
  517. }
  518. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  519. util::fail('订单取消失败: ' . $result['errcode']);
  520. }
  521. } catch (\Exception $e) {
  522. Yii::error("订单取消异常:" . $e->getMessage(), 'intraCity');
  523. util::fail("系统出错");
  524. }
  525. }
  526. /**
  527. * 微信回调接口
  528. */
  529. public function actionCallback()
  530. {
  531. $callbackData = Yii::$app->request->post();
  532. if (empty($callbackData)) {
  533. $postStr = file_get_contents('php://input');
  534. $callbackData = json_decode($postStr, true);
  535. if (empty($callbackData)) {
  536. util::fail('回调请求的数据为空');
  537. }
  538. }
  539. // 从配置中获取安全token
  540. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  541. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  542. // 记录回调日志
  543. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'intraCity');
  544. $storeOrderId = $callbackData['store_order_id'] ?? 0;
  545. $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
  546. if (empty($storeOrderId) || empty($wxStoreId)) {
  547. Yii::error("配送单回调接口的请求参数出错,storeOrderId = $storeOrderId, wxStoreId = $wxStoreId");
  548. return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
  549. }
  550. try {
  551. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  552. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  553. if (empty($eo)) {
  554. Yii::error('订单不存在. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  555. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  556. }
  557. // 从 $storeOrderId 提取 orderId
  558. $arr = explode('_', $storeOrderId);
  559. $orderId = intval($arr[0]);
  560. if ($orderId == 0) {
  561. Yii::error('订单号为0. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  562. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  563. }
  564. $tx = Yii::$app->db->beginTransaction(); // ====================== 开启事务
  565. $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
  566. $orderStatus = intval($callbackData['order_status']);
  567. switch ($orderStatus) {
  568. // 订单创建成功
  569. case IntraCityExpress::ORDER_STATUS_CREATED:
  570. $eo->orderStatus = 1;
  571. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  572. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 0]);
  573. break;
  574. // 商家取消订单
  575. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  576. $eo->orderStatus = 2;
  577. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
  578. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  579. $msg = '取消配送,订单编号 ';
  580. break;
  581. // 配送方取消订单
  582. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
  583. $eo->orderStatus = 3;
  584. $eo->status = 0;
  585. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
  586. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  587. $msg = '配送方取消配送,订单编号 ';
  588. break;
  589. // 配送员接单
  590. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  591. $eo->orderStatus = 4;
  592. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  593. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 1]); //订单创建时已执行了,这儿重复更新
  594. break;
  595. // 配送员到店
  596. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  597. $eo->orderStatus = 5;
  598. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  599. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 4]); //订单创建时已执行了,这儿重复更新
  600. break;
  601. // 配送中
  602. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  603. $eo->orderStatus = 6;
  604. OrderClass::updateById($orderId, ['sendStatus' => 5]);
  605. break;
  606. // 配送员撤单
  607. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  608. $eo->orderStatus = 7;
  609. $eo->status = 0;
  610. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
  611. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  612. $msg = '跑腿取消配送,订单编号 ';
  613. break;
  614. // 配送完成
  615. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  616. $eo->orderStatus = 8;
  617. // 更新 xhOrder 表的订单状态与配送状态 -- 已完成|已送达
  618. OrderClass::updateById($orderId, ['status' => 4, 'sendStatus' => 2]);
  619. break;
  620. // 配送异常
  621. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  622. $eo->orderStatus = 9;
  623. $eo->status = 0;
  624. noticeUtil::push('同城配送异常 --- store_order_id(orderId):' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
  625. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
  626. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  627. $msg = '订单配送异常,订单编号 ';
  628. break;
  629. }
  630. if ($msg != '') { // $msg 不为空,则发通知
  631. $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
  632. $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
  633. $result = $msg . $order->sendNum;
  634. WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
  635. }
  636. $re = $eo->save();
  637. if (!$re) {
  638. noticeUtil::push('同城配送回调更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  639. Yii::error('更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  640. $tx->rollBack(); // ====================== 事务回滚
  641. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  642. }
  643. $tx->commit(); // ====================== 事务提交
  644. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']); // 成功状态的返回数据
  645. } catch (\Exception $e) {
  646. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  647. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  648. }
  649. }
  650. //模拟接口回调 ssh 20250826
  651. public function actionMockNotify()
  652. {
  653. if (getenv('YII_ENV') != 'production') {
  654. $post = Yii::$app->request->post();
  655. $orderStatus = $post['orderStatus'] ?? 0;
  656. $wxOrderId = $post['wxOrderId'] ?? '';
  657. $ptStyle = dict::getDict('ptStyle', 'hd');
  658. $merchant = WxOpenClass::getWxInfo();
  659. $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
  660. util::success($ret);
  661. }
  662. util::complete();
  663. }
  664. }