OrderController.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. } elseif ($searchType == 3) {
  773. $where['customName'] = ['like', $search];
  774. } else {
  775. $where['actPrice'] = $search;
  776. }
  777. } else {
  778. //兼容旧版本
  779. if (stringUtil::isMobile($search)) {
  780. $where['bookMobile'] = $search;
  781. } else {
  782. $where['orderSn'] = strtoupper($search);
  783. }
  784. }
  785. }
  786. $searchTime = $get['searchTime'] ?? '';
  787. if (!empty($searchTime)) {
  788. $startTime = $get['startTime'] ?? '';
  789. $endTime = $get['endTime'] ?? '';
  790. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  791. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  792. }
  793. $list = OrderService::getOrderList($where);
  794. $list['shop'] = $this->shop->attributes ?? [];
  795. util::success($list);
  796. }
  797. //订单归类 ssh 2019.12.17
  798. public function actionClassify()
  799. {
  800. $post = Yii::$app->request->post();
  801. $id = isset($post['id']) ? $post['id'] : 0;
  802. $order = OrderService::getById($id);
  803. OrderService::valid($order, $this->mainId);
  804. $categoryId = isset($post['categoryId']) ? $post['categoryId'] : $post['categoryId'];
  805. $usageId = isset($post['usageId']) ? $post['usageId'] : $post['usageId'];
  806. OrderService::classify($id, $categoryId, $usageId);
  807. util::complete();
  808. }
  809. //更新配送单 ssh 2019.12.17
  810. public function actionUpdateSheet()
  811. {
  812. $post = Yii::$app->request->post();
  813. $id = isset($post['id']) ? $post['id'] : 0;
  814. unset($post['id']);
  815. $order = OrderService::getById($id);
  816. OrderService::valid($order, $this->mainId);
  817. OrderService::updateSheet($order, $post);
  818. util::complete('提交成功');
  819. }
  820. //商家收款与发货 ssh 2019.12.18
  821. public function actionGathering()
  822. {
  823. $post = Yii::$app->request->post();
  824. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  825. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  826. $userId = isset($post['userId']) ? $post['userId'] : 0;
  827. $userInfo = UserService::getById($userId);
  828. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  829. util::fail('您选择的客户无效');
  830. }
  831. if ($price <= 0) {
  832. util::fail('请输入金额');
  833. }
  834. $post['prePrice'] = $price;
  835. $post['actPrice'] = $price;
  836. $post['payWay'] = $payWay;
  837. $post['sourceType'] = 1;
  838. $post['userId'] = $userId;
  839. $post['goodsNum'] = 1;
  840. $post['orderName'] = '商品';
  841. $shopId = MerchantService::getDefaultShopId($this->sj);
  842. $post['shopId'] = $shopId;
  843. $order = OrderService::addOrder($post);
  844. $id = $order['id'];
  845. $orderSn = $order['orderSn'];
  846. //流水类型列表
  847. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  848. $callbackParams = [];
  849. switch ($payWay) {
  850. case 0:
  851. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  852. break;
  853. case 1:
  854. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  855. break;
  856. case 2:
  857. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  858. break;
  859. default:
  860. util::fail('无效支付方式');
  861. }
  862. util::success($order);
  863. }
  864. //免发货管理 ssh 2020.1.6
  865. public function actionWithoutSend()
  866. {
  867. $id = Yii::$app->request->get('id');
  868. $order = OrderService::getById($id);
  869. OrderService::valid($order, $this->mainId);
  870. //配送流程变更
  871. $currentFlow = OrderSendClass::withoutSend($order);
  872. util::success(['currentFlow' => $currentFlow]);
  873. }
  874. //修改价格 ssh 2020.1.6
  875. public function actionUpdatePrice()
  876. {
  877. $id = Yii::$app->request->get('id');
  878. $price = Yii::$app->request->get('price', 1);
  879. $order = OrderService::getById($id);
  880. OrderService::valid($order, $this->mainId);
  881. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  882. util::fail('已发起支付,不能修改价格');
  883. }
  884. OrderService::updateById($id, ['actPrice' => $price]);
  885. util::complete('修改成功');
  886. }
  887. //配送单 ssh 2020.2.29
  888. public function actionGetDeliverDetail()
  889. {
  890. $id = Yii::$app->request->get('id', 0);
  891. $order = OrderService::getById($id);
  892. OrderService::valid($order, $this->mainId);
  893. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  894. $reachPeriodId = $order['reachPeriod'];
  895. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  896. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  897. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  898. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  899. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  900. $bookName = '--';
  901. $bookMobile = '--';
  902. }
  903. $data = [
  904. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  905. 'orderSn' => $order['orderSn'],
  906. 'receiveUserName' => $order['receiveUserName'],
  907. 'receiveMobile' => $order['receiveMobile'],
  908. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  909. 'cardInfo' => $order['cardInfo'],
  910. 'bookMobile' => $bookMobile,
  911. 'bookName' => $bookName,
  912. 'remark' => $order['remark'],
  913. 'sendNum' => $order['sendNum'],
  914. 'telephone' => 18030142050,
  915. 'printTime' => '',
  916. 'img' => '',
  917. ];
  918. util::success($data);
  919. }
  920. //运费计算 lqh 2021.4.12 暂反回固定
  921. public function actionFreight()
  922. {
  923. util::success(['sedCost' => 10]);
  924. }
  925. }