OrderController.php 60 KB

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