OrderController.php 62 KB

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