OrderController.php 72 KB

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