IntraCityController.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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' => 1 // 如果不需要沙箱,use_sandbox就不传就好了 -- 踩坑人的经验
  277. //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1 // 根据环境变量判断是否使用沙盒环境 -- 没用,不生效
  278. ];
  279. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  280. $result = IntraCityExpress::preAddOrder($orderData);
  281. if ($result['errcode'] === 0) {
  282. util::success($result, "查询成功");
  283. } else {
  284. Yii::error("运费查询失败:" . json_encode($result));
  285. util::fail('运费查询失败' . json_encode($result));
  286. }
  287. }
  288. //根据订单查询运费 ssh
  289. public function actionGetOrderFee()
  290. {
  291. $post = Yii::$app->request->post();
  292. $orderId = $post['id'];
  293. $order = OrderClass::getById($orderId, true);
  294. if (empty($order)) {
  295. util::fail('没有找到订单');
  296. }
  297. if ($order->mainId != $this->mainId) {
  298. util::fail('不是你的订单');
  299. }
  300. $main = $this->main;
  301. $wxStoreId = $main->wxStoreId ?? '';
  302. if (empty($wxStoreId)) {
  303. util::fail('你还没有开通跑腿');
  304. }
  305. $weight = $post['weight'] ?? 0;
  306. if ($weight <= 0) {
  307. util::fail('请填写重量');
  308. }
  309. $packageNum = $post['packageNum'] ?? 1;
  310. $price = $order->actPrice ?? 0;
  311. $cargo = [
  312. 'cargo_name' => '鲜花花材', // 商品名称 -- $order 中没有,要在 goodsInfo 中取
  313. 'cargo_weight' => intval($weight * 1000), // 单位:克 -- 把千克转换为克
  314. 'cargo_price' => intval($price * 100), // 单位:分 -- 把元转换为分
  315. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  316. 'cargo_num' => intval($packageNum)
  317. ];
  318. $originalLng = $order->long;
  319. $originalLat = $order->lat;
  320. if (empty($originalLng) || empty($originalLat)) {
  321. util::fail('客户地址不完整');
  322. }
  323. $customName = $order->customName ?? '';
  324. $customMobile = $order->customMobile ?? '';
  325. if (empty($customMobile)) {
  326. util::fail('客户手机缺失');
  327. }
  328. $address = $order->address ?? '';
  329. if (empty($address)) {
  330. util::fail('客户地址缺失');
  331. }
  332. $orderData = [
  333. 'wx_store_id' => $wxStoreId,
  334. 'user_name' => $customName,
  335. 'user_phone' => $customMobile,
  336. 'user_lng' => $originalLng,
  337. 'user_lat' => $originalLat,
  338. 'user_address' => $address,
  339. 'cargo' => $cargo,
  340. //'use_sandbox' => 1 // 如果不需要沙箱,use_sandbox就不传就好了 -- 踩坑人的经验
  341. //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1 // 根据环境变量判断是否使用沙盒环境 -- 没用,不生效
  342. ];
  343. //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
  344. $result = IntraCityExpress::preAddOrder($orderData);
  345. if ($result['errcode'] === 0) {
  346. util::success($result, "查询成功");
  347. } else {
  348. Yii::error("运费查询失败:" . json_encode($result));
  349. util::fail('查询失败');
  350. }
  351. }
  352. /**
  353. * 创建订单
  354. * POST /intra-city/create-order
  355. */
  356. public function actionCreateOrder()
  357. {
  358. $post = Yii::$app->request->post();
  359. $orderId = intval($post['orderId']);
  360. $order = OrderClass::getById($orderId);
  361. if (empty($order)) {
  362. util::fail('没有找到订单');
  363. }
  364. if ($order['mainId'] != $this->mainId) {
  365. util::fail('不是你的订单');
  366. }
  367. $packageNum = $post['packageNum'] ?? 0;
  368. if ($packageNum <= 0) {
  369. util::fail('请填写包裹数量');
  370. }
  371. $weight = $post['weight'] ?? 0;
  372. if ($weight <= 0) {
  373. util::fail('请填写重量');
  374. }
  375. $actPrice = $order['actPrice'] ?? 0;
  376. if ($actPrice <= 0) {
  377. util::fail('订单没有价格,不需要发跑腿');
  378. }
  379. $sn = $order['orderSn'];
  380. $itemInfo = OrderItemClass::getByCondition(['orderSn' => $sn], null, 'id, name, cover, num');
  381. $num = intval($order['itemNum']);
  382. $itemList[] = [
  383. 'item_name' => '花材',
  384. 'item_pic_url' => imgUtil::groupImg($itemInfo['cover']) . "?x-oss-process=image/resize,m_fill,h_130,w_130",
  385. 'count' => $num,
  386. ];
  387. $main = $this->main;
  388. $wxStoreId = $main->wxStoreId ?? '';
  389. if (empty($wxStoreId)) {
  390. util::fail('你还没有开通跑腿功能');
  391. }
  392. $cgId = $order['purchaseId'] ?? 0;
  393. if (empty($cgId)) {
  394. util::fail('没有找到采购信息');
  395. }
  396. $miniOpenId = '';
  397. $customShopAdminId = $order['customShopAdminId'] ?? 0;
  398. if (!empty($customShopAdminId)) {
  399. $customStaff = StaffClass::getById($customShopAdminId, true);
  400. $customStaffAdminId = $customStaff->adminId ?? '';
  401. if (!empty($customStaffAdminId)) {
  402. $customAdmin = AdminClass::getById($customStaffAdminId, true);
  403. $miniOpenId = $customAdmin->miniOpenId ?? '';
  404. }
  405. }
  406. if (empty($miniOpenId)) {
  407. $admin = $this->admin;
  408. $miniOpenId = $admin->miniOpenId ?? '';
  409. }
  410. if (empty($miniOpenId)) {
  411. util::fail('没有找到微信登录信息,无法呼叫跑腿');
  412. }
  413. $cargoName = '鲜花花材';//商品名称
  414. $cargo = [
  415. 'cargo_name' => $cargoName,
  416. 'cargo_weight' => intval($weight * 1000),
  417. 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
  418. 'cargo_num' => intval($packageNum),
  419. 'cargo_price' => intval($actPrice * 100), // $order 中有各个价格,请注意
  420. 'item_list' => $itemList,
  421. ];
  422. //生成 store_order_id
  423. $storeOrderId = $orderId . '_ghs';;
  424. if ($order['sendStatus'] == 3) {
  425. // 如果不是首次用 $orderId 创建快递配送,则要生成新 store_order_id
  426. // store_order_id 门店订单编号, 即 orderId。如果是重新配送的第n次,订单编号的命名规则为:orderId_cp_n
  427. $query = (new Query())
  428. ->from('xhGhsExpressOrder')
  429. ->where(['orderId' => $orderId]);
  430. $copyOrderCount = $query->count();
  431. $copyOrderCount += 1;
  432. //区分线上线下
  433. if (getenv('YII_ENV') == 'production') {
  434. $storeOrderId = $storeOrderId . '_cp_' . $copyOrderCount;
  435. } else {
  436. $storeOrderId = $storeOrderId . '_cs_cp_' . $copyOrderCount;
  437. }
  438. }
  439. $sendNum = $order['sendNum'] ?? '';
  440. $customName = $order['customName'] ?? '';
  441. if (empty($customName)) {
  442. util::fail('客户名称无效');
  443. }
  444. $customMobile = $order['customMobile'] ?? '';
  445. if (empty($customMobile)) {
  446. util::fail('客户手机号无效');
  447. }
  448. $long = $order['long'] ?? '';
  449. $lat = $order['lat'] ?? '';
  450. if (empty($long) || empty($lat)) {
  451. util::fail('客户地址无效');
  452. }
  453. $address = $order['address'] ?? '';
  454. if (empty($address)) {
  455. util::fail('客户地址无效呢');
  456. }
  457. $callbackUrl = Yii::$app->params['ghsHost'] . '/intra-city/callback';
  458. $orderData = [
  459. 'wx_store_id' => $wxStoreId,
  460. 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
  461. 'user_openid' => $miniOpenId,
  462. 'user_lng' => (float)$long,
  463. 'user_lat' => (float)$lat,
  464. 'user_address' => $address,
  465. 'user_name' => $customName,
  466. 'user_phone' => $customMobile,
  467. 'order_seq' => $sendNum, // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
  468. 'verify_code_type' => 0,
  469. 'order_detail_path' => '/admin/order/detail?id=' . $cgId,
  470. 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
  471. 'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 开发环境默认使用沙箱
  472. 'cargo' => $cargo
  473. ];
  474. //开发环境只能使用沙箱 ssh
  475. if (getenv('YII_ENV') != 'production') {
  476. $orderData['use_sandbox'] = 1;
  477. $orderData['user_name'] = '顺丰同城';
  478. $orderData['user_phone'] = 13881979410;
  479. $orderData['user_address'] = '北京市海淀区学清嘉创大厦A座15层';
  480. $orderData['user_lng'] = '116.352954';
  481. $orderData['user_lat'] = '40.014747';
  482. }
  483. $result = IntraCityExpress::createOrder($orderData);
  484. if (isset($result['errcode']) && $result['errcode'] === 0) {
  485. // 保存进 xhGhsExpressOrder 表
  486. $data = [
  487. 'mainId' => $this->mainId,
  488. 'shopId' => $this->shopId,
  489. 'deliveryId' => $result['service_trans_id'] ?? '',
  490. 'wxOrderId' => $result['wx_order_id'] ?? '',
  491. 'wxStoreId' => $result['wx_store_id'] ?? '',
  492. 'storeOrderId' => $result['store_order_id'] ?? '',
  493. 'orderId' => $orderId,
  494. 'transOrderId' => $result['trans_order_id'] ?? '',
  495. 'distance' => $result['distance'] ?? 0,
  496. 'fee' => $result['fee'] ?? 0,
  497. 'fetchCode' => $result['fetch_code'] ?? '',
  498. 'orderSeq' => $result['order_seq'] ?? ''
  499. ];
  500. ExpressOrderClass::add($data);
  501. $updateData = [
  502. 'sendDistance' => $data['distance'],
  503. 'sendStatus' => 0,
  504. 'deliveryId' => $data['deliveryId'],
  505. ];
  506. //更新订单状态为配送中
  507. OrderClass::updateById($orderId, $updateData);
  508. util::success(['fee' => $data['fee']], '订单创建成功');
  509. } else {
  510. noticeUtil::push("批发 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
  511. Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
  512. util::fail('提交失败,请确认余额是否充足');
  513. }
  514. }
  515. /**
  516. * 查询订单
  517. * GET /intra-city/get-order
  518. */
  519. public function actionGetOrder()
  520. {
  521. try {
  522. $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  523. if (empty($shopExt)) {
  524. util::fail("微信门店不存在");
  525. }
  526. $post = Yii::$app->request->post();
  527. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  528. $orderId = $post['orderId'];
  529. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
  530. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  531. util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
  532. }
  533. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  534. if ($order['mainId'] != $this->mainId) {
  535. util::fail('订单未找到');
  536. }
  537. // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
  538. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  539. $query = (new Query())
  540. ->from('xhGhsExpressOrder')
  541. ->where(['orderId' => $orderId])
  542. ->andWhere(['mainId' => $this->mainId]);
  543. $esDatas = $query->all();
  544. $count = count($esDatas);
  545. if ($count > 0) {
  546. $es = $esDatas[0];
  547. $storeOrderId = $es['storeOrderId'];
  548. }
  549. $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
  550. if (isset($result['errcode']) && $result['errcode'] === 0) {
  551. util::success($result, "查询成功");
  552. } else {
  553. Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  554. util::fail('订单查询失败: ' . $result['errcode']);
  555. }
  556. } catch (\Exception $e) {
  557. Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
  558. util::fail("系统出错");
  559. }
  560. }
  561. /**
  562. * 取消订单
  563. * POST /intra-city/cancel-order
  564. */
  565. public function actionCancelOrder()
  566. {
  567. try {
  568. $post = Yii::$app->request->post();
  569. $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
  570. if (empty($main)) {
  571. util::fail("微信门店不存在");
  572. }
  573. $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
  574. $orderId = $post['orderId']; //配送订单创建成功后,也会返回的 store_order_id。 即 orderId
  575. $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $main['wxStoreId'];
  576. if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
  577. util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
  578. }
  579. $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
  580. if ($order['mainId'] != $this->mainId) {
  581. util::fail('订单未找到');
  582. }
  583. if (!in_array($order['sendStatus'], [0, 1, 4, 5])) {
  584. util::fail('配送单当前状态不能取消');
  585. }
  586. // 检查是否存在重复的订单,如果存在,则使用最后一个订单的 store_order_id
  587. $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
  588. $query = (new Query())
  589. ->from('xhGhsExpressOrder')
  590. ->where(['orderId' => $orderId])
  591. ->andWhere(['status' => 1])
  592. ->orderBy('addTime DESC');
  593. // $command = $query->createCommand();
  594. // $sql = $command->sql;
  595. $esDatas = $query->all();
  596. $count = count($esDatas);
  597. if ($count > 0) {
  598. $es = $esDatas[0];
  599. $storeOrderId = $es['storeOrderId'];
  600. if ($count > 1) {
  601. noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
  602. }
  603. }
  604. $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
  605. if (isset($result['errcode']) && $result['errcode'] === 0) {
  606. // 更新订单状态
  607. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  608. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true);
  609. if (!empty($eo)) {
  610. $eo->status = 3;
  611. $eo->cancelTime = date('Y-m-d H:i:s');
  612. $eo->deductfee = $result['deductfee'];
  613. $eo->save();
  614. }
  615. util::success($result, "订单取消成功");
  616. } else {
  617. if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
  618. // 更新订单状态
  619. OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
  620. util::success($result, "订单取消成功");
  621. }
  622. Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
  623. util::fail('订单取消失败: ' . $result['errcode']);
  624. }
  625. } catch (\Exception $e) {
  626. Yii::error("订单取消异常:" . $e->getMessage(), 'intraCity');
  627. util::fail("系统出错");
  628. }
  629. }
  630. /**
  631. * 微信回调接口
  632. */
  633. public function actionCallback()
  634. {
  635. $callbackData = Yii::$app->request->post();
  636. if (empty($callbackData)) {
  637. $postStr = file_get_contents('php://input');
  638. $callbackData = json_decode($postStr, true);
  639. if (empty($callbackData)) {
  640. util::fail('回调请求的数据为空');
  641. }
  642. }
  643. // 从配置中获取安全token
  644. // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
  645. // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
  646. // 记录回调日志
  647. Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'intraCity');
  648. $storeOrderId = $callbackData['store_order_id'] ?? 0;
  649. $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
  650. if (empty($storeOrderId) || empty($wxStoreId)) {
  651. Yii::error("配送单回调接口的请求参数出错,storeOrderId = $storeOrderId, wxStoreId = $wxStoreId");
  652. return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
  653. }
  654. try {
  655. // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
  656. $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
  657. if (empty($eo)) {
  658. Yii::error('订单不存在. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  659. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  660. }
  661. // 从 $storeOrderId 提取 orderId
  662. $arr = explode('_', $storeOrderId);
  663. $orderId = intval($arr[0]);
  664. if ($orderId == 0) {
  665. Yii::error('订单号为0. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
  666. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  667. }
  668. $tx = Yii::$app->db->beginTransaction(); // ====================== 开启事务
  669. $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
  670. $orderStatus = intval($callbackData['order_status']);
  671. switch ($orderStatus) {
  672. // 订单创建成功
  673. case IntraCityExpress::ORDER_STATUS_CREATED:
  674. $eo->orderStatus = 1;
  675. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  676. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 0]);
  677. break;
  678. // 商家取消订单
  679. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
  680. $eo->orderStatus = 2;
  681. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
  682. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  683. $msg = '取消配送,订单编号 ';
  684. break;
  685. // 配送方取消订单
  686. case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
  687. $eo->orderStatus = 3;
  688. $eo->status = 0;
  689. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
  690. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  691. $msg = '配送方取消配送,订单编号 ';
  692. break;
  693. // 配送员接单
  694. case IntraCityExpress::ORDER_STATUS_ACCEPTED:
  695. $eo->orderStatus = 4;
  696. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  697. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 1]); //订单创建时已执行了,这儿重复更新
  698. break;
  699. // 配送员到店
  700. case IntraCityExpress::ORDER_STATUS_ARRIVED:
  701. $eo->orderStatus = 5;
  702. // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
  703. OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 4]); //订单创建时已执行了,这儿重复更新
  704. break;
  705. // 配送中
  706. case IntraCityExpress::ORDER_STATUS_DELIVERING:
  707. $eo->orderStatus = 6;
  708. OrderClass::updateById($orderId, ['sendStatus' => 5]);
  709. break;
  710. // 配送员撤单
  711. case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
  712. $eo->orderStatus = 7;
  713. $eo->status = 0;
  714. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
  715. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  716. $msg = '跑腿取消配送,订单编号 ';
  717. break;
  718. // 配送完成
  719. case IntraCityExpress::ORDER_STATUS_COMPLETED:
  720. $eo->orderStatus = 8;
  721. // 更新 xhOrder 表的订单状态与配送状态 -- 已完成|已送达
  722. OrderClass::updateById($orderId, ['status' => 4, 'sendStatus' => 2]);
  723. break;
  724. // 配送异常
  725. case IntraCityExpress::ORDER_STATUS_EXCEPTION:
  726. $eo->orderStatus = 9;
  727. $eo->status = 0;
  728. noticeUtil::push('同城配送异常 --- store_order_id(orderId):' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
  729. // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
  730. OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
  731. $msg = '订单配送异常,订单编号 ';
  732. break;
  733. }
  734. if ($msg != '') { // $msg 不为空,则发通知
  735. $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
  736. $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
  737. $result = $msg . $order->sendNum;
  738. WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
  739. }
  740. $re = $eo->save();
  741. if (!$re) {
  742. noticeUtil::push('同城配送回调更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  743. Yii::error('更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
  744. $tx->rollBack(); // ====================== 事务回滚
  745. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  746. }
  747. $tx->commit(); // ====================== 事务提交
  748. return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']); // 成功状态的返回数据
  749. } catch (\Exception $e) {
  750. Yii::error('同城配送回调处理异常:' . $e->getMessage());
  751. return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
  752. }
  753. }
  754. //模拟接口回调 ssh 20250826
  755. public function actionMockNotify()
  756. {
  757. if (getenv('YII_ENV') != 'production') {
  758. $post = Yii::$app->request->post();
  759. $orderStatus = $post['orderStatus'] ?? 0;
  760. $wxOrderId = $post['wxOrderId'] ?? '';
  761. $ptStyle = dict::getDict('ptStyle', 'hd');
  762. $merchant = WxOpenClass::getWxInfo();
  763. $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
  764. util::success($ret);
  765. }
  766. util::complete();
  767. }
  768. }