IntraCityController.php 35 KB

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