OrderController.php 41 KB

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