OrderController.php 20 KB

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