IntraCityController.php 35 KB

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