IntraCityController.php 32 KB

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