OrderController.php 41 KB

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