OrderController.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. <?php
  2. namespace hd\controllers;
  3. use bizHd\hb\classes\HbClass;
  4. use Yii;
  5. use biz\shop\classes\ShopExtClass;
  6. use biz\sj\services\MerchantExtendService;
  7. use biz\sj\services\MerchantService;
  8. use bizHd\custom\classes\CustomClass;
  9. use bizHd\custom\classes\HdClass;
  10. use bizHd\goods\classes\GoodsClass;
  11. use bizHd\merchant\services\ShopService;
  12. use bizHd\order\classes\OrderClass;
  13. use bizHd\order\classes\OrderForwardClass;
  14. use bizHd\order\classes\OrderItemClass;
  15. use bizHd\order\classes\OrderSendClass;
  16. use hd\models\order\CreateOrderForm;
  17. use bizHd\express\classes\HdDeliveryOrderClass;
  18. use bizHd\order\services\OrderService;
  19. use bizHd\product\classes\ProductClass;
  20. use bizHd\saas\services\RegionService;
  21. use bizHd\shop\classes\ShopClass;
  22. use bizHd\user\services\UserService;
  23. use bizHd\work\classes\WorkClass;
  24. use common\components\dict;
  25. use common\components\dateUtil;
  26. use common\components\noticeUtil;
  27. use common\components\orderSn;
  28. use common\components\payUtil;
  29. use common\services\xhPayToolService;
  30. use common\components\util;
  31. use common\components\stringUtil;
  32. use bizHd\promote\services\CouponService;
  33. use common\components\httpUtil;
  34. use biz\wx\classes\WxMessageClass;
  35. use common\components\lakala\Lakala;
  36. use yii\helpers\ArrayHelper;
  37. class OrderController extends BaseController
  38. {
  39. public $guestAccess = ['order-relate', 'fast-pay', 'create-order', 'list', 'info'];
  40. public function actionDebt()
  41. {
  42. $get = Yii::$app->request->get();
  43. $id = $get['id'] ?? 0;
  44. $info = OrderClass::getById($id, true);
  45. if (empty($info)) {
  46. util::fail('没有找到订单');
  47. }
  48. if ($info->mainId != $this->mainId) {
  49. util::fail('不是你的订单');
  50. }
  51. //4秒内不允许重复提交
  52. util::checkRepeatCommit($id, 4);
  53. if ($info->status != 1) {
  54. util::fail('订单已付款或取消');
  55. }
  56. $payWay = dict::getDict('payWay', 'debtPay');
  57. $connection = Yii::$app->db;
  58. $transaction = $connection->beginTransaction();
  59. try {
  60. $actPrice = $info->actPrice ?? 0;
  61. $info->debtPrice = $actPrice;
  62. $info->remainDebtPrice = $actPrice;
  63. $info->debt = 1;
  64. $info->save();
  65. OrderClass::payAfter($info, $payWay);
  66. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  67. if ($info->getGoods == 1 && $info->sendType == 1 && $info->status == 2) {
  68. $info->status = 4;
  69. $info->save();
  70. }
  71. $transaction->commit();
  72. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  73. HdDeliveryOrderClass::payAfter($info);
  74. util::complete('赊账成功');
  75. } catch (\Exception $exception) {
  76. $transaction->rollBack();
  77. Yii::info("赊账失败原因:" . $exception->getMessage());
  78. util::fail('操作失败');
  79. }
  80. }
  81. //取消订单 ssh 20221231
  82. public function actionCancel()
  83. {
  84. //避免重复提交
  85. $adminId = $this->adminId;
  86. util::checkRepeatCommit($adminId, 8);
  87. $get = Yii::$app->request->get();
  88. $id = $get['id'] ?? 0;
  89. $order = OrderClass::getById($id, true);
  90. if ($order->mainId != $this->mainId) {
  91. util::fail('不是你的订单');
  92. }
  93. $staff = $this->shopAdmin;
  94. $connection = Yii::$app->db;
  95. $transaction = $connection->beginTransaction();
  96. try {
  97. OrderClass::setExpire($order, true, $staff);
  98. $transaction->commit();
  99. util::complete();
  100. } catch (\Exception $exception) {
  101. $transaction->rollBack();
  102. Yii::info("取消原因:" . $exception->getMessage());
  103. util::fail('取消失败');
  104. }
  105. }
  106. //修改订单 ssh 20220926
  107. public function actionUpdate()
  108. {
  109. $post = Yii::$app->request->post();
  110. $id = $post['id'] ?? 0;
  111. $order = OrderClass::getById($id, true);
  112. OrderClass::valid($order, $this->mainId);
  113. unset($post['id']);
  114. if ($order->status == 3) {
  115. util::fail('订单已配送');
  116. }
  117. if ($order->status == 4) {
  118. util::fail('订单已完成');
  119. }
  120. if ($order->status == 5) {
  121. util::fail('订单已取消');
  122. }
  123. if ($order->fromType == 4) {
  124. util::fail('请在美团APP上修改');
  125. }
  126. $address = $post['address'] ?? '';
  127. $floor = $post['floor'] ?? '';
  128. $post['fullAddress'] = $address . $floor;
  129. OrderClass::updateById($id, $post);
  130. $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  131. $remark = $post['remark'] ?? '';
  132. $reachDate = $post['reachDate'] ?? '';
  133. $reachPeriod = $post['reachPeriod'] ?? '';
  134. $cardInfo = $post['cardInfo'] ?? '';
  135. $anonymity = $post['anonymity'] ?? 0;
  136. $bookName = $post['bookName'] ?? '';
  137. if (!empty($workList)) {
  138. foreach ($workList as $work) {
  139. $work->remark = $remark;
  140. $work->reachDate = $reachDate;
  141. $work->reachPeriod = $reachPeriod;
  142. $work->cardInfo = $cardInfo;
  143. $work->anonymity = $anonymity;
  144. $work->bookName = $bookName;
  145. $work->save();
  146. }
  147. }
  148. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  149. ShopExtClass::orderUpdateRemind($shopExt, $order);
  150. util::complete();
  151. }
  152. //客户欠款的订单 ssh 2021.2.4
  153. public function actionDebtList()
  154. {
  155. $get = Yii::$app->request->get();
  156. $id = $get['id'] ?? 0;
  157. $info = CustomClass::getById($id, true);
  158. CustomClass::valid($info, $this->shopId);
  159. $where = ['customId' => $id, 'debt' => 1];
  160. $searchTime = $get['searchTime'] ?? '';
  161. if (!empty($searchTime)) {
  162. $startTime = $get['startTime'] ?? '';
  163. $endTime = $get['endTime'] ?? '';
  164. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  165. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  166. }
  167. $allowedPageSizes = [100, 200, 300];
  168. $pageSize = isset($get['pageSize']) && in_array((int)$get['pageSize'], $allowedPageSizes, true)
  169. ? (int)$get['pageSize'] : 100;
  170. $page = max(1, (int)($get['page'] ?? 1));
  171. $fields = ['id', 'orderSn', 'actPrice', 'addTime', 'remainDebtPrice', 'debtPrice'];
  172. Yii::$app->request->setQueryParams(array_merge($get, ['page' => $page, 'pageSize' => $pageSize]));
  173. $result = OrderClass::getList($fields, $where, 'addTime DESC');
  174. if (!empty($result['list'])) {
  175. foreach ($result['list'] as $key => $value) {
  176. $debtPrice = $value['debtPrice'] ?? 0;
  177. $remainDebtPrice = $value['remainDebtPrice'] ?? 0;
  178. $hasPayDebt = 0;
  179. if ($debtPrice > $remainDebtPrice) {
  180. $hasPayDebt = bcsub($debtPrice, $remainDebtPrice, 2);
  181. }
  182. $result['list'][$key]['hasPayDebt'] = floatval($hasPayDebt);
  183. }
  184. }
  185. $result['customInfo'] = $info;
  186. util::success($result);
  187. }
  188. //确认送达 ssh 20250902
  189. public function actionReach()
  190. {
  191. //解决重复提交
  192. util::checkRepeatCommit($this->adminId, 5);
  193. $get = Yii::$app->request->get();
  194. $id = $get['id'] ?? 0;
  195. $order = OrderClass::getById($id, true);
  196. if (empty($order)) {
  197. util::fail('没有找到订单');
  198. }
  199. OrderClass::valid($order, $this->mainId);
  200. if ($order->status == 5) {
  201. util::fail('订单已取消');
  202. }
  203. if ($order->status == 1) {
  204. util::fail('订单待付款');
  205. }
  206. if ($order->status == 2) {
  207. util::fail('订单未发货');
  208. }
  209. if ($order->status == 4) {
  210. util::fail('订单已经送到了');
  211. }
  212. if (!in_array($order->sendStatus, [-1, -4])) {
  213. util::fail('由跑腿送货,无需确认');
  214. }
  215. $order->status = 4;
  216. $order->save();
  217. util::complete('操作成功');
  218. }
  219. //确认取货
  220. public function actionFetch()
  221. {
  222. $get = Yii::$app->request->get();
  223. $id = $get['id'] ?? 0;
  224. //解决重复提交
  225. util::checkRepeatCommit($id . '_' . $this->adminId, 5);
  226. $order = OrderClass::getById($id, true);
  227. if (empty($order)) {
  228. util::fail('没有找到订单');
  229. }
  230. OrderClass::valid($order, $this->mainId);
  231. if ($order->status == 5) {
  232. util::fail('订单已取消');
  233. }
  234. if ($order->status == 1) {
  235. util::fail('订单待付款');
  236. }
  237. if ($order->status == 4) {
  238. util::fail('订单已取过了');
  239. }
  240. if (in_array($order->sendStatus, [-1, 0, 1, 2, 4, 5])) {
  241. util::fail('由跑腿送货,无需确认');
  242. }
  243. $order->status = 4;
  244. $order->save();
  245. util::complete('操作成功');
  246. }
  247. //批量确认取货 待发货的自取订单 每次500个
  248. public function actionBatchFetch()
  249. {
  250. $where = ["status" => 2, "sendType" => 1, "shopId" => $this->shopId];
  251. $orderList = OrderService::getLimitList("id", $where, 500, "id desc");
  252. $ids = ArrayHelper::getColumn($orderList, "id");
  253. OrderService::updateByIds($ids, ["status" => 4]);
  254. util::complete($ids);
  255. }
  256. //确认发货
  257. public function actionSend()
  258. {
  259. //解决重复提交
  260. util::checkRepeatCommit($this->adminId, 5);
  261. $get = Yii::$app->request->get();
  262. $id = $get['id'] ?? 0;
  263. $order = OrderClass::getById($id, true);
  264. if (empty($order)) {
  265. util::fail('没有找到订单');
  266. }
  267. OrderClass::valid($order, $this->mainId);
  268. if ($order->status != 2) {
  269. util::fail('订单不是待发货状态');
  270. }
  271. // $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  272. // if (!empty($workList)) {
  273. // $unComplete = false;
  274. // foreach ($workList as $work) {
  275. // if ($work->status != 1) {
  276. // $unComplete = true;
  277. // }
  278. // }
  279. // if ($unComplete == true) {
  280. // util::fail('还有制作单没有完成');
  281. // }
  282. // }
  283. $order->status = 3;
  284. $order->save();
  285. util::complete('已发货');
  286. }
  287. //打印订单 ssh 20220601
  288. public function actionPrintOrder()
  289. {
  290. $get = Yii::$app->request->get();
  291. $id = isset($get['id']) ? $get['id'] : 0;
  292. $order = OrderClass::getById($id, true);
  293. if (empty($order)) {
  294. util::fail('没有找到订单');
  295. }
  296. if ($order->forward == 1) {
  297. util::fail('红冲订单不能打印');
  298. }
  299. OrderClass::valid($order, $this->mainId);
  300. OrderClass::onlinePrint($order, true);
  301. util::complete();
  302. }
  303. //微信和支付宝付款码支付复查 ssh 20220422
  304. public function actionCodePayCheck()
  305. {
  306. ini_set('date.timezone', 'Asia/Shanghai');
  307. header("Content-type: text/html; charset=utf-8");
  308. $get = Yii::$app->request->get();
  309. $id = isset($get['id']) ? $get['id'] : 0;
  310. util::checkRepeatCommit($id, 3);
  311. $order = OrderClass::getById($id, true);
  312. OrderClass::valid($order, $this->mainId);
  313. $orderSn = $order->orderSn ?? '';
  314. $totalFee = $order->mainPay ?? 0;
  315. if ($order->payStatus == 1) {
  316. util::success(['returnStatus' => 'SUCCESS']);
  317. }
  318. if ($order->status == 5) {
  319. util::success(['returnStatus' => 'CANCEL']);
  320. }
  321. $connection = Yii::$app->db;
  322. $transaction = $connection->beginTransaction();
  323. try {
  324. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  325. $shop = $this->shop;
  326. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  327. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  328. $params = [
  329. 'appid' => 'OP00002119',
  330. 'serial_no' => '018b08cfddbd',
  331. 'merchant_no' => $shop->lklSjNo,
  332. 'term_no' => $shop->lklScanTermNo,
  333. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  334. 'lklCertificatePath' => $lklCertificatePath,
  335. ];
  336. $laResource = new Lakala($params);
  337. $scanParams = ['orderSn' => $orderSn,];
  338. $response = $laResource->query($scanParams);
  339. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  340. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  341. $payWayType = dict::getDict('payWay', 'wxPay');
  342. $account_type = $response['resp_data']['account_type'] ?? '';
  343. if ($account_type == 'WECHAT') {
  344. $payWayType = dict::getDict('payWay', 'wxPay');
  345. }
  346. if ($account_type == 'ALIPAY') {
  347. $payWayType = dict::getDict('payWay', 'alipay');
  348. }
  349. $transactionId = $response['resp_data']['trade_no'] ?? '';
  350. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  351. $order->save();
  352. $attach = '';
  353. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  354. $transaction->commit();
  355. //解决重复通知
  356. $cacheKey = 'pay_success_notice_' . $orderSn;
  357. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  358. if (empty($has)) {
  359. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  360. //打印小票和语音播报
  361. $newOrder = OrderClass::getById($id, true);
  362. OrderClass::onlinePrint($newOrder);
  363. ShopExtClass::hdGatheringReport($newOrder);
  364. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  365. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  366. $newOrder->status = 4;
  367. $newOrder->save();
  368. }
  369. HdDeliveryOrderClass::payAfter($newOrder);
  370. $shopId = $newOrder->shopId ?? 0;
  371. $shop = ShopClass::getById($shopId, true);
  372. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  373. }
  374. util::success(['returnStatus' => 'SUCCESS']);
  375. } else {
  376. util::complete('未知状态..');
  377. }
  378. }
  379. util::complete('未知状态..');
  380. } catch (\Exception $e) {
  381. $transaction->rollBack();
  382. util::complete('支付失败');
  383. }
  384. }
  385. //微信和支付宝付款码支付复查 ssh 20260716
  386. public function actionCodePayVerify()
  387. {
  388. ini_set('date.timezone', 'Asia/Shanghai');
  389. header("Content-type: text/html; charset=utf-8");
  390. $get = Yii::$app->request->get();
  391. $id = $get['id'] ?? 0;
  392. util::checkRepeatCommit($id, 3);
  393. $order = OrderClass::getById($id, true);
  394. OrderClass::valid($order, $this->mainId);
  395. $orderSn = $order->orderSn ?? '';
  396. $totalFee = $order->mainPay ?? 0;
  397. if ($order->payStatus == 1) {
  398. util::success(['returnStatus' => 'SUCCESS']);
  399. }
  400. if ($order->status == 5) {
  401. util::success(['returnStatus' => 'CANCEL']);
  402. }
  403. $connection = Yii::$app->db;
  404. $transaction = $connection->beginTransaction();
  405. try {
  406. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  407. $shop = $this->shop;
  408. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  409. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  410. $params = [
  411. 'appid' => 'OP00002119',
  412. 'serial_no' => '018b08cfddbd',
  413. 'merchant_no' => $shop->lklSjNo,
  414. 'term_no' => $shop->lklScanTermNo,
  415. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  416. 'lklCertificatePath' => $lklCertificatePath,
  417. ];
  418. $laResource = new Lakala($params);
  419. $scanParams = ['orderSn' => $orderSn,];
  420. $response = $laResource->query($scanParams);
  421. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  422. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  423. $payWayType = dict::getDict('payWay', 'wxPay');
  424. $account_type = $response['resp_data']['account_type'] ?? '';
  425. if ($account_type == 'WECHAT') {
  426. $payWayType = dict::getDict('payWay', 'wxPay');
  427. }
  428. if ($account_type == 'ALIPAY') {
  429. $payWayType = dict::getDict('payWay', 'alipay');
  430. }
  431. $transactionId = $response['resp_data']['trade_no'] ?? '';
  432. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  433. $order->save();
  434. $attach = '';
  435. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  436. $transaction->commit();
  437. //解决重复通知
  438. $cacheKey = 'pay_success_notice_' . $orderSn;
  439. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  440. if (empty($has)) {
  441. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  442. //打印小票和语音播报
  443. $newOrder = OrderClass::getById($id, true);
  444. OrderClass::onlinePrint($newOrder);
  445. ShopExtClass::hdGatheringReport($newOrder);
  446. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  447. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  448. $newOrder->status = 4;
  449. $newOrder->save();
  450. }
  451. HdDeliveryOrderClass::payAfter($newOrder);
  452. $shopId = $newOrder->shopId ?? 0;
  453. $shop = ShopClass::getById($shopId, true);
  454. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  455. }
  456. util::success(['returnStatus' => 'SUCCESS']);
  457. } else {
  458. util::success(['returnStatus' => 'PENDING'], '等待支付中...');
  459. }
  460. }
  461. util::success(['returnStatus' => 'PENDING'], '等待支付中...');
  462. } catch (\Exception $e) {
  463. $transaction->rollBack();
  464. util::complete('支付失败');
  465. }
  466. }
  467. /**
  468. * 微信和支付宝付款码支付
  469. * 职责:处理商户扫描客户付款码(被扫支付)的请求,调用拉卡拉支付接口并更新本地订单状态(零售端)
  470. * 入参:GET 传参 id (订单ID), authCode (付款码), version (版本号)
  471. * 返回:JSON 格式的支付结果(SUCCESS/FAILURE)
  472. * 副作用:更新订单支付状态、支付方式,记录支付日志,触发云打印、跑腿呼叫及语音播报
  473. * 关键边界:
  474. * 1. 验证订单有效性与待付款状态
  475. * 2. 校验付款码格式(微信/支付宝)
  476. * 3. 优化:将拉卡拉外部网络请求移出数据库事务,避免因网络延迟长时间占用数据库连接和行锁
  477. */
  478. public function actionCodePay()
  479. {
  480. ini_set('date.timezone', 'Asia/Shanghai');
  481. header("Content-type: text/html; charset=utf-8");
  482. $get = Yii::$app->request->get();
  483. $id = isset($get['id']) ? $get['id'] : 0;
  484. util::checkRepeatCommit($id, 3);
  485. $version = $get['version'] ?? 0;
  486. $order = OrderClass::getById($id, true);
  487. OrderClass::valid($order, $this->mainId);
  488. if ($order->status == OrderClass::ORDER_STATUS_CANCEL) {
  489. $msg = '订单已取消';
  490. util::success(['returnStatus' => 'FAILURE'], $msg);
  491. }
  492. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  493. $msg = '订单不是待付款状态';
  494. util::success(['returnStatus' => 'FAILURE'], $msg);
  495. }
  496. $shop = $this->shop;
  497. $sj = $shop->merchantName;
  498. $shopName = $shop->shopName;
  499. $name = $shopName == '首店' ? $sj : $sj . '-' . $shopName;
  500. $authCode = (string)$get['authCode'] ?? '';
  501. if ($version > 0) {
  502. if (empty($authCode)) {
  503. $msg = '没有扫到付款码';
  504. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  505. noticeUtil::push($remind . ' 编号005', '15280215347');
  506. util::success(['returnStatus' => 'FAILURE'], $msg);
  507. }
  508. //微信文档说明 https://pay.weixin.qq.com/doc/v2/merchant/4011936234
  509. $wxPattern = '/^(10|11|12|13|14|15)\d{16}$/';
  510. //支付宝文档说明 https://opendocs.alipay.com/open/194/106039/
  511. $aliPattern = '/^(25|26|27|28|29|30)\d{14,22}$/';
  512. if (!preg_match($wxPattern, $authCode) && !preg_match($aliPattern, $authCode)) {
  513. $msg = '付款码错误,请使用微信或支付宝付款码';
  514. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  515. //noticeUtil::push($remind . ' 编号009', '15280215347');
  516. util::success(['returnStatus' => 'FAILURE'], $msg);
  517. }
  518. } else {
  519. if (empty($authCode)) {
  520. util::fail('没有获取到支付码');
  521. }
  522. }
  523. $orderSn = $order->orderSn ?? '';
  524. $lsCodePayErrorKey = 'ls_code_pay_error_' . $id;
  525. $hasFailPay = Yii::$app->redis->executeCommand('GET', [$lsCodePayErrorKey]);
  526. //前面有付失败过,要重新生成单号
  527. if (!empty($hasFailPay)) {
  528. $oldOrderSn = $order->orderSn;
  529. $orderSn = orderSn::getOrderSn();
  530. $order->orderSn = $orderSn;
  531. $order->save();
  532. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  533. }
  534. $subject = '购买花材 ' . $orderSn;
  535. $totalFee = $order->mainPay ?? 0;
  536. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  537. try {
  538. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  539. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  540. $params = [
  541. 'appid' => 'OP00002119',
  542. 'serial_no' => '018b08cfddbd',
  543. 'merchant_no' => $shop->lklSjNo,
  544. 'term_no' => $shop->lklScanTermNo,
  545. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  546. 'lklCertificatePath' => $lklCertificatePath,
  547. ];
  548. $laResource = new Lakala($params);
  549. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  550. $scanParams = [
  551. 'orderSn' => $orderSn,
  552. 'amount' => $totalFee,
  553. 'capitalType' => $capitalType,
  554. 'notifyUrl' => $notifyUrl,
  555. 'subject' => $subject,
  556. 'authCode' => $authCode,
  557. ];
  558. // 复杂分支/关键逻辑:在调用外部支付接口前不开启事务,防止网络延迟卡死数据库连接
  559. $response = $laResource->scanPay($scanParams);
  560. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  561. // 复杂分支/关键逻辑:支付成功后,开启数据库事务,确保本地订单状态更新的原子性
  562. $connection = Yii::$app->db;
  563. $transaction = $connection->beginTransaction();
  564. try {
  565. $account_type = $response['resp_data']['account_type'] ?? '';
  566. $payWayType = dict::getDict('payWay', 'wxPay');
  567. if ($account_type == 'WECHAT') {
  568. $payWayType = dict::getDict('payWay', 'wxPay');
  569. }
  570. if ($account_type == 'ALIPAY') {
  571. $payWayType = dict::getDict('payWay', 'alipay');
  572. }
  573. $order->payWay = $payWayType;
  574. $transactionId = $response['resp_data']['trade_no'] ?? '';
  575. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  576. $order->save();
  577. $attach = '';
  578. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  579. $transaction->commit();
  580. } catch (\Exception $e) {
  581. $transaction->rollBack();
  582. throw $e;
  583. }
  584. //解决重复通知
  585. $cacheKey = 'hd_shop_order_pay_' . $orderSn;
  586. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  587. if (empty($has)) {
  588. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  589. $newOrder = OrderClass::getById($id, true);
  590. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  591. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  592. $newOrder->status = 4;
  593. $newOrder->save();
  594. }
  595. //打印小票
  596. OrderClass::onlinePrint($newOrder);
  597. HdDeliveryOrderClass::payAfter($newOrder);
  598. //语音播报
  599. ShopExtClass::hdGatheringReport($newOrder);
  600. $shopId = $newOrder->shopId ?? 0;
  601. $shop = ShopClass::getById($shopId, true);
  602. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  603. }
  604. util::success(['returnStatus' => 'SUCCESS']);
  605. } else {
  606. //标记有没付成功的次数,原因有可能是余额不足等
  607. Yii::$app->redis->executeCommand('SETEX', [$lsCodePayErrorKey, 1200, 'hasFail']);
  608. $msg = $response['msg'] ?? '';
  609. $retCode = $response['code'] ?? '';
  610. $fullMsg = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  611. if ($retCode == 'BBS10000' || $retCode == 'BBS11105') {
  612. $shopId = $order->shopId;
  613. ShopExtClass::remindInputPassword($shopId);
  614. }
  615. //noticeUtil::push($fullMsg . ' ' . $retCode . ' 编号008', '15280215347');
  616. util::success(['returnStatus' => 'FAILURE', 'returnCode' => $retCode], $msg);
  617. }
  618. } catch (\Exception $e) {
  619. Yii::error("零售端支付失败原因:" . $e->getMessage());
  620. util::fail('支付失败');
  621. }
  622. }
  623. //开单操作 ssh 20220316
  624. public function actionCreateOrder()
  625. {
  626. $post = Yii::$app->request->post();
  627. $post['sjId'] = $this->sjId;
  628. $post['shopId'] = $this->shopId;
  629. $post['mainId'] = $this->mainId ?? 0;
  630. $shop = $this->shop;
  631. if ($shop->memberLevelSet == 0) {
  632. //util::fail('请先设置会员等级');
  633. }
  634. $now = time();
  635. $orderValidTime = 600;
  636. $expireTime = $now + $orderValidTime;
  637. $post['deadline'] = $expireTime;
  638. $post['staffId'] = $this->shopAdminId ?? 0;
  639. $post['staffName'] = $this->shopAdmin->name ?? '';
  640. $post['flowerNum'] = isset($post['flowerNum']) && $post['flowerNum'] > 0 ? $post['flowerNum'] : 0;
  641. $version = $post['version'] ?? 0; //验证已移至 CreateOrderForm
  642. if ($version < 3) {
  643. util::fail('请升级版本,或用小程序');
  644. }
  645. //默认情况开单员工和收款员工是同个人
  646. $staffId = $this->shopAdminId ?? 0;
  647. $staffName = $this->shopAdmin->name ?? '';
  648. if (empty($post['shopAdminId'])) {
  649. $post['shopAdminId'] = $staffId;
  650. $post['shopAdminName'] = $staffName;
  651. }
  652. if (empty($post['getStaffId'])) {
  653. $post['getStaffId'] = $staffId;
  654. $post['getStaffName'] = $this->shopAdmin->name ?? '';
  655. }
  656. $groupId = !empty($post['groupId']) ? $post['groupId'] : 0;
  657. $post['fromType'] = $post['fromType'] ?? 1;
  658. if ($post['fromType'] == dict::getDict('fromType', 'friend')) {
  659. if (empty($post['bookName'])) {
  660. util::fail('请填写订花人姓名');
  661. }
  662. }
  663. $customId = $post['customId'] ?? 0;
  664. $custom = CustomClass::getById($customId, true);
  665. if (empty($custom)) {
  666. util::fail('没有找到客户哦');
  667. }
  668. $hdId = $custom->hdId ?? 0;
  669. $hd = HdClass::getById($hdId, true);
  670. if (empty($hd)) {
  671. util::fail('客户对应的花店信息缺失,编号869');
  672. }
  673. $hdName = $hd->name ?? '';
  674. $post['hdId'] = $hdId;
  675. $post['hdName'] = $hdName;
  676. $customName = $custom->name ?? '';
  677. $post['customName'] = $customName;
  678. $post['customNamePy'] = stringUtil::py($customName);
  679. if (!empty($post['receiveMobile'])) {
  680. if (!stringUtil::isMobile($post['receiveMobile'])) {
  681. util::fail('请填写正确的收花人手机号');
  682. }
  683. }
  684. if (!empty($post['bookMobile'])) {
  685. if (!stringUtil::isMobile($post['bookMobile'])) {
  686. util::fail('请填写正确的订花人手机号');
  687. }
  688. }
  689. $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
  690. $post['sendType'] = $post['sendType'] ?? 1;
  691. $forward = $post['forward'] ?? 0;
  692. if ($forward == 1) {
  693. if ($hasPay != 1) {
  694. util::fail('红冲订单只能走线下转账');
  695. }
  696. $historyDate = $post['historyDate'] ?? '';
  697. if (!empty($historyDate)) {
  698. if ($historyDate != date("Y-m-d")) {
  699. util::fail('红冲订单不能修改账单日期,只能今天');
  700. }
  701. }
  702. }
  703. $productJson = $post['product'] ?? '';
  704. $productList = [];
  705. if (!empty($productJson)) {
  706. $productList = json_decode($productJson, true);
  707. }
  708. if (empty($productList) && empty($groupId)) {
  709. //商家手机上开单并生成制作单
  710. if (!empty($post['unitGoodsPrice'])) {
  711. util::fail('此功能停用,有需要请联系管理员');
  712. $unitGoodsPrice = $post['unitGoodsPrice'];
  713. if (!is_numeric($unitGoodsPrice)) {
  714. util::fail('请输入正确的单价');
  715. }
  716. $productList = GoodsClass::orderCreateGoods($post);
  717. }
  718. }
  719. //直接收款
  720. $zjGathering = $post['zjGathering'] ?? 0;
  721. if ($zjGathering == 1) {
  722. $lsGoodsPrice = $post['lsGoodsPrice'] ?? 0;
  723. if (!is_numeric($lsGoodsPrice) || $lsGoodsPrice <= 0) {
  724. util::fail('请填写价格');
  725. }
  726. //直接收款不需要打印小票
  727. $post['needPrint'] = dict::getDict('needPrint', 'noNeed');
  728. $shopId = $this->shopId;
  729. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  730. $zjGatheringItem = !empty($ext) ? $ext->zjGatheringItem : 0;
  731. if (empty($zjGatheringItem)) {
  732. util::fail('请设置直接收款的商品');
  733. }
  734. $zjGatheringItemInfo = ProductClass::getById($zjGatheringItem, true);
  735. if (empty($zjGatheringItemInfo)) {
  736. util::fail('请设置直接收款的商品哈');
  737. }
  738. $productList = [['productId' => $zjGatheringItem, 'unitType' => 0, 'num' => 1, 'property' => '1', 'unitPrice' => $lsGoodsPrice]];
  739. }
  740. $callErrand = $post['callErrand'] ?? 0;
  741. if ($callErrand == 1) {
  742. $shopId = $this->shopId;
  743. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  744. if (!empty($shopExt) && $shopExt->orderFlow == 0) {
  745. util::fail('下单后要变待发货,才能直接发跑腿');
  746. }
  747. }
  748. $connection = Yii::$app->db;
  749. $transaction = $connection->beginTransaction();
  750. try {
  751. $post['product'] = $productList;
  752. $reduceStock = $post['reduceStock'] ?? 0;
  753. if ($reduceStock == 1) {
  754. //如果扣除库,则走另外一条路
  755. $return = OrderClass::reduceMyStock($post, $this->shop, $custom);
  756. $transaction->commit();
  757. util::success($return);
  758. }
  759. //解决开单提交订单时,别人修改价格,造成提交价格不是真实卖价问题!!
  760. $dealPrice = $post['dealPrice'] ?? 0;
  761. //解决重复提交
  762. util::checkRepeatCommit($this->adminId . '_' . $dealPrice, 3);
  763. $totalNum = 0;
  764. if ($dealPrice == 0) {
  765. $productIds = [];
  766. $hsIds = [];
  767. foreach ($productList as $pv) {
  768. $property = $pv['property'] ?? 0;
  769. $puId = $pv['productId'] ?? 0;
  770. if ($property == 0) {
  771. $hsIds[] = $puId;
  772. } else {
  773. $productIds[] = $puId;
  774. }
  775. }
  776. $itemInfo = [];
  777. if (!empty($productIds)) {
  778. $itemInfo = ProductClass::getByIds($productIds, null, 'id');
  779. }
  780. $hsInfo = [];
  781. if (!empty($hsIds)) {
  782. $hsInfo = GoodsClass::getByIds($hsIds, null, 'id');
  783. }
  784. $diff = [];
  785. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  786. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  787. $level = 0;
  788. foreach ($productList as $currentProduct) {
  789. $property = $currentProduct['property'] ?? 0;
  790. $currentPrice = $currentProduct['unitPrice'] ?? 0;
  791. $currentId = $currentProduct['productId'] ?? 0;
  792. if ($property == 1) {
  793. $systemInfo = $itemInfo[$currentId] ?? [];
  794. if (!empty($systemInfo)) {
  795. $name = $systemInfo['name'] ?? '';
  796. $systemPrice = \bizGhs\product\classes\ProductClass::getFinalPrice($systemInfo, $level, $priceMap, $addPriceMap);
  797. if (floatval($currentPrice) != floatval($systemPrice)) {
  798. $diff[] = [
  799. 'name' => $name,
  800. 'price' => $systemPrice,
  801. 'kdPrice' => $currentPrice,
  802. ];
  803. }
  804. }
  805. } else {
  806. $systemInfo = $hsInfo[$currentId] ?? [];
  807. if (!empty($systemInfo)) {
  808. $params = [];
  809. $name = $systemInfo['name'] ?? '';
  810. $hsData = GoodsClass::getFinalPrice($systemInfo, $shop, $custom, $params);
  811. $systemPrice = $hsData['price'] ?? 0;
  812. if ($systemInfo['priceType'] == 1) {
  813. if (floatval($currentPrice) != floatval($systemPrice)) {
  814. $diff[] = [
  815. 'name' => $name,
  816. 'price' => $systemPrice,
  817. 'kdPrice' => $currentPrice,
  818. ];
  819. }
  820. }
  821. }
  822. }
  823. $num = $currentProduct['num'];
  824. $totalNum = bcadd($totalNum, $num);
  825. }
  826. if (!empty($diff)) {
  827. util::success(['diff' => $diff, 'respondType' => 'priceError']);
  828. }
  829. }
  830. //红包使用,多有处,关键词 use_hb_action
  831. $hbId = $post['hbId'] ?? 0;
  832. $hb = null;
  833. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  834. $hb = HbClass::getById($hbId, true);
  835. if (!empty($hb)) {
  836. if ($hb->customId != $customId) {
  837. util::fail('不是这个客户的红包');
  838. }
  839. if ($hb->amount != $post['hbAmount']) {
  840. util::fail('红包错误'); //红包数据可能被串改
  841. }
  842. if ($hb->status == 1) {
  843. util::fail('红包已使用');
  844. }
  845. if ($hb->status == -1) {
  846. util::fail('红包已作废');
  847. }
  848. if ($hb->endTime < time()) {
  849. $hb->status = -1;
  850. $hb->save();
  851. util::fail('红包已失效');
  852. }
  853. if ($hb->beginTime > time()) {
  854. util::fail('红包可使用期未到');
  855. }
  856. if ($this->shop->rechargeWeal == 3) {
  857. // 判断支付方式是否是余额支付
  858. if ($hasPay != dict::getDict('hasPay', 'balance')) {
  859. util::fail('用红包要用余额支付');
  860. } else {
  861. if ($custom->balance < $post['modifyPrice']) {
  862. util::fail('用红包要用余额支付(您的余额不足)');
  863. }
  864. }
  865. }
  866. } else {
  867. Yii::error('没有找到红包,hbId: ', $hbId . ' ' . __METHOD__);
  868. util::fail('红包无效');
  869. }
  870. }
  871. $post['bigNum'] = $totalNum;
  872. //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
  873. $return = OrderService::createHdOrder($post, $custom, $hasPay);
  874. if (!empty($hb)) {
  875. $hb->status = 1;
  876. $hb->orderId = $return->id;
  877. $hb->save();
  878. }
  879. $staff = $this->shopAdmin;
  880. //售后开付款单,库存要变化,关系要建立,多处需要同步修改 sh_pay_change ssh
  881. OrderClass::shPayChange($return, $shop, $staff);
  882. //打印小票和语音播报等使用
  883. $id = $return->id ?? 0;
  884. $order = OrderClass::getById($id, true);
  885. //如果需要生成制作单
  886. $needWork = $post['needWork'] ?? 0;
  887. if ($needWork == 1) {
  888. $main = $this->main;
  889. WorkClass::needWork($order, $main);
  890. $has = WorkClass::getByCondition(['orderId' => $id], true);
  891. if (!empty($has)) {
  892. $return->hasWork = 1;
  893. $return->save();
  894. }
  895. }
  896. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  897. if ($order->getGoods == 1 && $order->sendType == 1 && $order->status == 2) {
  898. $order->status = 4;
  899. $order->save();
  900. }
  901. $transaction->commit();
  902. if ($order->fromType == 3 || $order->fromType == 4) {
  903. //除了客服号下单和美团下单,其它情况允许打小票
  904. } else {
  905. //前台打小票
  906. OrderClass::onlinePrint($order);
  907. }
  908. //订单发跑腿流程
  909. HdDeliveryOrderClass::prepareAskData($post, $order);
  910. //前台提示收款多少钱
  911. ShopExtClass::hdGatheringReport($order);
  912. //前台提醒出示付款码
  913. if (isset($order->status) && $order->status == 1) {
  914. if (isset($post['isCashier']) && $post['isCashier'] == 1) {
  915. ShopExtClass::pleasePayReport($order);
  916. }
  917. }
  918. $shopId = $order->shopId ?? 0;
  919. $shop = ShopClass::getById($shopId, true);
  920. WxMessageClass::gatheringIncomeInform($shop, $order);
  921. if ($needWork == 1) {
  922. //新制作单提示
  923. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  924. ShopExtClass::newWorkRemind($shopExt, $order);
  925. }
  926. util::success($return);
  927. } catch (\Exception $e) {
  928. $transaction->rollBack();
  929. Yii::error("下单失败原因:" . $e->getMessage());
  930. util::fail('下单失败');
  931. }
  932. }
  933. //下单要用到的相关信息 ssh 2019.12.6
  934. public function actionOrderRelate()
  935. {
  936. $regionTree = RegionService::tree();
  937. $shop = $this->shop->attributes;
  938. $freight = MerchantExtendService::getFreight($this->sjExtend);
  939. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  940. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  941. util::success($out);
  942. }
  943. //余额支付 ssh 2019.12.6
  944. public function actionBalancePay()
  945. {
  946. $post = Yii::$app->request->post();
  947. $orderSn = $post['orderSn'] ?? 0;
  948. $payPassword = $post['payPassword'] ?? 0;
  949. $couponId = $post['couponId'] ?? 0;
  950. $order = OrderService::getByOrderSn($orderSn);
  951. $userId = $this->adminId;
  952. $user = UserService::getUserInfo($userId);
  953. //验证支付密码是否正确
  954. UserService::validPayPassword($payPassword, $user);
  955. //支付前验证订单有效性
  956. OrderService::checkBeforePay($order);
  957. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  958. $totalFee = $order['prePrice'];
  959. $sourceType = 0;
  960. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  961. $actPrice = $discountData['price'];
  962. $callbackParams = [];
  963. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  964. $balance = $respond['balance'] ?? 0;
  965. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  966. }
  967. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  968. public function actionWxPay()
  969. {
  970. ini_set('date.timezone', 'Asia/Shanghai');
  971. $post = Yii::$app->request->post();
  972. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  973. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  974. $order = OrderService::getByOrderSn($orderSn);
  975. $orderId = $order['id'];
  976. //验证优惠券是否还有效
  977. if (!empty($couponId)) {
  978. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  979. }
  980. //支付前验证订单有效性
  981. OrderService::checkBeforePay($order);
  982. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  983. $totalFee = $order['realPrice'];
  984. //小程序使用miniOpenId
  985. if (httpUtil::isMiniProgram()) {
  986. $openId = $this->user['miniOpenId'];
  987. } else {
  988. $openId = $this->user['openId'];
  989. }
  990. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  991. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  992. $wxPayType = 0;
  993. if (httpUtil::isMiniProgram()) {
  994. $wxPayType = 1;
  995. }
  996. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  997. //订单30分钟后过期
  998. $now = time();
  999. $expireTime = $now + 1800;
  1000. $wx = Yii::getAlias("@vendor/weixin");
  1001. require_once($wx . '/lib/WxPay.Api.php');
  1002. require_once($wx . '/example/WxPay.JsApiPay.php');
  1003. $input = new \WxPayUnifiedOrder();
  1004. $input->SetBody($name);
  1005. $input->SetOut_trade_no($orderSn);
  1006. $input->SetTotal_fee($totalFee * 100);
  1007. $input->SetTime_start(date("YmdHis", $now));
  1008. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  1009. $input->SetTime_expire(date("YmdHis", $expireTime));
  1010. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1011. $input->SetTrade_type("JSAPI");
  1012. //花卉宝代为申请的微信支付
  1013. $merchantExtend = $this->sjExtend->attributes;
  1014. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1015. $input->SetSub_openid($openId);
  1016. } else {
  1017. $input->SetOpenid($openId);
  1018. }
  1019. //小程序使用miniAppId
  1020. if (httpUtil::isMiniProgram()) {
  1021. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1022. }
  1023. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1024. $tools = new \JsApiPay();
  1025. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1026. $newParams = json_decode($jsApiParameters, true);
  1027. //已请求微信不能修改价格
  1028. $updateData = [];
  1029. $updateData['modPrice'] = 0;
  1030. if (empty($order['deadline'])) {
  1031. $updateData['deadline'] = $expireTime;
  1032. }
  1033. OrderService::updateById($orderId, $updateData);
  1034. util::success($newParams);
  1035. }
  1036. //快捷付款订单
  1037. public function actionFastPay()
  1038. {
  1039. ini_set('date.timezone', 'Asia/Shanghai');
  1040. $post = Yii::$app->request->post();
  1041. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  1042. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
  1043. //验证门店是否有效
  1044. $shopInfo = ShopService::getById($shopId);
  1045. ShopService::valid($shopInfo, $this->sjId);
  1046. $post['shopId'] = $shopId;
  1047. //默认门店订单
  1048. $store = isset($post['store']) ? $post['store'] : 1;
  1049. $post['store'] = $store;
  1050. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  1051. $sourceType = $this->isWx ? 0 : 1;
  1052. if (httpUtil::isMiniProgram()) {
  1053. $sourceType = 2;
  1054. }
  1055. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  1056. //兼容旧系统sourceType=3表示朋友圈来源
  1057. $fromType = $sourceType == 3 ? 2 : 0;
  1058. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  1059. $post['userId'] = $this->adminId;
  1060. $custom = $this->custom;
  1061. $post['bookName'] = $custom['userName'] ?? '';
  1062. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  1063. $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
  1064. $post['bookMobile'] = $bookMobile;
  1065. $prePrice = round($post['prePrice'], 2);
  1066. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1067. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  1068. $actPrice = $discountData['price'];
  1069. $post['discountType'] = $discountData['discountType'];
  1070. $post['discountAmount'] = $discountData['discountAmount'];
  1071. $post['actPrice'] = $actPrice;
  1072. $post['realPrice'] = $actPrice;
  1073. $post['payStyle'] = 0;
  1074. $post['sjId'] = $this->sjId;
  1075. $now = time();
  1076. $expireTime = $now + 300;//订单5分钟后过期
  1077. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1078. $post['deadline'] = $expireTime;
  1079. if ($actPrice <= 0) {
  1080. util::fail('请填写正确的金额');
  1081. }
  1082. //微信支付订单提交不能修改价格
  1083. $post['modPrice'] = $this->isWx ? 0 : 1;
  1084. $post['sourceType'] = $sourceType;
  1085. $post['goodsNum'] = 1;
  1086. $post['fromType'] = $fromType;
  1087. $order = OrderService::addOrder($post);
  1088. $orderId = $order['id'];
  1089. $orderSn = $order['orderSn'];
  1090. $sjId = $this->sjId;
  1091. if ($payWay == 0) {
  1092. $orderId = $order['id'];
  1093. $name = '购买商品';
  1094. $totalFee = $actPrice;
  1095. $user = UserService::getById($this->adminId);
  1096. $openId = isset($user['openId']) ? $user['openId'] : 0;
  1097. if (httpUtil::isMiniProgram()) {
  1098. //小程序使用miniOpenId
  1099. $openId = $user['miniOpenId'];
  1100. }
  1101. if (empty($openId)) {
  1102. util::fail('没有找到客户的openId');
  1103. }
  1104. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1105. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  1106. $wxPayType = 0;
  1107. if (httpUtil::isMiniProgram()) {
  1108. $wxPayType = 1;
  1109. }
  1110. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  1111. $wx = Yii::getAlias("@vendor/weixin");
  1112. require_once($wx . '/lib/WxPay.Api.php');
  1113. require_once($wx . '/example/WxPay.JsApiPay.php');
  1114. $input = new \WxPayUnifiedOrder();
  1115. $input->SetBody($name);
  1116. $input->SetOut_trade_no($orderSn);
  1117. $input->SetTotal_fee($totalFee * 100);
  1118. $input->SetTime_start(date("YmdHis", $now));
  1119. $input->SetAttach($attach);
  1120. //设置订单有效期5分钟
  1121. $input->SetTime_expire(date("YmdHis", $expireTime));
  1122. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1123. $input->SetTrade_type("JSAPI");
  1124. //花卉宝代为申请的微信支付
  1125. $merchantExtend = $this->sjExtend->attributes;
  1126. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1127. $input->SetSub_openid($openId);
  1128. } else {
  1129. $input->SetOpenid($openId);
  1130. }
  1131. //小程序使用miniAppId
  1132. if (httpUtil::isMiniProgram()) {
  1133. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1134. }
  1135. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  1136. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1137. $tools = new \JsApiPay();
  1138. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1139. $newParams = json_decode($jsApiParameters, true);
  1140. $newParams['orderId'] = $orderId;
  1141. util::success($newParams);
  1142. } elseif ($payWay == 1) {
  1143. $extend = MerchantExtendService::getBySjId($sjId);
  1144. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  1145. util::fail('支付宝付款即将开通...');
  1146. }
  1147. $config = [
  1148. //应用ID,您的APPID。
  1149. 'app_id' => $extend['alipayPId'],
  1150. //商户私钥,您的原始格式RSA私钥
  1151. 'merchant_private_key' => $extend['alipayKey'],
  1152. //异步通知地址
  1153. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  1154. //同步跳转
  1155. 'return_url' => "",
  1156. //编码格式
  1157. 'charset' => "UTF-8",
  1158. //签名方式
  1159. 'sign_type' => "RSA2",
  1160. //支付宝网关
  1161. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  1162. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  1163. 'alipay_public_key' => $extend['alipayPublicKey'],
  1164. ];
  1165. Yii::info(json_encode($config) . ' aplipay config');
  1166. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  1167. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  1168. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  1169. $totalFee = $order['realPrice'];
  1170. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  1171. $subject = '购买商品';//订单名称,必填
  1172. $total_amount = $totalFee;//付款金额,必填
  1173. $body = '';//商品描述,可空
  1174. $timeout_express = "1m";//超时时间
  1175. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1176. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  1177. $passBackParams = urlencode($passBackParams);
  1178. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  1179. $payRequestBuilder->setBody($body);
  1180. $payRequestBuilder->setSubject($subject);
  1181. $payRequestBuilder->setOutTradeNo($out_trade_no);
  1182. $payRequestBuilder->setTotalAmount($total_amount);
  1183. $payRequestBuilder->setTimeExpress($timeout_express);
  1184. //在异步通知时将该参数原样返回
  1185. $payRequestBuilder->setPassbackParams($passBackParams);
  1186. //同步通知
  1187. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  1188. //异步通知
  1189. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  1190. $payResponse = new \AlipayTradeService($config);
  1191. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  1192. //直接将支付宝的html返回给前端
  1193. echo $result;
  1194. } elseif ($payWay == 2) {
  1195. //余额支付
  1196. util::fail('暂不支持');
  1197. } else {
  1198. util::fail('无效的支付方式');
  1199. }
  1200. }
  1201. //订单评价
  1202. public function actionComment()
  1203. {
  1204. $post = Yii::$app->request->post();
  1205. $id = $post['id'];
  1206. $order = OrderService::getById($id);
  1207. OrderService::valid($order, $this->mainId);
  1208. if ($order['grade'] > 0) {
  1209. util::fail('您已经评过了');
  1210. }
  1211. OrderService::comment($post);
  1212. util::complete('提交成功');
  1213. }
  1214. //订单详情,不需要登陆可以查看,要有盐,给跑腿上查看订单信息用的
  1215. public function actionInfo()
  1216. {
  1217. $get = Yii::$app->request->get();
  1218. $id = $get['id'] ?? 0;
  1219. $salt = $get['salt'] ?? '';
  1220. $detail = OrderClass::getFullInfo($id);
  1221. if (empty($detail)) {
  1222. util::fail('没有找到订单');
  1223. }
  1224. if (empty($detail['salt'])) {
  1225. util::fail('没有找到订单信息');
  1226. }
  1227. if (empty($salt)) {
  1228. util::fail('请求参数错误呢');
  1229. }
  1230. if ($detail['salt'] != $salt) {
  1231. util::fail('不是你的订单');
  1232. }
  1233. util::success($detail);
  1234. }
  1235. //订单详情
  1236. public function actionDetail()
  1237. {
  1238. $id = Yii::$app->request->get('id', 0);
  1239. $detail = OrderClass::getFullInfo($id);
  1240. OrderService::valid($detail, $this->mainId);
  1241. $forwardMap = [];
  1242. if ($detail['forward'] == 1) {
  1243. //当前单如果已经是红冲订单,则取出其对应的原单
  1244. $map = OrderForwardClass::getByCondition(['shOrderId' => $id], true);
  1245. if (!empty($map)) {
  1246. $originOrderId = $map->orderId ?? 0;
  1247. $forwardMap['orderId'] = $originOrderId;
  1248. }
  1249. }
  1250. $detail['forwardMap'] = $forwardMap;
  1251. $shOrderMap = [];
  1252. if ($detail['hasForward'] == 1) {
  1253. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1254. }
  1255. $detail['shOrderMap'] = $shOrderMap;
  1256. $main = $this->main;
  1257. //是否走红冲订单模式判断 ssh
  1258. $ret = OrderClass::ifShPay($detail, $main, 0);
  1259. $shAddPay = $ret['shAddPay'];
  1260. $shAddPayReason = $ret['shAddPayReason'];
  1261. $detail['shAddPay'] = $shAddPay;
  1262. $detail['shAddPayReason'] = $shAddPayReason;
  1263. util::success($detail);
  1264. }
  1265. public function actionList()
  1266. {
  1267. $get = Yii::$app->request->get();
  1268. $searchText = $get['searchText'] ?? '';
  1269. $shopId = $this->shopId ?? 0;
  1270. if (empty($shopId)) {
  1271. //没有登录不显示数据
  1272. util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
  1273. }
  1274. $where = [];
  1275. $where['shopId'] = $shopId;
  1276. if (!empty($get['customId'])) {
  1277. $where['customId'] = $get['customId'];
  1278. }
  1279. if (!empty($get['ids'])) {
  1280. $stringIds = $get['ids'];
  1281. $newIds = explode(',', $stringIds);
  1282. $where['id'] = ['in', $newIds];
  1283. }
  1284. $status = $get['status'] ?? 0;
  1285. if (!empty($status)) {
  1286. $where['status'] = $get['status'];
  1287. }
  1288. $debt = $get['debt'] ?? -1;
  1289. if ($debt > -1) {
  1290. $where['debt'] = $debt;
  1291. }
  1292. if (!empty($get['shopAdminId'])) {
  1293. $where['shopAdminId'] = $get['shopAdminId'];
  1294. }
  1295. // 按搜索词自动识别:纯数字查货号,否则查姓名
  1296. if (!empty($searchText)) {
  1297. $this->appendOrderListSearchWhere($where, $searchText);
  1298. }
  1299. if (isset($get['repeat']) && $get['repeat'] > -1) {
  1300. $where['repeat'] = $get['repeat'];
  1301. }
  1302. if (!empty($get['searchTime'])) {
  1303. $startTime = $get['startTime'] ?? '';
  1304. $endTime = $get['endTime'] ?? '';
  1305. $period = dateUtil::formatTime($get['searchTime'], $startTime, $endTime);
  1306. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1307. }
  1308. $list = OrderService::getOrderList($where);
  1309. $list['shop'] = $this->shop->attributes ?? [];
  1310. util::success($list);
  1311. }
  1312. //订单归类 ssh 2019.12.17
  1313. public function actionClassify()
  1314. {
  1315. $post = Yii::$app->request->post();
  1316. $id = $post['id'] ?? 0;
  1317. $order = OrderService::getById($id);
  1318. OrderService::valid($order, $this->mainId);
  1319. $categoryId = $post['categoryId'];
  1320. $usageId = $post['usageId'];
  1321. OrderService::classify($id, $categoryId, $usageId);
  1322. util::complete();
  1323. }
  1324. //更新配送单 ssh 2019.12.17
  1325. public function actionUpdateSheet()
  1326. {
  1327. $post = Yii::$app->request->post();
  1328. $id = $post['id'] ?? 0;
  1329. unset($post['id']);
  1330. $order = OrderService::getById($id);
  1331. OrderService::valid($order, $this->mainId);
  1332. OrderService::updateSheet($order, $post);
  1333. util::complete('提交成功');
  1334. }
  1335. //商家收款与发货 ssh 2019.12.18
  1336. public function actionGathering()
  1337. {
  1338. $post = Yii::$app->request->post();
  1339. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  1340. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  1341. $userId = $post['userId'] ?? 0;
  1342. $userInfo = UserService::getById($userId);
  1343. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  1344. util::fail('您选择的客户无效');
  1345. }
  1346. if ($price <= 0) {
  1347. util::fail('请输入金额');
  1348. }
  1349. $post['prePrice'] = $price;
  1350. $post['actPrice'] = $price;
  1351. $post['payWay'] = $payWay;
  1352. $post['sourceType'] = 1;
  1353. $post['userId'] = $userId;
  1354. $post['goodsNum'] = 1;
  1355. $post['orderName'] = '商品';
  1356. $shopId = MerchantService::getDefaultShopId($this->sj);
  1357. $post['shopId'] = $shopId;
  1358. $order = OrderService::addOrder($post);
  1359. $id = $order['id'];
  1360. $orderSn = $order['orderSn'];
  1361. //流水类型列表
  1362. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1363. $callbackParams = [];
  1364. switch ($payWay) {
  1365. case 0:
  1366. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  1367. break;
  1368. case 1:
  1369. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  1370. break;
  1371. case 2:
  1372. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  1373. break;
  1374. default:
  1375. util::fail('无效支付方式');
  1376. }
  1377. util::success($order);
  1378. }
  1379. //免发货管理 ssh 2020.1.6
  1380. public function actionWithoutSend()
  1381. {
  1382. $id = Yii::$app->request->get('id');
  1383. $order = OrderService::getById($id);
  1384. OrderService::valid($order, $this->mainId);
  1385. //配送流程变更
  1386. $currentFlow = OrderSendClass::withoutSend($order);
  1387. util::success(['currentFlow' => $currentFlow]);
  1388. }
  1389. //修改价格 ssh 2020.1.6
  1390. public function actionUpdatePrice()
  1391. {
  1392. $id = Yii::$app->request->get('id');
  1393. $price = Yii::$app->request->get('price', 1);
  1394. $order = OrderService::getById($id);
  1395. OrderService::valid($order, $this->mainId);
  1396. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1397. util::fail('已发起支付,不能修改价格');
  1398. }
  1399. OrderService::updateById($id, ['actPrice' => $price]);
  1400. util::complete('修改成功');
  1401. }
  1402. //配送单 ssh 2020.2.29
  1403. public function actionGetDeliverDetail()
  1404. {
  1405. $id = Yii::$app->request->get('id', 0);
  1406. $order = OrderService::getById($id);
  1407. OrderService::valid($order, $this->mainId);
  1408. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  1409. $reachPeriodId = $order['reachPeriod'];
  1410. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  1411. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  1412. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  1413. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  1414. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  1415. $bookName = '--';
  1416. $bookMobile = '--';
  1417. }
  1418. $data = [
  1419. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  1420. 'orderSn' => $order['orderSn'],
  1421. 'receiveUserName' => $order['receiveUserName'],
  1422. 'receiveMobile' => $order['receiveMobile'],
  1423. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  1424. 'cardInfo' => $order['cardInfo'],
  1425. 'bookMobile' => $bookMobile,
  1426. 'bookName' => $bookName,
  1427. 'remark' => $order['remark'],
  1428. 'sendNum' => $order['sendNum'],
  1429. 'telephone' => 18030142050,
  1430. 'printTime' => '',
  1431. 'img' => '',
  1432. ];
  1433. util::success($data);
  1434. }
  1435. //运费计算 lqh 2021.4.12 暂反回固定
  1436. public function actionFreight()
  1437. {
  1438. util::success(['sedCost' => 10]);
  1439. }
  1440. /**
  1441. * 订单列表搜索条件:纯数字按货号精确匹配,否则按客户姓名模糊匹配
  1442. * @param array $where 查询条件(引用传递)
  1443. * @param string $searchText 搜索关键词
  1444. */
  1445. private function appendOrderListSearchWhere(&$where, $searchText)
  1446. {
  1447. $searchText = trim((string)$searchText);
  1448. if ($searchText === '') {
  1449. return;
  1450. }
  1451. if (preg_match('/^\d+$/', $searchText)) {
  1452. $where['sendNum'] = $searchText;
  1453. return;
  1454. }
  1455. $where['customName'] = ['like', $searchText];
  1456. }
  1457. }