OrderController.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. <?php
  2. namespace hd\controllers;
  3. use biz\shop\classes\ShopExtClass;
  4. use biz\sj\services\MerchantExtendService;
  5. use biz\sj\services\MerchantService;
  6. use bizHd\custom\classes\CustomClass;
  7. use bizHd\goods\classes\GoodsClass;
  8. use bizHd\merchant\services\ShopService;
  9. use bizHd\order\classes\OrderClass;
  10. use bizHd\order\classes\OrderSendClass;
  11. use bizHd\order\services\OrderService;
  12. use bizHd\product\classes\ProductClass;
  13. use bizHd\purchase\classes\PurchaseClass;
  14. use bizHd\saas\services\RegionService;
  15. use bizHd\shop\classes\ShopClass;
  16. use bizHd\user\services\UserService;
  17. use bizHd\work\classes\WorkClass;
  18. use bizHd\wx\classes\WxOpenClass;
  19. use common\components\dict;
  20. use common\components\dateUtil;
  21. use common\components\payUtil;
  22. use common\services\xhPayToolService;
  23. use Yii;
  24. use common\components\util;
  25. use common\components\stringUtil;
  26. use bizHd\promote\services\CouponService;
  27. use common\components\httpUtil;
  28. use biz\wx\classes\WxMessageClass;
  29. use common\components\lakala\Lakala;
  30. class OrderController extends BaseController
  31. {
  32. public $guestAccess = ['order-relate', 'fast-pay', 'create-order', 'list'];
  33. //取消订单 ssh 20221231
  34. public function actionCancel()
  35. {
  36. $get = Yii::$app->request->get();
  37. $id = $get['id'] ?? 0;
  38. $order = OrderClass::getById($id, true);
  39. OrderClass::valid($order, $this->mainId);
  40. $deadTime = $order->deadline ?? 0;
  41. $current = time();
  42. $diff = bcsub($deadTime, $current);
  43. if ($diff < 60) {
  44. util::fail('60秒后将自动取消');
  45. }
  46. $connection = Yii::$app->db;
  47. $transaction = $connection->beginTransaction();
  48. try {
  49. OrderClass::setExpire($order, true);
  50. $transaction->commit();
  51. util::complete();
  52. } catch (\Exception $exception) {
  53. $transaction->rollBack();
  54. Yii::info("取消原因:" . $exception->getMessage());
  55. util::fail('取消失败');
  56. }
  57. }
  58. //修改订单 ssh 20220926
  59. public function actionUpdate()
  60. {
  61. $post = Yii::$app->request->post();
  62. $id = $post['id'] ?? 0;
  63. $order = OrderClass::getById($id, true);
  64. OrderClass::valid($order, $this->mainId);
  65. unset($post['id']);
  66. if ($order->status == 3) {
  67. util::fail('订单已配送');
  68. }
  69. if ($order->status == 4) {
  70. util::fail('订单已完成');
  71. }
  72. if ($order->status == 5) {
  73. util::fail('订单已取消');
  74. }
  75. if ($order->fromType == 4) {
  76. util::fail('请在美团APP上修改');
  77. }
  78. $address = $post['address'] ?? '';
  79. $floor = $post['floor'] ?? '';
  80. $post['fullAddress'] = $address . $floor;
  81. OrderClass::updateById($id, $post);
  82. $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  83. $remark = $post['remark'] ?? '';
  84. $reachDate = $post['reachDate'] ?? '';
  85. $reachPeriod = $post['reachPeriod'] ?? '';
  86. $cardInfo = $post['cardInfo'] ?? '';
  87. $anonymity = $post['anonymity'] ?? 0;
  88. $bookName = $post['bookName'] ?? '';
  89. if (!empty($workList)) {
  90. foreach ($workList as $work) {
  91. $work->remark = $remark;
  92. $work->reachDate = $reachDate;
  93. $work->reachPeriod = $reachPeriod;
  94. $work->cardInfo = $cardInfo;
  95. $work->anonymity = $anonymity;
  96. $work->bookName = $bookName;
  97. $work->save();
  98. }
  99. }
  100. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  101. ShopExtClass::orderUpdateRemind($shopExt, $order);
  102. util::complete();
  103. }
  104. //客户欠款的订单 ssh 2021.2.4
  105. public function actionDebtList()
  106. {
  107. $get = Yii::$app->request->get();
  108. $id = $get['id'] ?? 0;
  109. $info = CustomClass::getById($id, true);
  110. CustomClass::valid($info, $this->shopId);
  111. $where = ['customId' => $id, 'debt' => 1];
  112. $searchTime = $get['searchTime'] ?? '';
  113. if (!empty($searchTime)) {
  114. $startTime = $get['startTime'] ?? '';
  115. $endTime = $get['endTime'] ?? '';
  116. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  117. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  118. }
  119. $list = OrderClass::getAllByCondition($where, 'addTime DESC', ['id', 'orderSn', 'actPrice', 'addTime', 'remainDebtPrice']);
  120. $result = ['customInfo' => $info, 'list' => $list];
  121. util::success($result);
  122. }
  123. //发货
  124. public function actionSend()
  125. {
  126. $get = Yii::$app->request->get();
  127. $id = isset($get['id']) ? $get['id'] : 0;
  128. $order = OrderClass::getById($id, true);
  129. if (empty($order)) {
  130. util::fail('没有找到订单');
  131. }
  132. OrderClass::valid($order, $this->mainId);
  133. if ($order->status != 2) {
  134. util::fail('订单不是待发货状态');
  135. }
  136. $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  137. if (!empty($workList)) {
  138. $unComplete = false;
  139. foreach ($workList as $work) {
  140. if ($work->status != 1) {
  141. $unComplete = true;
  142. }
  143. }
  144. if ($unComplete == true) {
  145. util::fail('还有制作单没有完成');
  146. }
  147. }
  148. $order->status = 4;
  149. $order->save();
  150. util::complete('操作成功');
  151. }
  152. //打印订单 ssh 20220601
  153. public function actionPrintOrder()
  154. {
  155. $get = Yii::$app->request->get();
  156. $id = isset($get['id']) ? $get['id'] : 0;
  157. $order = OrderClass::getById($id, true);
  158. if (empty($order)) {
  159. util::fail('没有找到订单');
  160. }
  161. OrderClass::valid($order, $this->mainId);
  162. OrderClass::onlinePrint($order, true);
  163. util::complete();
  164. }
  165. //微信和支付宝付款码支付复查 ssh 20220422
  166. public function actionCodePayCheck()
  167. {
  168. ini_set('date.timezone', 'Asia/Shanghai');
  169. header("Content-type: text/html; charset=utf-8");
  170. $get = Yii::$app->request->get();
  171. $id = isset($get['id']) ? $get['id'] : 0;
  172. $order = OrderClass::getById($id, true);
  173. OrderClass::valid($order, $this->mainId);
  174. $orderSn = $order->orderSn ?? '';
  175. $totalFee = $order->mainPay ?? 0;
  176. if ($order->status == OrderClass::ORDER_STATUS_COMPLETE) {
  177. util::success(['returnStatus' => 'SUCCESS']);
  178. }
  179. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  180. util::complete('订单不是待付款状态');
  181. }
  182. $connection = Yii::$app->db;
  183. $transaction = $connection->beginTransaction();
  184. try {
  185. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  186. $shop = $this->shop;
  187. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  188. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  189. $params = [
  190. 'appid' => 'OP00002119',
  191. 'serial_no' => '018b08cfddbd',
  192. 'merchant_no' => $shop->lklSjNo,
  193. 'term_no' => $shop->lklScanTermNo,
  194. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  195. 'lklCertificatePath' => $lklCertificatePath,
  196. ];
  197. $laResource = new Lakala($params);
  198. $scanParams = ['orderSn' => $orderSn,];
  199. $response = $laResource->query($scanParams);
  200. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  201. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  202. $payWayType = dict::getDict('payWay', 'wxPay');
  203. $account_type = $response['resp_data']['account_type'] ?? '';
  204. if ($account_type == 'WECHAT') {
  205. $payWayType = dict::getDict('payWay', 'wxPay');
  206. }
  207. if ($account_type == 'ALIPAY') {
  208. $payWayType = dict::getDict('payWay', 'alipay');
  209. }
  210. $transactionId = $response['resp_data']['trade_no'] ?? '';
  211. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  212. $order->save();
  213. $attach = '';
  214. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  215. $transaction->commit();
  216. //打印小票和语音播报
  217. $newOrder = OrderClass::getById($id, true);
  218. OrderClass::onlinePrint($newOrder);
  219. ShopExtClass::hdGatheringReport($newOrder);
  220. $shopId = $newOrder->shopId ?? 0;
  221. $shop = ShopClass::getById($shopId, true);
  222. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  223. util::success(['returnStatus' => 'SUCCESS']);
  224. } else {
  225. util::complete('未知状态..');
  226. }
  227. }
  228. util::complete('未知状态..');
  229. } catch (\Exception $e) {
  230. $transaction->rollBack();
  231. util::complete('支付失败');
  232. }
  233. }
  234. //微信和支付宝付款码支付 ssh 2021.4.11
  235. public function actionCodePay()
  236. {
  237. ini_set('date.timezone', 'Asia/Shanghai');
  238. header("Content-type: text/html; charset=utf-8");
  239. $get = Yii::$app->request->get();
  240. $id = isset($get['id']) ? $get['id'] : 0;
  241. $order = OrderClass::getById($id, true);
  242. OrderClass::valid($order, $this->mainId);
  243. $authCode = (string)$get['authCode'] ?? '';
  244. if (empty($authCode)) {
  245. util::fail('没有获取到支付码');
  246. }
  247. $orderSn = $order->orderSn ?? '';
  248. $subject = '购买花材';
  249. $totalFee = $order->mainPay ?? 0;
  250. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  251. $connection = Yii::$app->db;
  252. $transaction = $connection->beginTransaction();
  253. try {
  254. $shop = $this->shop;
  255. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  256. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  257. $params = [
  258. 'appid' => 'OP00002119',
  259. 'serial_no' => '018b08cfddbd',
  260. 'merchant_no' => $shop->lklSjNo,
  261. 'term_no' => $shop->lklScanTermNo,
  262. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  263. 'lklCertificatePath' => $lklCertificatePath,
  264. ];
  265. $laResource = new Lakala($params);
  266. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  267. $scanParams = [
  268. 'orderSn' => $orderSn,
  269. 'amount' => $totalFee,
  270. 'capitalType' => $capitalType,
  271. 'notifyUrl' => $notifyUrl,
  272. 'subject' => $subject,
  273. 'authCode' => $authCode,
  274. ];
  275. $response = $laResource->scanPay($scanParams);
  276. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  277. $account_type = $response['resp_data']['account_type'] ?? '';
  278. $payWayType = dict::getDict('payWay', 'wxPay');
  279. if ($account_type == 'WECHAT') {
  280. $payWayType = dict::getDict('payWay', 'wxPay');
  281. }
  282. if ($account_type == 'ALIPAY') {
  283. $payWayType = dict::getDict('payWay', 'alipay');
  284. }
  285. $order->payWay = $payWayType;
  286. $transactionId = $response['resp_data']['trade_no'] ?? '';
  287. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  288. $order->save();
  289. $attach = '';
  290. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  291. $transaction->commit();
  292. //解决重复通知
  293. $cacheKey = 'hd_shop_order_pay_' . $orderSn;
  294. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  295. if (empty($has)) {
  296. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  297. $newOrder = OrderClass::getById($id, true);
  298. //打印小票
  299. OrderClass::onlinePrint($newOrder);
  300. //语音播报
  301. ShopExtClass::hdGatheringReport($newOrder);
  302. $shopId = $newOrder->shopId ?? 0;
  303. $shop = ShopClass::getById($shopId, true);
  304. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  305. }
  306. util::success(['returnStatus' => 'SUCCESS']);
  307. } else {
  308. $msg = $response['msg'] ?? '';
  309. util::success(['returnStatus' => 'FAILURE'], $msg);
  310. }
  311. } catch (\Exception $e) {
  312. $transaction->rollBack();
  313. util::fail('支付失败');
  314. }
  315. }
  316. //开单操作 ssh 20220316
  317. public function actionCreateOrder()
  318. {
  319. $post = Yii::$app->request->post();
  320. $post['sjId'] = $this->sjId;
  321. $post['shopId'] = $this->shopId;
  322. $post['mainId'] = $this->mainId ?? 0;
  323. $now = time();
  324. $orderValidTime = getenv('ORDER_VALID_TIME') == false ? 600 : getenv('ORDER_VALID_TIME');
  325. $expireTime = $now + $orderValidTime;
  326. $post['deadline'] = $expireTime;
  327. $post['staffId'] = $this->shopAdminId ?? 0;
  328. $post['staffName'] = $this->shopAdmin->name ?? '';
  329. $post['flowerNum'] = isset($post['flowerNum']) && $post['flowerNum'] > 0 ? $post['flowerNum'] : 0;
  330. //默认情况开单员工和收款员工是同个人
  331. $staffId = $this->shopAdminId ?? 0;
  332. $staffName = $this->shopAdmin->name ?? '';
  333. if (isset($post['shopAdminId']) == false || empty($post['shopAdminId'])) {
  334. $post['shopAdminId'] = $staffId;
  335. $post['shopAdminName'] = $staffName;
  336. }
  337. if (isset($post['getStaffId']) == false || empty($post['getStaffId'])) {
  338. $post['getStaffId'] = $staffId;
  339. $post['getStaffName'] = $this->shopAdmin->name ?? '';
  340. }
  341. $groupId = isset($post['groupId']) && !empty($post['groupId']) ? $post['groupId'] : 0;
  342. $post['fromType'] = $post['fromType'] ?? 1;
  343. if ($post['fromType'] == dict::getDict('fromType', 'friend')) {
  344. if (isset($post['bookName']) == false || empty($post['bookName'])) {
  345. util::fail('请填写订花人姓名');
  346. }
  347. }
  348. $customId = isset($post['customId']) && $post['customId'] > 0 ? $post['customId'] : 0;
  349. if (empty($customId)) {
  350. $customId = $this->shop->defaultCustomId ?? 0;
  351. }
  352. $custom = CustomClass::getById($customId);
  353. if (empty($custom)) {
  354. util::fail('没有找到客户哦');
  355. }
  356. $post['customId'] = $customId;
  357. $customName = $custom['name'] ?? '';
  358. $post['customName'] = $customName;
  359. $post['customNamePy'] = stringUtil::py($customName);
  360. if (isset($post['receiveMobile']) && !empty($post['receiveMobile'])) {
  361. if (stringUtil::isMobile($post['receiveMobile']) == false) {
  362. util::fail('请填写正确的收花人手机号');
  363. }
  364. }
  365. if (isset($post['bookMobile']) && !empty($post['bookMobile'])) {
  366. if (stringUtil::isMobile($post['bookMobile']) == false) {
  367. util::fail('请填写正确的订花人手机号');
  368. }
  369. }
  370. $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
  371. if (isset($post['isCashier']) && $post['isCashier'] == 1) {
  372. //收银台开单默认到店自取
  373. $post['sendType'] = dict::getDict('sendType', 'shopGet');
  374. }
  375. $productJson = $post['product'] ?? '';
  376. $productList = [];
  377. if (!empty($productJson)) {
  378. $productList = json_decode($productJson, true);
  379. }
  380. if (empty($productList) && empty($groupId)) {
  381. //商家手机上开单并生成制作单
  382. if (isset($post['unitGoodsPrice']) && !empty($post['unitGoodsPrice'])) {
  383. $unitGoodsPrice = $post['unitGoodsPrice'];
  384. if (is_numeric($unitGoodsPrice) == false) {
  385. util::fail('请输入正确的单价');
  386. }
  387. $productList = GoodsClass::orderCreateGoods($post);
  388. }
  389. }
  390. if (empty($productList) && empty($groupId)) {
  391. if (isset($post['lsGoodsPrice']) == false || $post['lsGoodsPrice'] <= 0) {
  392. $lsGoodsPrice = $post['lsGoodsPrice'];
  393. if (is_numeric($lsGoodsPrice) == false) {
  394. util::fail('请输入正确的金额');
  395. }
  396. util::fail('请填写金额或选商品');
  397. }
  398. }
  399. $connection = Yii::$app->db;
  400. $transaction = $connection->beginTransaction();
  401. try {
  402. $post['product'] = $productList;
  403. //阿东开5支老是会出现5扎情况跟踪
  404. ProductClass::adStockCheck($this->shop, $productList);
  405. //3秒内不允许重复开单
  406. $staffId = $this->shopAdminId ?? 0;
  407. $cacheKey = 'hd_create_order_' . $staffId . '_' . $customId;
  408. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  409. if (!empty($has)) {
  410. util::fail('稍等5秒再开单');
  411. }
  412. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 3, 'has']);
  413. $return = OrderService::createFinishOrder($post, $custom, $hasPay);
  414. $transaction->commit();
  415. //打印小票和语音播报
  416. $id = $return->id ?? 0;
  417. $order = OrderClass::getById($id, true);
  418. if ($order->fromType == 3 || $order->fromType == 4) {
  419. //除了客服号下单和美团下单,其它情况允许打小票
  420. } else {
  421. //前台打小票
  422. OrderClass::onlinePrint($order);
  423. }
  424. //前台提示收款多少钱
  425. ShopExtClass::hdGatheringReport($order);
  426. //前台提醒出示付款码
  427. if (isset($order->status) && $order->status == 1) {
  428. if (isset($post['isCashier']) && $post['isCashier'] == 1) {
  429. ShopExtClass::pleasePayReport($order);
  430. }
  431. }
  432. $shopId = $order->shopId ?? 0;
  433. $shop = ShopClass::getById($shopId, true);
  434. WxMessageClass::gatheringIncomeInform($shop, $order);
  435. //新制作单提示
  436. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  437. ShopExtClass::newWorkRemind($shopExt, $order);
  438. util::success($return);
  439. } catch (\Exception $e) {
  440. $transaction->rollBack();
  441. Yii::error("失败原因:" . $e->getMessage());
  442. util::fail('下单失败');
  443. }
  444. }
  445. //下单要用到的相关信息 ssh 2019.12.6
  446. public function actionOrderRelate()
  447. {
  448. $regionTree = RegionService::tree();
  449. $shop = $this->shop->attributes;
  450. $freight = MerchantExtendService::getFreight($this->sjExtend);
  451. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  452. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'txMapKey' => $mapKey, 'merchant' => $shop];
  453. util::success($out);
  454. }
  455. //余额支付 ssh 2019.12.6
  456. public function actionBalancePay()
  457. {
  458. $post = Yii::$app->request->post();
  459. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  460. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  461. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  462. $order = OrderService::getByOrderSn($orderSn);
  463. $userId = $this->adminId;
  464. $user = UserService::getUserInfo($userId);
  465. //验证支付密码是否正确
  466. UserService::validPayPassword($payPassword, $user);
  467. //支付前验证订单有效性
  468. OrderService::checkBeforePay($order);
  469. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  470. $totalFee = $order['prePrice'];
  471. $sourceType = 0;
  472. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  473. $actPrice = $discountData['price'];
  474. $callbackParams = [];
  475. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  476. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  477. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  478. }
  479. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  480. public function actionWxPay()
  481. {
  482. ini_set('date.timezone', 'Asia/Shanghai');
  483. $post = Yii::$app->request->post();
  484. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  485. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  486. $order = OrderService::getByOrderSn($orderSn);
  487. $orderId = $order['id'];
  488. //验证优惠券是否还有效
  489. if (!empty($couponId)) {
  490. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  491. }
  492. //支付前验证订单有效性
  493. OrderService::checkBeforePay($order);
  494. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  495. $totalFee = $order['realPrice'];
  496. //小程序使用miniOpenId
  497. if (httpUtil::isMiniProgram()) {
  498. $openId = $this->user['miniOpenId'];
  499. } else {
  500. $openId = $this->user['openId'];
  501. }
  502. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  503. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  504. $wxPayType = 0;
  505. if (httpUtil::isMiniProgram()) {
  506. $wxPayType = 1;
  507. }
  508. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  509. //订单30分钟后过期
  510. $now = time();
  511. $expireTime = $now + 1800;
  512. $wx = Yii::getAlias("@vendor/weixin");
  513. require_once($wx . '/lib/WxPay.Api.php');
  514. require_once($wx . '/example/WxPay.JsApiPay.php');
  515. $input = new \WxPayUnifiedOrder();
  516. $input->SetBody($name);
  517. $input->SetOut_trade_no($orderSn);
  518. $input->SetTotal_fee($totalFee * 100);
  519. $input->SetTime_start(date("YmdHis", $now));
  520. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  521. $input->SetTime_expire(date("YmdHis", $expireTime));
  522. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  523. $input->SetTrade_type("JSAPI");
  524. //花卉宝代为申请的微信支付
  525. $merchantExtend = $this->sjExtend->attributes;
  526. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  527. $input->SetSub_openid($openId);
  528. } else {
  529. $input->SetOpenid($openId);
  530. }
  531. //小程序使用miniAppId
  532. if (httpUtil::isMiniProgram()) {
  533. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  534. }
  535. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  536. $tools = new \JsApiPay();
  537. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  538. $newParams = json_decode($jsApiParameters, true);
  539. //已请求微信不能修改价格
  540. $updateData = [];
  541. $updateData['modPrice'] = 0;
  542. if (empty($order['deadline'])) {
  543. $updateData['deadline'] = $expireTime;
  544. }
  545. OrderService::updateById($orderId, $updateData);
  546. util::success($newParams);
  547. }
  548. //快捷付款订单
  549. public function actionFastPay()
  550. {
  551. ini_set('date.timezone', 'Asia/Shanghai');
  552. $post = Yii::$app->request->post();
  553. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  554. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
  555. //验证门店是否有效
  556. $shopInfo = ShopService::getById($shopId);
  557. ShopService::valid($shopInfo, $this->sjId);
  558. $post['shopId'] = $shopId;
  559. //默认门店订单
  560. $store = isset($post['store']) ? $post['store'] : 1;
  561. $post['store'] = $store;
  562. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  563. $sourceType = $this->isWx ? 0 : 1;
  564. if (httpUtil::isMiniProgram()) {
  565. $sourceType = 2;
  566. }
  567. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  568. //兼容旧系统sourceType=3表示朋友圈来源
  569. $fromType = $sourceType == 3 ? 2 : 0;
  570. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  571. $post['userId'] = $this->adminId;
  572. $custom = $this->custom;
  573. $post['bookName'] = $custom['userName'] ?? '';
  574. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  575. $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
  576. $post['bookMobile'] = $bookMobile;
  577. $prePrice = round($post['prePrice'], 2);
  578. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  579. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  580. $actPrice = $discountData['price'];
  581. $post['discountType'] = $discountData['discountType'];
  582. $post['discountAmount'] = $discountData['discountAmount'];
  583. $post['actPrice'] = $actPrice;
  584. $post['realPrice'] = $actPrice;
  585. $post['payStyle'] = 0;
  586. $post['sjId'] = $this->sjId;
  587. $now = time();
  588. $expireTime = $now + 300;//订单5分钟后过期
  589. $post['createTime'] = date("Y-m-d H:i:s", $now);
  590. $post['deadline'] = $expireTime;
  591. if ($actPrice <= 0) {
  592. util::fail('请填写正确的金额');
  593. }
  594. //微信支付订单提交不能修改价格
  595. $post['modPrice'] = $this->isWx ? 0 : 1;
  596. $post['sourceType'] = $sourceType;
  597. $post['goodsNum'] = 1;
  598. $post['fromType'] = $fromType;
  599. $order = OrderService::addOrder($post);
  600. $orderId = $order['id'];
  601. $orderSn = $order['orderSn'];
  602. $sjId = $this->sjId;
  603. if ($payWay == 0) {
  604. $orderId = $order['id'];
  605. $name = '购买商品';
  606. $totalFee = $actPrice;
  607. $user = UserService::getById($this->adminId);
  608. $openId = isset($user['openId']) ? $user['openId'] : 0;
  609. if (httpUtil::isMiniProgram()) {
  610. //小程序使用miniOpenId
  611. $openId = $user['miniOpenId'];
  612. }
  613. if (empty($openId)) {
  614. util::fail('没有找到客户的openId');
  615. }
  616. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  617. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  618. $wxPayType = 0;
  619. if (httpUtil::isMiniProgram()) {
  620. $wxPayType = 1;
  621. }
  622. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  623. $wx = Yii::getAlias("@vendor/weixin");
  624. require_once($wx . '/lib/WxPay.Api.php');
  625. require_once($wx . '/example/WxPay.JsApiPay.php');
  626. $input = new \WxPayUnifiedOrder();
  627. $input->SetBody($name);
  628. $input->SetOut_trade_no($orderSn);
  629. $input->SetTotal_fee($totalFee * 100);
  630. $input->SetTime_start(date("YmdHis", $now));
  631. $input->SetAttach($attach);
  632. //设置订单有效期5分钟
  633. $input->SetTime_expire(date("YmdHis", $expireTime));
  634. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  635. $input->SetTrade_type("JSAPI");
  636. //花卉宝代为申请的微信支付
  637. $merchantExtend = $this->sjExtend->attributes;
  638. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  639. $input->SetSub_openid($openId);
  640. } else {
  641. $input->SetOpenid($openId);
  642. }
  643. //小程序使用miniAppId
  644. if (httpUtil::isMiniProgram()) {
  645. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  646. }
  647. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  648. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  649. $tools = new \JsApiPay();
  650. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  651. $newParams = json_decode($jsApiParameters, true);
  652. $newParams['orderId'] = $orderId;
  653. util::success($newParams);
  654. } elseif ($payWay == 1) {
  655. $extend = MerchantExtendService::getBySjId($sjId);
  656. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  657. util::fail('支付宝付款即将开通...');
  658. }
  659. $config = [
  660. //应用ID,您的APPID。
  661. 'app_id' => $extend['alipayPId'],
  662. //商户私钥,您的原始格式RSA私钥
  663. 'merchant_private_key' => $extend['alipayKey'],
  664. //异步通知地址
  665. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  666. //同步跳转
  667. 'return_url' => "",
  668. //编码格式
  669. 'charset' => "UTF-8",
  670. //签名方式
  671. 'sign_type' => "RSA2",
  672. //支付宝网关
  673. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  674. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  675. 'alipay_public_key' => $extend['alipayPublicKey'],
  676. ];
  677. Yii::info(json_encode($config) . ' aplipay config');
  678. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  679. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  680. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  681. $totalFee = $order['realPrice'];
  682. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  683. $subject = '购买商品';//订单名称,必填
  684. $total_amount = $totalFee;//付款金额,必填
  685. $body = '';//商品描述,可空
  686. $timeout_express = "1m";//超时时间
  687. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  688. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  689. $passBackParams = urlencode($passBackParams);
  690. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  691. $payRequestBuilder->setBody($body);
  692. $payRequestBuilder->setSubject($subject);
  693. $payRequestBuilder->setOutTradeNo($out_trade_no);
  694. $payRequestBuilder->setTotalAmount($total_amount);
  695. $payRequestBuilder->setTimeExpress($timeout_express);
  696. //在异步通知时将该参数原样返回
  697. $payRequestBuilder->setPassbackParams($passBackParams);
  698. //同步通知
  699. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  700. //异步通知
  701. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  702. $payResponse = new \AlipayTradeService($config);
  703. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  704. //直接将支付宝的html返回给前端
  705. echo $result;
  706. } elseif ($payWay == 2) {
  707. //余额支付,验证支付密码是否正确
  708. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  709. $user = UserService::getUserInfo($this->adminId);
  710. UserService::validPayPassword($payPassword, $user);
  711. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  712. $callbackParams = [];
  713. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  714. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  715. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'orderSn' => $orderSn, 'orderId' => $orderId, 'balance' => $balance]);
  716. } else {
  717. util::fail('无效的支付方式');
  718. }
  719. }
  720. //订单评价
  721. public function actionComment()
  722. {
  723. $post = Yii::$app->request->post();
  724. $id = $post['id'];
  725. $order = OrderService::getById($id);
  726. OrderService::valid($order, $this->mainId);
  727. if ($order['grade'] > 0) {
  728. util::fail('您已经评过了');
  729. }
  730. OrderService::comment($post);
  731. util::complete('提交成功');
  732. }
  733. //订单详情 ssh 2019.12.16
  734. public function actionDetail()
  735. {
  736. $id = Yii::$app->request->get('id', 0);
  737. $detail = OrderClass::getFullInfo($id);
  738. OrderService::valid($detail, $this->mainId);
  739. util::success($detail);
  740. }
  741. public function actionList()
  742. {
  743. $get = Yii::$app->request->get();
  744. $search = isset($get['searchText']) ? $get['searchText'] : '';
  745. $searchType = isset($get['searchType']) && is_numeric($get['searchType']) ? $get['searchType'] : '';
  746. $shopId = $this->shopId ?? 0;
  747. if (empty($shopId)) {
  748. //没有登录不显示数据
  749. util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
  750. }
  751. $where = [];
  752. $where['shopId'] = $shopId;
  753. $status = $get['status'] ?? 0;
  754. if (!empty($status)) {
  755. $where['status'] = $get['status'];
  756. }
  757. $debt = $get['debt'] ?? 2;
  758. if ($debt != 2) {
  759. $where['debt'] = $debt;
  760. }
  761. if (isset($get['shopAdminId']) && !empty($get['shopAdminId'])) {
  762. $where['shopAdminId'] = $get['shopAdminId'];
  763. }
  764. if (!empty($search)) {
  765. if (is_numeric($searchType)) {
  766. if ($searchType == 0) {
  767. $where['actPrice'] = $search;
  768. } elseif ($searchType == 1) {
  769. $where['orderSn'] = $search;
  770. } elseif ($searchType == 2) {
  771. $where['bookMobile'] = $search;
  772. } else {
  773. $where['actPrice'] = $search;
  774. }
  775. } else {
  776. //兼容旧版本
  777. if (stringUtil::isMobile($search)) {
  778. $where['bookMobile'] = $search;
  779. } else {
  780. $where['orderSn'] = strtoupper($search);
  781. }
  782. }
  783. }
  784. $searchTime = $get['searchTime'] ?? '';
  785. if (!empty($searchTime)) {
  786. $startTime = $get['startTime'] ?? '';
  787. $endTime = $get['endTime'] ?? '';
  788. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  789. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  790. }
  791. $list = OrderService::getOrderList($where);
  792. $list['shop'] = $this->shop->attributes ?? [];
  793. util::success($list);
  794. }
  795. //订单归类 ssh 2019.12.17
  796. public function actionClassify()
  797. {
  798. $post = Yii::$app->request->post();
  799. $id = isset($post['id']) ? $post['id'] : 0;
  800. $order = OrderService::getById($id);
  801. OrderService::valid($order, $this->mainId);
  802. $categoryId = isset($post['categoryId']) ? $post['categoryId'] : $post['categoryId'];
  803. $usageId = isset($post['usageId']) ? $post['usageId'] : $post['usageId'];
  804. OrderService::classify($id, $categoryId, $usageId);
  805. util::complete();
  806. }
  807. //更新配送单 ssh 2019.12.17
  808. public function actionUpdateSheet()
  809. {
  810. $post = Yii::$app->request->post();
  811. $id = isset($post['id']) ? $post['id'] : 0;
  812. unset($post['id']);
  813. $order = OrderService::getById($id);
  814. OrderService::valid($order, $this->mainId);
  815. OrderService::updateSheet($order, $post);
  816. util::complete('提交成功');
  817. }
  818. //商家收款与发货 ssh 2019.12.18
  819. public function actionGathering()
  820. {
  821. $post = Yii::$app->request->post();
  822. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  823. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  824. $userId = isset($post['userId']) ? $post['userId'] : 0;
  825. $userInfo = UserService::getById($userId);
  826. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  827. util::fail('您选择的客户无效');
  828. }
  829. if ($price <= 0) {
  830. util::fail('请输入金额');
  831. }
  832. $post['prePrice'] = $price;
  833. $post['actPrice'] = $price;
  834. $post['payWay'] = $payWay;
  835. $post['sourceType'] = 1;
  836. $post['userId'] = $userId;
  837. $post['goodsNum'] = 1;
  838. $post['orderName'] = '商品';
  839. $shopId = MerchantService::getDefaultShopId($this->sj);
  840. $post['shopId'] = $shopId;
  841. $order = OrderService::addOrder($post);
  842. $id = $order['id'];
  843. $orderSn = $order['orderSn'];
  844. //流水类型列表
  845. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  846. $callbackParams = [];
  847. switch ($payWay) {
  848. case 0:
  849. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  850. break;
  851. case 1:
  852. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  853. break;
  854. case 2:
  855. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  856. break;
  857. default:
  858. util::fail('无效支付方式');
  859. }
  860. util::success($order);
  861. }
  862. //免发货管理 ssh 2020.1.6
  863. public function actionWithoutSend()
  864. {
  865. $id = Yii::$app->request->get('id');
  866. $order = OrderService::getById($id);
  867. OrderService::valid($order, $this->mainId);
  868. //配送流程变更
  869. $currentFlow = OrderSendClass::withoutSend($order);
  870. util::success(['currentFlow' => $currentFlow]);
  871. }
  872. //修改价格 ssh 2020.1.6
  873. public function actionUpdatePrice()
  874. {
  875. $id = Yii::$app->request->get('id');
  876. $price = Yii::$app->request->get('price', 1);
  877. $order = OrderService::getById($id);
  878. OrderService::valid($order, $this->mainId);
  879. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  880. util::fail('已发起支付,不能修改价格');
  881. }
  882. OrderService::updateById($id, ['actPrice' => $price]);
  883. util::complete('修改成功');
  884. }
  885. //配送单 ssh 2020.2.29
  886. public function actionGetDeliverDetail()
  887. {
  888. $id = Yii::$app->request->get('id', 0);
  889. $order = OrderService::getById($id);
  890. OrderService::valid($order, $this->mainId);
  891. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  892. $reachPeriodId = $order['reachPeriod'];
  893. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  894. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  895. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  896. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  897. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  898. $bookName = '--';
  899. $bookMobile = '--';
  900. }
  901. $data = [
  902. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  903. 'orderSn' => $order['orderSn'],
  904. 'receiveUserName' => $order['receiveUserName'],
  905. 'receiveMobile' => $order['receiveMobile'],
  906. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  907. 'cardInfo' => $order['cardInfo'],
  908. 'bookMobile' => $bookMobile,
  909. 'bookName' => $bookName,
  910. 'remark' => $order['remark'],
  911. 'sendNum' => $order['sendNum'],
  912. 'telephone' => 18030142050,
  913. 'printTime' => '',
  914. 'img' => '',
  915. ];
  916. util::success($data);
  917. }
  918. //运费计算 lqh 2021.4.12 暂反回固定
  919. public function actionFreight()
  920. {
  921. util::success(['sedCost' => 10]);
  922. }
  923. }