OrderController.php 21 KB

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