OrderController.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. <?php
  2. namespace mall\controllers;
  3. use biz\product\classes\ProductClass;
  4. use bizHd\custom\classes\HdClass;
  5. use bizHd\wx\classes\WxOpenClass;
  6. use bizMall\custom\classes\CustomClass;
  7. use bizMall\goods\classes\GoodsClass;
  8. use bizMall\order\classes\OrderClass;
  9. use bizMall\order\classes\OrderGoodsClass;
  10. use bizMall\order\services\OrderService;
  11. use bizMall\promote\services\CouponService;
  12. use bizMall\saas\services\RegionService;
  13. use bizMall\user\services\UserService;
  14. use common\components\dict;
  15. use common\components\httpUtil;
  16. use common\components\noticeUtil;
  17. use common\components\orderSn;
  18. use common\components\stringUtil;
  19. use common\services\xhPayToolService;
  20. use Yii;
  21. use common\components\util;
  22. use common\components\lakala\Lakala;
  23. class OrderController extends BaseController
  24. {
  25. //计算运费,请搜索关键词calc_freight,二个方法要合一起 ssh 20221014
  26. public function actionFreight()
  27. {
  28. $get = Yii::$app->request->get();
  29. $shop = $this->shop;
  30. $shopLat = isset($shop->lat) ? $shop->lat : '';
  31. $shopLong = isset($shop->long) ? $shop->long : '';
  32. if (empty($shopLat) || empty($shopLong)) {
  33. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  34. }
  35. $userLat = $get['lat'] ?? '';
  36. $userLong = $get['long'] ?? '';
  37. if (empty($userLat) || empty($userLong)) {
  38. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  39. }
  40. $weight = $get['weight'] ?? 0;
  41. if (empty($weight)) {
  42. util::success(['distance' => 0, 'showDistance' => 0, 'fee' => 0]);
  43. }
  44. $respond = OrderClass::getDistanceFee($userLat, $userLong, $shopLat, $shopLong, $weight);
  45. util::success($respond);
  46. }
  47. //购买花材 ssh 20220511
  48. public function actionBuyItem()
  49. {
  50. $post = Yii::$app->request->post();
  51. $post['sjId'] = $this->sjId;
  52. $post['shopId'] = $this->shopId;
  53. $post['payWay'] = $this->isWx == true ? 0 : 1;
  54. $post['mainId'] = $this->mainId ?? 0;
  55. $post['userId'] = $this->userId ?? 0;
  56. $custom = CustomClass::getByCondition(['shopId' => $this->shopId, 'userId' => $this->userId], true);
  57. $customId = $custom->id ?? 0;
  58. if (!empty($custom)) {
  59. $post['customId'] = $customId;
  60. $customName = $custom->name ?? '';
  61. $post['customName'] = $customName;
  62. $post['customNamePy'] = stringUtil::py($customName);
  63. $hdId = $custom->hdId ?? 0;
  64. $hd = HdClass::getById($hdId, true);
  65. if (!empty($hd)) {
  66. $post['hdId'] = $hd->id ?? 0;
  67. $post['hdName'] = $hd->name ?? '';
  68. }
  69. }
  70. $now = time();
  71. //订单30分钟后过期
  72. $expireTime = $now + 1800;
  73. $post['deadline'] = $expireTime;
  74. //商城
  75. $post['fromType'] = dict::getDict('fromType', 'mall');
  76. $productJson = $post['product'] ?? '';
  77. if (empty($productJson) && empty($groupId)) {
  78. util::fail('请选择商品');
  79. }
  80. $productList = json_decode($productJson, true);
  81. if (empty($productList)) {
  82. util::fail('请选择商品');
  83. }
  84. $ids = array_unique(array_filter(array_column($productList, 'productId')));
  85. $productInfoList = productClass::getByIds($ids, null, 'id');
  86. if (!empty($productInfoList)) {
  87. $presellData = [];
  88. $nowTime = strtotime(date("Y-m-d"));
  89. foreach ($productInfoList as $currentInfo) {
  90. if (isset($currentInfo['mainId']) == false || $currentInfo['mainId'] != $this->mainId) {
  91. util::fail('只能选择同一家的商品哦');
  92. }
  93. $currentName = $currentInfo['name'] ?? '';
  94. $presell = $currentInfo['presell'] ?? 0;
  95. $presellData[] = $presell;
  96. if ($presell == 1) {
  97. if (isset($post['reachDate']) == false || empty($post['reachDate'])) {
  98. util::fail('请选择配送或取货日期');
  99. }
  100. $sendTimeWant = $post['reachDate'];
  101. if (strtotime($sendTimeWant) < $nowTime) {
  102. util::fail('不能选择过去时间');
  103. }
  104. $hasDateStr = $currentInfo['presellDate'] ?? [];
  105. $hasDate = explode(',', trim($hasDateStr));
  106. if (empty($hasDate)) {
  107. util::fail('预售日期有问题,请提醒门店');
  108. }
  109. if (in_array(strtotime($sendTimeWant), $hasDate) == false) {
  110. util::fail("有预售花材在{$sendTimeWant}没到货");
  111. }
  112. $post['presell'] = 1;
  113. }
  114. }
  115. if (count($productInfoList) != count($ids)) {
  116. util::fail('存在无效商品');
  117. }
  118. $presellData = array_unique($presellData);
  119. if (count($presellData) > 1) {
  120. util::fail('预售和非预售花材不能一起下单');
  121. }
  122. } else {
  123. util::fail('花材不存在');
  124. }
  125. $connection = Yii::$app->db;
  126. $transaction = $connection->beginTransaction();
  127. try {
  128. $post['product'] = $productList;
  129. $orderValidTime = getenv('ORDER_VALID_TIME') == false ? 600 : getenv('ORDER_VALID_TIME');
  130. $post['deadline'] = time() + $orderValidTime;
  131. $post['reachDate'] = isset($post['reachDate']) && !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  132. $post['needPrint'] = dict::getDict('needPrint', 'need');
  133. $user = $this->user;
  134. $post['bookMobile'] = $user->mobile ?? '';
  135. $post['bookName'] = $user->name ?? '';
  136. $return = OrderService::createOrder($post);
  137. $transaction->commit();
  138. $orderSn = $return->orderSn ?? '';
  139. $orderPrice = $return->orderPrice ?? 0;
  140. $id = $return->id ?? 0;
  141. util::success(['orderSn' => $orderSn, 'totalPrice' => $orderPrice, 'couponId' => 0, 'id' => $id]);
  142. } catch (\Exception $e) {
  143. $transaction->rollBack();
  144. Yii::error("失败原因:" . $e->getMessage());
  145. util::fail('下单失败');
  146. }
  147. }
  148. //商城下单操作 ssh 2019.12.3
  149. public function actionCreateOrder()
  150. {
  151. $post = Yii::$app->request->post();
  152. $goodsId = isset($post['goodsId']) ? $post['goodsId'] : 0;
  153. $goodsStyleId = isset($post['goodsStyleId']) ? $post['goodsStyleId'] : 0;
  154. $goodsNum = isset($post['goodsNum']) && $post['goodsNum'] > 0 ? $post['goodsNum'] : 1;
  155. $sendType = $post['sendType'] ?? dict::getDict('sendType', 'thirdSend');
  156. if (empty($goodsId)) {
  157. util::fail('请选择商品');
  158. }
  159. $goodsInfo = GoodsClass::getGoodsInfo($goodsId);
  160. if (empty($goodsInfo)) {
  161. util::fail('没有找到商品');
  162. }
  163. $stock = $goodsInfo['stock'] && is_numeric($goodsInfo['stock']) ? $goodsInfo['stock'] : 0;
  164. $stockSet = $goodsInfo['stockSet'] && is_numeric($goodsInfo['stockSet']) ? $goodsInfo['stockSet'] : 0;
  165. if ($stock <= 0 && $stockSet == 0) {
  166. util::fail('库存不足');
  167. }
  168. //事务处理
  169. $connection = Yii::$app->db;
  170. $transaction = $connection->beginTransaction();
  171. try {
  172. $custom = CustomClass::getByCondition(['shopId' => $this->shopId, 'userId' => $this->userId], true);
  173. $customId = $custom->id ?? 0;
  174. if (!empty($custom)) {
  175. $post['customId'] = $customId;
  176. $customName = $custom->name ?? '';
  177. $post['customName'] = $customName;
  178. $post['customNamePy'] = stringUtil::py($customName);
  179. $hdId = $custom->hdId ?? 0;
  180. $hd = HdClass::getById($hdId, true);
  181. if (!empty($hd)) {
  182. $post['hdId'] = $hd->id ?? 0;
  183. $post['hdName'] = $hd->name ?? '';
  184. }
  185. }
  186. $user = isset($this->user->attributes) ? $this->user->attributes : [];
  187. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  188. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  189. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  190. $post['bookMobile'] = $bookMobile;
  191. $post['payWay'] = $this->isWx == true ? 0 : 1;
  192. //计算运费
  193. $sendDistance = 0;
  194. $sendCost = 0;
  195. $shop = $this->shop;
  196. if ($sendType == dict::getDict('sendType', 'thirdSend')) {
  197. $lat = $post['lat'] ?? '';
  198. $lng = $post['long'] ?? '';
  199. if (empty($lat) || empty($lng)) {
  200. util::fail('请填写收花地址');
  201. }
  202. $address = $post['address'] ?? '';
  203. $floor = $post['floor'] ?? '';
  204. $fullAddress = $address . $floor;
  205. $post['fullAddress'] = $fullAddress;
  206. $shopLat = $shop->lat ?? '';
  207. $shopLong = $shop->long ?? '';
  208. if (empty($shopLat) || empty($shopLong)) {
  209. util::fail('请完成门店地址');
  210. }
  211. //花束重量默认1.5
  212. $weight = 1.5;
  213. $disRespond = OrderClass::getDistanceFee($lat, $lng, $shopLat, $shopLong, $weight);
  214. $sendCost = $disRespond['fee'] ?? 0;
  215. $sendDistance = $disRespond['distance'] ?? 0;
  216. }
  217. $post['sendDistance'] = $sendDistance;
  218. $post['sendCost'] = $sendCost;
  219. $post['sjId'] = $this->sjId;
  220. $post['shopId'] = $this->shopId;
  221. $mainId = $this->mainId;
  222. $post['mainId'] = $mainId;
  223. $post['userId'] = $this->userId;
  224. //计算总金额
  225. $unitPrice = $goodsInfo['price'];
  226. $goodsStyleList = isset($goodsInfo['goodsStyleList']) ? $goodsInfo['goodsStyleList'] : [];
  227. if (!empty($goodsStyleId)) {
  228. if (empty($goodsStyleList)) {
  229. util::fail('商品款式没有找到');
  230. }
  231. $styleIdList = array_keys($goodsStyleList);
  232. if (in_array($goodsStyleId, $styleIdList) == false) {
  233. util::fail('商品款式没有找到!');
  234. }
  235. $unitPrice = isset($goodsStyleList[$goodsStyleId]['price']) ? $goodsStyleList[$goodsStyleId]['price'] : 9999;
  236. }
  237. $goodsPrice = $unitPrice * $goodsNum;
  238. $prePrice = stringUtil::calcAdd($sendCost, $goodsPrice);
  239. //非门店订单
  240. $post['store'] = 0;
  241. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  242. $sourceType = $this->isWx ? 0 : 1;
  243. if (httpUtil::isMiniProgram()) {
  244. $sourceType = 2;
  245. }
  246. $couponId = isset($post['couponId']) && !empty($post['couponId']) ? $post['couponId'] : 0;
  247. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->userId]);
  248. $actPrice = $discountData['price'];
  249. $post['discountType'] = $discountData['discountType'];
  250. $post['discountAmount'] = $discountData['discountAmount'];
  251. //非自取订单考虑配送时间
  252. $post['reachDate'] = isset($post['reachDate']) && !empty($post['reachDate']) ? $post['reachDate'] : date("Y-m-d");
  253. $sendType = $post['sendType'] ?? 0;
  254. if ($sendType != 1) {
  255. if (isset($post['reachPeriod']) == false || empty($post['reachPeriod'])) {
  256. util::fail('请选择配送时间');
  257. }
  258. $post['reachTime'] = strtotime($post['reachDate'] . ' ' . $post['reachPeriod']);
  259. }
  260. $now = time();
  261. $expireTime = $now + 1800;//订单30分钟后过期
  262. $post['deadline'] = $expireTime;
  263. $orderSn = orderSn::getOrderSn();
  264. $post['orderSn'] = $orderSn;
  265. $post['fromType'] = dict::getDict('fromType', 'mall');
  266. $post['prePrice'] = $prePrice;
  267. $post['orderPrice'] = $actPrice;
  268. $post['actPrice'] = $actPrice;
  269. $post['realPrice'] = $actPrice;
  270. $post['mainPay'] = $actPrice;
  271. $post['cash'] = 0;
  272. $post['mainId'] = $mainId;
  273. $post['needPrint'] = dict::getDict('needPrint', 'need');
  274. $order = OrderClass::addOrder($post);
  275. $orderId = $order['id'];
  276. $orderSn = $order['orderSn'];
  277. $currentCover = isset($goodsInfo['shortImgList']) && !empty($goodsInfo['shortImgList']) ? current($goodsInfo['shortImgList']) : '';
  278. $flower = $goodsInfo['flower'] ?? 0;
  279. $price = bcmul($goodsNum, $unitPrice, 2);
  280. $data = [
  281. 'orderId' => $orderId,
  282. 'goodsId' => $goodsId,
  283. 'flower' => $flower,
  284. 'userId' => $this->userId,
  285. 'sjId' => $this->sjId,
  286. 'mainId' => $mainId,
  287. 'name' => $goodsInfo['name'] ?? '',
  288. 'cover' => $currentCover,
  289. 'unitPrice' => $unitPrice,
  290. 'num' => $goodsNum,
  291. 'orderSn' => $orderSn,
  292. 'price' => $price,
  293. 'createTime' => date("Y-m-d H:i:s"),
  294. ];
  295. OrderGoodsClass::addData($data);
  296. $transaction->commit();
  297. util::success(['orderSn' => $orderSn, 'totalPrice' => $actPrice, 'couponId' => $couponId, 'id' => $orderId]);
  298. } catch (Exception $e) {
  299. $transaction->rollBack();
  300. Yii::info("失败原因:" . $e->getMessage());
  301. util::fail('下单失败');
  302. }
  303. }
  304. //下单要用到的相关信息 ssh 2019.12.6
  305. public function actionOrderRelate()
  306. {
  307. $regionTree = RegionService::tree();
  308. //门店名称
  309. $shop = isset($this->shop) && !empty($this->shop) ? $this->shop->attributes : [];
  310. $sjName = $shop['merchantName'] ?? '';
  311. $shopName = $shop['shopName'] ?? '';
  312. $default = $shop['default'] ?? 0;
  313. $shop['showName'] = $default == 1 && $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
  314. $freight = ['first' => 5, 'add' => 2];
  315. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  316. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'txMapKey' => $mapKey, 'merchant' => $shop];
  317. util::success($out);
  318. }
  319. //余额支付 ssh 2019.12.6
  320. public function actionBalancePay()
  321. {
  322. $post = Yii::$app->request->post();
  323. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  324. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  325. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  326. //验证优惠券是否还有效
  327. if (!empty($couponId)) {
  328. //CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  329. }
  330. $order = OrderService::getByOrderSn($orderSn);
  331. $userId = $this->userId;
  332. $user = UserService::getUserInfo($userId);
  333. //验证支付密码是否正确
  334. UserService::validPayPassword($payPassword, $user);
  335. //支付前验证订单有效性
  336. OrderService::checkBeforePay($order);
  337. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  338. $totalFee = $order['prePrice'];
  339. $sourceType = 0;
  340. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->userId]);
  341. $actPrice = $discountData['price'];
  342. $callbackParams = [];
  343. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  344. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  345. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  346. }
  347. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  348. public function actionWxPay()
  349. {
  350. ini_set('date.timezone', 'Asia/Shanghai');
  351. $post = Yii::$app->request->post();
  352. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  353. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  354. $order = OrderService::getByOrderSn($orderSn);
  355. $orderId = $order['id'];
  356. //验证优惠券是否还有效
  357. if (!empty($couponId)) {
  358. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  359. }
  360. //支付前验证订单有效性
  361. OrderService::checkBeforePay($order);
  362. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买花材';
  363. $shop = $this->shop;
  364. if (isset($shop->shopName) && !empty($shop->shopName)) {
  365. $name .= '(' . $shop->shopName . ')';
  366. }
  367. $totalFee = $order['mainPay'];
  368. //小程序使用miniOpenId
  369. $openId = $this->user['miniOpenId'] ?? '';
  370. if (empty($openId)) {
  371. $openId = $post['miniOpenId'] ?? '';
  372. }
  373. if (empty($openId)) {
  374. util::fail('没有openId');
  375. }
  376. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  377. $now = time();
  378. $expireTime = $now + 1800;
  379. $sjExtend = WxOpenClass::getMallWxInfo();
  380. $shop = $this->shop;
  381. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  382. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  383. $params = [
  384. 'appid' => 'OP00002119',
  385. 'serial_no' => '018b08cfddbd',
  386. 'merchant_no' => $shop->lklSjNo,
  387. 'term_no' => $shop->lklScanTermNo,
  388. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  389. 'lklCertificatePath' => $lklCertificatePath,
  390. ];
  391. $laResource = new Lakala($params);
  392. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/pay-callback";
  393. $wxParams = [
  394. 'orderSn' => $orderSn,
  395. 'amount' => $totalFee,
  396. 'capitalType' => $capitalType,
  397. 'notifyUrl' => $notifyUrl,
  398. 'wxAppId' => $sjExtend['miniAppId'],
  399. 'openId' => $openId,
  400. 'subject' => $name,
  401. 'couponId' => $couponId,
  402. ];
  403. noticeUtil::push($sjExtend['miniAppId'] . ' ' . $shop->lklSjNo . ' ' . $shop->lklScanTermNo, '15280215347');
  404. $response = $laResource->driveWxPay($wxParams);
  405. if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
  406. $errMsg = $response['msg'] ?? '';
  407. noticeUtil::push($errMsg, '15280215347');
  408. util::fail('支付失败');
  409. }
  410. //已请求微信不能修改价格
  411. $updateData = [];
  412. $updateData['modPrice'] = 0;
  413. if (empty($order['deadline'])) {
  414. $updateData['deadline'] = $expireTime;
  415. }
  416. OrderService::updateById($orderId, $updateData);
  417. $newParams = isset($response['resp_data']['acc_resp_fields']) ? $response['resp_data']['acc_resp_fields'] : [];
  418. $appId = $newParams['app_id'] ?? '';
  419. $nonceStr = $newParams['nonce_str'] ?? '';
  420. $paySign = $newParams['pay_sign'] ?? '';
  421. $package = $newParams['package'] ?? '';
  422. $signType = $newParams['sign_type'] ?? '';
  423. $timeStamp = $newParams['time_stamp'] ?? '';
  424. $new = [
  425. 'id' => $orderId,
  426. 'appId' => $appId,
  427. 'nonceStr' => $nonceStr,
  428. 'paySign' => $paySign,
  429. 'package' => $package,
  430. 'signType' => $signType,
  431. 'timeStamp' => $timeStamp,
  432. 'orderSn' => $orderSn,
  433. ];
  434. util::success($new);
  435. }
  436. //快捷付款订单
  437. public function actionFastPay()
  438. {
  439. ini_set('date.timezone', 'Asia/Shanghai');
  440. $post = Yii::$app->request->post();
  441. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  442. $shopId = $this->shopId;
  443. $post['shopId'] = $shopId;
  444. $post['mainId'] = $this->mainId;
  445. $post['sjId'] = $this->sjId;
  446. $post['store'] = 0;
  447. $post['customId'] = $this->customId;
  448. $user = isset($this->user->attributes) ? $this->user->attributes : [];
  449. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  450. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  451. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  452. $post['bookMobile'] = $bookMobile;
  453. $prePrice = round($post['prePrice'], 2);
  454. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  455. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => 0, 'couponId' => $couponId, 'userId' => $this->userId]);
  456. $actPrice = $discountData['price'];
  457. $post['discountType'] = $discountData['discountType'];
  458. $post['discountAmount'] = $discountData['discountAmount'];
  459. $post['orderPrice'] = $actPrice;
  460. $post['actPrice'] = $actPrice;
  461. $post['realPrice'] = $actPrice;
  462. $post['mainPay'] = $actPrice;
  463. $post['payStyle'] = 0;
  464. $post['sjId'] = $this->sjId;
  465. $post['needPrint'] = dict::getDict('needPrint', 'noNeed');
  466. $now = time();
  467. $expireTime = $now + 300;//订单5分钟后过期
  468. $post['createTime'] = date("Y-m-d H:i:s", $now);
  469. $post['deadline'] = $expireTime;
  470. if ($actPrice <= 0) {
  471. util::fail('请填写正确的金额');
  472. }
  473. //微信支付订单提交不能修改价格
  474. $post['modPrice'] = $this->isWx ? 0 : 1;
  475. $post['goodsNum'] = 1;
  476. $post['fromType'] = $post['fromType'] ?? 1;
  477. $post['reachDate'] = isset($post['reachDate']) && !empty($post['reachDate']) ? $post['reachDate'] : '00-00-00';
  478. $post['onlinePay'] = dict::getDict('onlinePay', 'yes');
  479. //前端未修改时这边做兼容
  480. if (isset($post['receiveAddress']) && !empty($post['receiveAddress'])) {
  481. $post['address'] = $post['receiveAddress'];
  482. if (isset($post['receiveProvince']) && !empty($post['receiveProvince'])) {
  483. $post['province'] = $post['receiveProvince'];
  484. }
  485. if (isset($post['receiveCity']) && !empty($post['receiveCity'])) {
  486. $post['city'] = $post['receiveCity'];
  487. }
  488. if (isset($post['receiveFloor']) && !empty($post['receiveFloor'])) {
  489. $post['floor'] = $post['receiveFloor'];
  490. }
  491. if (isset($post['latitude']) && !empty($post['latitude'])) {
  492. $post['lat'] = $post['latitude'];
  493. }
  494. if (isset($post['longitude']) && !empty($post['longitude'])) {
  495. $post['long'] = $post['longitude'];
  496. }
  497. $city = $post['receiveCity'] ?? '';
  498. $address = $post['receiveAddress'] ?? '';
  499. $floor = $post['receiveFloor'] ?? '';
  500. $post['fullAddress'] = $city . $address . $floor;
  501. }
  502. $order = OrderClass::addOrder($post);
  503. $orderId = $order['id'];
  504. $orderSn = $order['orderSn'];
  505. $sjId = $this->sjId;
  506. if ($payWay == 0) {
  507. $orderId = $order['id'];
  508. $name = '购买商品';
  509. $totalFee = $actPrice;
  510. $user = UserService::getById($this->userId);
  511. //小程序使用miniOpenId
  512. $openId = $user['miniOpenId'];
  513. if (empty($openId)) {
  514. $openId = isset($post['miniOpenId']) && !empty($post['miniOpenId']) ? $post['miniOpenId'] : '';
  515. }
  516. if (empty($openId)) {
  517. util::fail('没有微信信息');
  518. }
  519. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  520. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  521. $wxPayType = 0;
  522. if (httpUtil::isMiniProgram()) {
  523. $wxPayType = 1;
  524. }
  525. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  526. $wx = Yii::getAlias("@vendor/weixin");
  527. require_once($wx . '/lib/WxPay.Api.php');
  528. require_once($wx . '/example/WxPay.JsApiPay.php');
  529. $input = new \WxPayUnifiedOrder();
  530. $input->SetBody($name);
  531. $input->SetOut_trade_no($orderSn);
  532. $input->SetTotal_fee($totalFee * 100);
  533. $input->SetTime_start(date("YmdHis", $now));
  534. $input->SetAttach($attach);
  535. //设置订单有效期5分钟
  536. $input->SetTime_expire(date("YmdHis", $expireTime));
  537. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  538. $input->SetTrade_type("JSAPI");
  539. $sjExtend = WxOpenClass::getMallWxInfo();
  540. $input->SetOpenid($openId);
  541. //小程序使用miniAppId
  542. $sjExtend['wxAppId'] = $sjExtend['miniAppId'];
  543. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $sjExtend);
  544. $tools = new \JsApiPay();
  545. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $sjExtend);
  546. $newParams = json_decode($jsApiParameters, true);
  547. $newParams['orderId'] = $orderId;
  548. $newParams['orderSn'] = $orderSn;
  549. $newParams['totalPrice'] = $actPrice;
  550. util::success($newParams);
  551. } elseif ($payWay == 1) {
  552. $aliPId = '2021003122664465';
  553. $aliKey = 'MIIEpAIBAAKCAQEAnefrChYa5FUbGTlZNMTDNG531WrVP+TBPw3/hSmycRlBE/1sg9EryM0S3a9OQKQenRdYOoalqkkBuzt41ygJUC5hfNeaiV2OzphIiAyxUaiL1mSftP5B8joBN3HGG2AKbcvKlWcFoeiGY4ZmV/K0t3fqj/uPP6N/pEtnx6X4Ifgz4WGCDKUXKqT1Pyk2rqyIpel2EYk+HtC+9iicfac9kKQQiksDopb7sYosttdk64Dmjp2nMLDSpR+KOZUaqB39MEeHcJGeTzdVrp+Z9wW/NcJzSkSUb9juA0YjmogdbiKltykVHTbP6J0uPyByvzfyyY22QPqwNPiIPbCN6H543QIDAQABAoIBAQCO0+rOecYjSDO1siDVUTC8KTutR+/R1klRjojUWy3zjQNHYJAZ/0ZaX9wzttDSOWETeL0uWwJYL6coQxf/jVA3PWyirqYyn/R/PFFG9iwhj5HE/8lRvjXKMttM2lV2B34HaDE6yC/ZDmkYdsX1wSvjU81QJRuiVXIsGqSpep8hoVvVAn5sjvoC+zBSUaCsYy+7v7IXc6L8f/oLCBXY1r5j/+F/XFU1uFv4j162eRShQs6jQyVqQGLGCy4sSujj+8mpd6uCyJSIGJQHJlaN6cibTYStU/Z9+I/AP/+wQPVx31OwEC5J2xBfSHsezMsHSF7HQnfpQSz5AsOYZ3MOkiglAoGBAPV8sZz3C1gQ6WX5eKZE7PEUSxvAHsP+X6AAA6sWfH4cZq1uGJXgiDpTqN5dOqfNpNAU8gBDNTx4xUZ+cDuDH4WYxqkCe3CDdL97QmXDl2PnNvCKgHl735g3U1v3kCXgUAfBomc/xEIDguiEtsjPpknfjte/HmDE0zrWMOAQkJqXAoGBAKSrD5ry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aKozp+XMwIDAQAB';
  555. if (getenv('YII_ENV') == 'production') {
  556. if ($shopId == 1) {
  557. //线上国兰使用老的支付宝账号
  558. $aliPId = '2017041906821571';
  559. $aliKey = 'MIIEpAIBAAKCAQEAvbeu6o90L+0AilI+mbhuJJH0lUv7hWQCEC+XUc+cWlC9ulKC3cSVScVLJHpUc09aj6v/iD1p9iVfgMxjeADNVKiQC2RJyRshAjzyTq+2bTcODp619iV2y4qW8UM65VcP7Ide3P0uT5xC2ReW0HpkdHZgm4F+P7mh1VhGt9qOP3hjvoraAHhtGACvsGvy8H69HhSAG+CEmFt7f2tKNWJ8xEUvkfhDvys93PfTk4xMWj048hJE2r38+2mWI/Il5dFQHWXXTVl2x9yi7uhEEW42a+7s9Q3HgqEvZiQ2NI1FTeEAPLFBApiEsNLY/smaszwqqfWGAyTMvtQ6T4K96GcTLQIDAQABAoIBAHwYTj33n9RJfnT73x7F2KXrIsUVcmyKQh88QgqtdmRNNA1QM3HESLJ8bu5pZhwW5/HaW8dOBKWRRKsHBnlUbPrXV4FcFDeLm0fPfd+iZ/2AaZ1+ix962f3BpYIiq7+f9zaMRazfnw9L8x31pByyMktLs12EkoQ0dHsMxxUzzKAOiiPnvCn8Pv+Jb2qej8GXgCjefutCVNMWGsdwJtMVXEbpdmMa48Wvw+0In5ZS/UG39YAreFzgDqI9jWHE1ZhkGmB1+8hKpeIlEeVGAeYVveUgssMORdA/YY8SWHk26KSIFXBrmdKjAcRJ8Q7ZHUmzIqAV+IMV+RD4J5mZHeJgdAECgYEA8J+Hp1M6eYbT4CPLXa//yRP6Xo+qSzrKHaRB1LRAjYhvKpx/TQetYpNCJ5bWpa+Jp0T5R21pzuYaJkPuGlNEHA13b5T3r1l2ltomSEdaShvD5EZ9WtErYV5zpSv7FjjIGkbwa0H3A8Ydnvw5z4A9TZjjHLjC2GtVGJReqHGglMECgYEAydddA4NRPxmXvIjjmLb1Ft1qwHuyv3vvWhi50foGZXNEnBcfP/OkfyBDDpOEu34GZBMX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应用ID,您的APPID。
  565. 'app_id' => $aliPId,
  566. //商户私钥,您的原始格式RSA私钥
  567. 'merchant_private_key' => $aliKey,
  568. //异步通知地址
  569. 'notify_url' => Yii::$app->params['mallHost'] . "/notice/ali-callback",
  570. //同步跳转
  571. 'return_url' => "",
  572. //编码格式
  573. 'charset' => "UTF-8",
  574. //签名方式
  575. 'sign_type' => "RSA2",
  576. //支付宝网关
  577. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  578. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  579. 'alipay_public_key' => $aliPublicKey,
  580. ];
  581. Yii::info(json_encode($config) . ' aplipay config');
  582. $aliWap = Yii::getAlias("@vendor/alipayWap");
  583. require_once($aliWap . '/wappay/service/AlipayTradeService.php');
  584. require_once($aliWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  585. $totalFee = $order['realPrice'];
  586. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  587. $subject = '购买商品';//订单名称,必填
  588. $total_amount = $totalFee;//付款金额,必填
  589. $body = '';//商品描述,可空
  590. $timeout_express = "1m";//超时时间
  591. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  592. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  593. $passBackParams = urlencode($passBackParams);
  594. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  595. $payRequestBuilder->setBody($body);
  596. $payRequestBuilder->setSubject($subject);
  597. $payRequestBuilder->setOutTradeNo($out_trade_no);
  598. $payRequestBuilder->setTotalAmount($total_amount);
  599. $payRequestBuilder->setTimeExpress($timeout_express);
  600. //在异步通知时将该参数原样返回
  601. $payRequestBuilder->setPassbackParams($passBackParams);
  602. //同步通知
  603. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  604. //异步通知
  605. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  606. $payResponse = new \AlipayTradeService($config);
  607. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  608. //直接将支付宝的html返回给前端
  609. echo $result;
  610. } elseif ($payWay == 2) {
  611. //余额支付,验证支付密码是否正确
  612. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  613. $user = UserService::getUserInfo($this->userId);
  614. UserService::validPayPassword($payPassword, $user);
  615. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  616. $callbackParams = [];
  617. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  618. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  619. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'orderSn' => $orderSn, 'orderId' => $orderId, 'balance' => $balance]);
  620. } else {
  621. util::fail('无效的支付方式');
  622. }
  623. }
  624. //订单列表 ssh 2019.12.12
  625. public function actionList()
  626. {
  627. $userId = $this->userId;
  628. if (empty($userId)) {
  629. util::success(['list' => [], 'moreData' => 0, 'totalNum' => 0, 'totalPage' => 0]);
  630. }
  631. $where = ['userId' => $userId];
  632. $list = OrderService::getOrderList($where);
  633. util::success($list);
  634. }
  635. //订单评价
  636. public function actionComment()
  637. {
  638. $post = Yii::$app->request->post();
  639. $id = $post['id'];
  640. $order = OrderClass::getById($id);
  641. if ($order['grade'] > 0) {
  642. util::fail('您已经评过了');
  643. }
  644. OrderService::comment($post);
  645. util::complete('提交成功');
  646. }
  647. //订单详情 ssh 2019.12.16
  648. public function actionDetail()
  649. {
  650. $id = Yii::$app->request->get('id', 0);
  651. $detail = OrderClass::getOrderById($id);
  652. util::success($detail);
  653. }
  654. //获取详情 ssh 20220512
  655. public function actionInfo()
  656. {
  657. $sn = Yii::$app->request->get('orderSn', '');
  658. $detail = OrderClass::getOrderBySn($sn);
  659. util::success($detail);
  660. }
  661. }