IntraCityController.php 34 KB

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