OrderController.php 41 KB

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