IntraCityController.php 35 KB

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