OrderController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. <?php
  2. namespace mall\controllers;
  3. use bizHd\wx\classes\WxOpenClass;
  4. use bizMall\goods\services\GoodsService;
  5. use bizMall\merchant\services\ExpressService;
  6. use bizMall\merchant\services\MerchantExtendService;
  7. use bizMall\merchant\services\MerchantService;
  8. use bizMall\order\classes\OrderClass;
  9. use bizMall\order\services\OrderGoodsService;
  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\stringUtil;
  17. use common\services\xhPayToolService;
  18. use Yii;
  19. use common\components\util;
  20. class OrderController extends BaseController
  21. {
  22. //商城下单操作 ssh 2019.12.3
  23. public function actionCreateOrder()
  24. {
  25. $post = Yii::$app->request->post();
  26. $goodsId = isset($post['goodsId']) ? $post['goodsId'] : 0;
  27. $goodsStyleId = isset($post['goodsStyleId']) ? $post['goodsStyleId'] : 0;
  28. $goodsNum = isset($post['goodsNum']) && $post['goodsNum'] > 0 ? $post['goodsNum'] : 1;
  29. $needSend = isset($post['needSend']) && is_numeric($post['needSend']) ? $post['needSend'] : 1;
  30. if (empty($goodsId)) {
  31. util::fail('请选择商品');
  32. }
  33. $goodsInfo = GoodsService::getGoodsInfo($goodsId);
  34. if (empty($goodsInfo)) {
  35. util::fail('没有找到商品');
  36. }
  37. if (isset($goodsInfo['stock']) == false || $goodsInfo['stock'] == 0) {
  38. util::fail('已经卖完了');
  39. }
  40. //运费计算方式
  41. $freightType = isset($goodsInfo['freightType']) ? $goodsInfo['freightType'] : 0;
  42. //事务处理
  43. $connection = Yii::$app->db;
  44. $transaction = $connection->beginTransaction();
  45. try {
  46. $post['customId'] = $this->customId;
  47. $post['customName'] = $this->custom['name'] ?? '';
  48. $user = isset($this->user->attributes) ? $this->user->attributes : [];
  49. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  50. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  51. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  52. $post['bookMobile'] = $bookMobile;
  53. $post['payWay'] = $this->isWx == true ? 0 : 1;
  54. //计算运费
  55. $post['sendDistance'] = isset($post['sendDistance']) ? $post['sendDistance'] : 0;
  56. $sendCost = 0;
  57. //按距离计算运费并且客户要求送的
  58. if ($freightType == 0 && $needSend == 1) {
  59. $lat = $post['latitude'];//收货人纬度
  60. $lng = $post['longitude'];//收货人经度
  61. $respond = ExpressService::getUserDistance($lng, $lat, $this->shopId, $this->sjExtend);
  62. $sendCost = isset($respond['fee']) ? $respond['fee'] : 0;
  63. }
  64. $post['sendCost'] = $sendCost;
  65. $post['sjId'] = $this->sjId;
  66. $post['shopId'] = $this->shopId;
  67. //计算总金额
  68. $unitPrice = $goodsInfo['price'];
  69. $goodsStyleList = isset($goodsInfo['goodsStyleList']) ? $goodsInfo['goodsStyleList'] : [];
  70. if (!empty($goodsStyleId)) {
  71. if (empty($goodsStyleList)) {
  72. util::fail('商品款式没有找到');
  73. }
  74. $styleIdList = array_keys($goodsStyleList);
  75. if (in_array($goodsStyleId, $styleIdList) == false) {
  76. util::fail('商品款式没有找到!');
  77. }
  78. $unitPrice = isset($goodsStyleList[$goodsStyleId]['price']) ? $goodsStyleList[$goodsStyleId]['price'] : 9999;
  79. }
  80. $goodsPrice = $unitPrice * $goodsNum;
  81. $prePrice = stringUtil::calcAdd($sendCost, $goodsPrice);
  82. //非门店订单
  83. $post['store'] = 0;
  84. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  85. $sourceType = $this->isWx ? 0 : 1;
  86. if (httpUtil::isMiniProgram()) {
  87. $sourceType = 2;
  88. }
  89. $couponId = isset($post['couponId']) && !empty($post['couponId']) ? $post['couponId'] : 0;
  90. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->userId]);
  91. $actPrice = $discountData['price'];
  92. $post['discountType'] = $discountData['discountType'];
  93. $post['discountAmount'] = $discountData['discountAmount'];
  94. $now = time();
  95. $expireTime = $now + 1800;//订单30分钟后过期
  96. $post['deadline'] = $expireTime;
  97. $post['fromType'] = dict::getDict('fromType', 'mall');
  98. $post['prePrice'] = $prePrice;
  99. $post['actPrice'] = $actPrice;
  100. $order = OrderClass::addOrder($post);
  101. $orderId = $order['id'];
  102. $orderSn = $order['orderSn'];
  103. $data = [
  104. 'orderId' => $orderId,
  105. 'goodsId' => $goodsId,
  106. 'userId' => $this->userId,
  107. 'sjId' => $this->sjId,
  108. 'title' => $goodsInfo['goodsName'],
  109. 'cover' => isset($goodsInfo['shortImgList']) && !empty($goodsInfo['shortImgList']) ? current($goodsInfo['shortImgList']) : '',
  110. 'unitPrice' => $unitPrice,
  111. 'num' => $goodsNum,
  112. 'goodsStyleName' => isset($goodsInfo['goodsStyleList'][$goodsStyleId]['title']) ? $goodsInfo['goodsStyleList'][$goodsStyleId]['title'] : '',
  113. 'goodsStyleId' => $goodsStyleId,
  114. 'createTime' => date("Y-m-d H:i:s"),
  115. ];
  116. OrderGoodsService::add($data);//创建订单商品列表
  117. $transaction->commit();
  118. util::success(['orderSn' => $orderSn, 'totalPrice' => $actPrice, 'couponId' => $couponId]);
  119. } catch (Exception $e) {
  120. $transaction->rollBack();
  121. Yii::info("下单失败原因:" . $e->getMessage());
  122. util::fail('下单失败');
  123. }
  124. }
  125. //下单要用到的相关信息 ssh 2019.12.6
  126. public function actionOrderRelate()
  127. {
  128. $regionTree = RegionService::tree();
  129. $shop = $this->shop->attributes;
  130. $freight = ['first' => 5, 'add' => 2];
  131. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  132. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'txMapKey' => $mapKey, 'merchant' => $shop];
  133. Yii::info(json_encode($shop));
  134. Yii::info($shop['shopName']);
  135. util::success($out);
  136. }
  137. //余额支付 ssh 2019.12.6
  138. public function actionBalancePay()
  139. {
  140. $post = Yii::$app->request->post();
  141. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  142. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  143. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  144. //验证优惠券是否还有效
  145. if (!empty($couponId)) {
  146. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  147. }
  148. $order = OrderService::getByOrderSn($orderSn);
  149. $userId = $this->userId;
  150. $user = UserService::getUserInfo($userId);
  151. //验证支付密码是否正确
  152. UserService::validPayPassword($payPassword, $user);
  153. //支付前验证订单有效性
  154. OrderService::checkBeforePay($order, $this->userId);
  155. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  156. $totalFee = $order['prePrice'];
  157. $sourceType = 0;
  158. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->userId]);
  159. $actPrice = $discountData['price'];
  160. $callbackParams = [];
  161. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  162. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  163. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  164. }
  165. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  166. public function actionWxPay()
  167. {
  168. ini_set('date.timezone', 'Asia/Shanghai');
  169. $post = Yii::$app->request->post();
  170. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  171. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  172. $order = OrderService::getByOrderSn($orderSn);
  173. $orderId = $order['id'];
  174. //验证优惠券是否还有效
  175. if (!empty($couponId)) {
  176. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  177. }
  178. //支付前验证订单有效性
  179. OrderService::checkBeforePay($order, $this->userId);
  180. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  181. $totalFee = $order['actPrice'];
  182. //小程序使用miniOpenId
  183. $openId = $this->user['miniOpenId'];
  184. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  185. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  186. $wxPayType = 0;
  187. if (httpUtil::isMiniProgram()) {
  188. $wxPayType = 1;
  189. }
  190. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  191. //订单30分钟后过期
  192. $now = time();
  193. $expireTime = $now + 1800;
  194. $wx = Yii::getAlias("@vendor/weixin");
  195. require_once($wx . '/lib/WxPay.Api.php');
  196. require_once($wx . '/example/WxPay.JsApiPay.php');
  197. $input = new \WxPayUnifiedOrder();
  198. $input->SetBody($name);
  199. $input->SetOut_trade_no($orderSn);
  200. $input->SetTotal_fee($totalFee * 100);
  201. $input->SetTime_start(date("YmdHis", $now));
  202. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  203. $input->SetTime_expire(date("YmdHis", $expireTime));
  204. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  205. $input->SetTrade_type("JSAPI");
  206. $sjExtend = WxOpenClass::getMallWxInfo();
  207. $input->SetOpenid($openId);
  208. //小程序使用miniAppId
  209. $sjExtend['wxAppId'] = $sjExtend['miniAppId'];
  210. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $sjExtend);
  211. $tools = new \JsApiPay();
  212. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $sjExtend);
  213. $newParams = json_decode($jsApiParameters, true);
  214. //已请求微信不能修改价格
  215. $updateData = [];
  216. $updateData['modPrice'] = 0;
  217. if (empty($order['deadline'])) {
  218. $updateData['deadline'] = $expireTime;
  219. }
  220. OrderService::updateById($orderId, $updateData);
  221. util::success($newParams);
  222. }
  223. //快捷付款订单
  224. public function actionFastPay()
  225. {
  226. ini_set('date.timezone', 'Asia/Shanghai');
  227. $post = Yii::$app->request->post();
  228. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  229. $shopId = $this->shopId;
  230. $post['shopId'] = $shopId;
  231. $post['sjId'] = $this->sjId;
  232. $post['store'] = 0;
  233. $fromType = dict::getDict('fromType', 'shop');
  234. $post['customId'] = $this->customId;
  235. $user = isset($this->user->attributes) ? $this->user->attributes : [];
  236. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  237. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  238. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  239. $post['bookMobile'] = $bookMobile;
  240. $prePrice = round($post['prePrice'], 2);
  241. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  242. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => 0, 'couponId' => $couponId, 'userId' => $this->userId]);
  243. $actPrice = $discountData['price'];
  244. $post['discountType'] = $discountData['discountType'];
  245. $post['discountAmount'] = $discountData['discountAmount'];
  246. $post['actPrice'] = $actPrice;
  247. $post['payStyle'] = 0;
  248. $post['sjId'] = $this->sjId;
  249. $now = time();
  250. $expireTime = $now + 300;//订单5分钟后过期
  251. $post['createTime'] = date("Y-m-d H:i:s", $now);
  252. $post['deadline'] = $expireTime;
  253. if ($actPrice <= 0) {
  254. util::fail('请填写正确的金额');
  255. }
  256. //微信支付订单提交不能修改价格
  257. $post['modPrice'] = $this->isWx ? 0 : 1;
  258. $post['goodsNum'] = 1;
  259. $post['fromType'] = $fromType;
  260. $post['reachDate'] = isset($post['reachDate']) && !empty($post['reachDate']) ? $post['reachDate'] : '00-00-00';
  261. $order = OrderClass::addOrder($post);
  262. $orderId = $order['id'];
  263. $orderSn = $order['orderSn'];
  264. $sjId = $this->sjId;
  265. if ($payWay == 0) {
  266. $orderId = $order['id'];
  267. $name = '购买商品';
  268. $totalFee = $actPrice;
  269. $user = UserService::getById($this->userId);
  270. //小程序使用miniOpenId
  271. $openId = $user['miniOpenId'];
  272. if (empty($openId)) {
  273. util::fail('没有找您的微信ID');
  274. }
  275. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  276. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  277. $wxPayType = 0;
  278. if (httpUtil::isMiniProgram()) {
  279. $wxPayType = 1;
  280. }
  281. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  282. $wx = Yii::getAlias("@vendor/weixin");
  283. require_once($wx . '/lib/WxPay.Api.php');
  284. require_once($wx . '/example/WxPay.JsApiPay.php');
  285. $input = new \WxPayUnifiedOrder();
  286. $input->SetBody($name);
  287. $input->SetOut_trade_no($orderSn);
  288. $input->SetTotal_fee($totalFee * 100);
  289. $input->SetTime_start(date("YmdHis", $now));
  290. $input->SetAttach($attach);
  291. //设置订单有效期5分钟
  292. $input->SetTime_expire(date("YmdHis", $expireTime));
  293. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  294. $input->SetTrade_type("JSAPI");
  295. $sjExtend = WxOpenClass::getMallWxInfo();
  296. $input->SetOpenid($openId);
  297. //小程序使用miniAppId
  298. $sjExtend['wxAppId'] = $sjExtend['miniAppId'];
  299. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $sjExtend);
  300. $tools = new \JsApiPay();
  301. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $sjExtend);
  302. $newParams = json_decode($jsApiParameters, true);
  303. $newParams['orderId'] = $orderId;
  304. $newParams['orderSn'] = $orderSn;
  305. $newParams['totalPrice'] = $actPrice;
  306. util::success($newParams);
  307. } elseif ($payWay == 1) {
  308. $extend = MerchantExtendService::getBySjId($sjId);
  309. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  310. util::fail('支付宝付款即将开通...');
  311. }
  312. $config = [
  313. //应用ID,您的APPID。
  314. 'app_id' => $extend['alipayPId'],
  315. //商户私钥,您的原始格式RSA私钥
  316. 'merchant_private_key' => $extend['alipayKey'],
  317. //异步通知地址
  318. 'notify_url' => Yii::$app->params['mallHost'] . "/notice/ali-callback",
  319. //同步跳转
  320. 'return_url' => "",
  321. //编码格式
  322. 'charset' => "UTF-8",
  323. //签名方式
  324. 'sign_type' => "RSA2",
  325. //支付宝网关
  326. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  327. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  328. 'alipay_public_key' => $extend['alipayPublicKey'],
  329. ];
  330. Yii::info(json_encode($config) . ' aplipay config');
  331. $aliWap = Yii::getAlias("@vendor/alipayWap");
  332. require_once($aliWap . '/wappay/service/AlipayTradeService.php');
  333. require_once($aliWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  334. $totalFee = $order['actPrice'];
  335. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  336. $subject = '购买商品';//订单名称,必填
  337. $total_amount = $totalFee;//付款金额,必填
  338. $body = '';//商品描述,可空
  339. $timeout_express = "1m";//超时时间
  340. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  341. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  342. $passBackParams = urlencode($passBackParams);
  343. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  344. $payRequestBuilder->setBody($body);
  345. $payRequestBuilder->setSubject($subject);
  346. $payRequestBuilder->setOutTradeNo($out_trade_no);
  347. $payRequestBuilder->setTotalAmount($total_amount);
  348. $payRequestBuilder->setTimeExpress($timeout_express);
  349. //在异步通知时将该参数原样返回
  350. $payRequestBuilder->setPassbackParams($passBackParams);
  351. //同步通知
  352. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  353. //异步通知
  354. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  355. $payResponse = new \AlipayTradeService($config);
  356. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  357. //直接将支付宝的html返回给前端
  358. echo $result;
  359. } elseif ($payWay == 2) {
  360. //余额支付,验证支付密码是否正确
  361. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  362. $user = UserService::getUserInfo($this->userId);
  363. UserService::validPayPassword($payPassword, $user);
  364. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  365. $callbackParams = [];
  366. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  367. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  368. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'orderSn' => $orderSn, 'orderId' => $orderId, 'balance' => $balance]);
  369. } else {
  370. util::fail('无效的支付方式');
  371. }
  372. }
  373. //订单列表 ssh 2019.12.12
  374. public function actionList()
  375. {
  376. $where = ['customId' => $this->customId];
  377. $list = OrderService::getOrderList($where);
  378. util::success($list);
  379. }
  380. //订单评价
  381. public function actionComment()
  382. {
  383. $post = Yii::$app->request->post();
  384. $id = $post['id'];
  385. $order = OrderService::getById($id);
  386. OrderService::valid($order, $this->shopId);
  387. if ($order['grade'] > 0) {
  388. util::fail('您已经评过了');
  389. }
  390. OrderService::comment($post);
  391. util::complete('提交成功');
  392. }
  393. //订单详情 ssh 2019.12.16
  394. public function actionDetail()
  395. {
  396. $id = Yii::$app->request->get('id', 0);
  397. $orderSn = Yii::$app->request->get('orderSn', '');
  398. $detail = [];
  399. if (!empty($id)) {
  400. $detail = OrderService::getOrderById($id);
  401. }
  402. if (!empty($orderSn)) {
  403. $detail = OrderService::getOrderBySn($orderSn);
  404. }
  405. OrderService::valid($detail, $this->shopId);
  406. util::success($detail);
  407. }
  408. }