OrderController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. <?php
  2. namespace mall\controllers;
  3. use biz\goods\services\CategoryService;
  4. use biz\goods\services\GoodsCategoryService;
  5. use biz\goods\services\GoodsService;
  6. use biz\merchant\services\MerchantExtendService;
  7. use biz\merchant\services\MerchantService;
  8. use biz\merchant\services\ShopService;
  9. use biz\order\services\OrderGoodsService;
  10. use biz\order\services\OrderService;
  11. use biz\promote\services\CouponService;
  12. use biz\saas\services\RegionService;
  13. use biz\user\services\UserAssetService;
  14. use biz\user\services\UserService;
  15. use common\components\configDict;
  16. use common\components\httpUtil;
  17. use common\components\stringUtil;
  18. use common\services\xhPayToolService;
  19. use Yii;
  20. use yii\web\Controller;
  21. use common\components\util;
  22. class OrderController extends BaseController
  23. {
  24. public $withoutLogin = ['order-relate', 'fast-pay'];
  25. //商城下单操作 shish 2019.12.3
  26. public function actionCreateOrder()
  27. {
  28. $post = Yii::$app->request->post();
  29. $goodsId = isset($post['goodsId']) ? $post['goodsId'] : 0;
  30. $goodsStyleId = isset($post['goodsStyleId']) ? $post['goodsStyleId'] : 0;
  31. $goodsNum = isset($post['goodsNum']) && $post['goodsNum'] > 0 ? $post['goodsNum'] : 1;
  32. if (empty($goodsId)) {
  33. util::fail('请选择商品');
  34. }
  35. $goodsInfo = GoodsService::getGoodsInfo($goodsId);
  36. if (empty($goodsInfo)) {
  37. util::fail('没有找到商品');
  38. }
  39. if (isset($goodsInfo['stock']) == false || $goodsInfo['stock'] == 0) {
  40. util::fail('已经卖完了');
  41. }
  42. //确认是否要配送的商品
  43. $needSend = isset($goodsInfo['needSend']) && $goodsInfo['needSend'] == 1 ? 1 : 0;
  44. $post['userId'] = $this->userId;
  45. $user = $this->user;
  46. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  47. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  48. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  49. $post['bookMobile'] = $bookMobile;
  50. $post['payWay'] = $this->isWx == true ? 0 : 1;
  51. $defaultShopId = MerchantService::getDefaultShopId($this->merchant);
  52. if (empty($defaultShopId)) {
  53. util::fail('没有找到门店');
  54. }
  55. $shopInfo = ShopService::getById($defaultShopId);
  56. //计算运费
  57. $post['sendDistance'] = isset($post['sendDistance']) ? $post['sendDistance'] : 0;
  58. $sendCost = 0;
  59. if ($needSend == 1) {
  60. $lat = $post['receiveLat'];//收货人纬度
  61. $lng = $post['receiveLong'];//收货人经度
  62. $jsStatDistance = $post['sendDistance'];
  63. $sendCost = ShopService::getSendCost($lat, $lng, $jsStatDistance, $shopInfo);
  64. }
  65. $post['sendCost'] = $sendCost;
  66. $post['merchantId'] = $this->merchantId;
  67. $post['shopId'] = $defaultShopId;
  68. //计算总金额
  69. $unitPrice = $goodsInfo['price'];
  70. $goodsStyleList = isset($goodsInfo['goodsStyleList']) ? $goodsInfo['goodsStyleList'] : [];
  71. if (!empty($goodsStyleId)) {
  72. if (empty($goodsStyleList)) {
  73. util::fail('商品款式没有找到');
  74. }
  75. $styleIdList = array_keys($goodsStyleList);
  76. if (in_array($goodsStyleId, $styleIdList) == false) {
  77. util::fail('商品款式没有找到!');
  78. }
  79. $unitPrice = isset($goodsStyleList[$goodsStyleId]['price']) ? $goodsStyleList[$goodsStyleId]['price'] : 9999;
  80. }
  81. $goodsPrice = $unitPrice * $goodsNum;
  82. $prePrice = stringUtil::calcAdd($sendCost, $goodsPrice);
  83. $showPrice = $prePrice;
  84. //非门店订单
  85. $store = 0;
  86. $post['store'] = $store;
  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['prePrice'] = $prePrice;
  101. $post['actPrice'] = $actPrice;
  102. $order = OrderService::addOrder($post);
  103. $orderId = $order['id'];
  104. $orderSn = $order['orderSn'];
  105. $data = [
  106. 'orderId' => $orderId,
  107. 'goodsId' => $goodsId,
  108. 'userId' => $this->userId,
  109. 'merchantId' => $this->merchantId,
  110. 'title' => $goodsInfo['goodsName'],
  111. 'cover' => isset($goodsInfo['shortImgList']) && !empty($goodsInfo['shortImgList']) ? current($goodsInfo['shortImgList']) : '',
  112. 'unitPrice' => $unitPrice,
  113. 'num' => $goodsNum,
  114. 'goodsStyleName' => isset($goodsInfo['goodsStyleList'][$goodsStyleId]['title']) ? $goodsInfo['goodsStyleList'][$goodsStyleId]['title'] : '',
  115. 'goodsStyleId' => $goodsStyleId,
  116. 'createTime' => date("Y-m-d H:i:s"),
  117. ];
  118. OrderGoodsService::add($data);//创建订单商品列表
  119. util::success(['orderSn' => $orderSn, 'totalPrice' => $showPrice, 'couponId' => $couponId]);
  120. }
  121. //下单要用到的相关信息 shish 2019.12.6
  122. public function actionOrderRelate()
  123. {
  124. $regionTree = RegionService::tree();
  125. $shop = ShopService::getDefaultShop($this->merchant);
  126. $freight = MerchantExtendService::getFreight($this->merchantExtend);
  127. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  128. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'txMapKey' => $mapKey, 'merchant' => $this->merchant];
  129. util::success($out);
  130. }
  131. //余额支付 shish 2019.12.6
  132. public function actionBalancePay()
  133. {
  134. $post = Yii::$app->request->post();
  135. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  136. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  137. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  138. $order = OrderService::getByOrderSn($orderSn);
  139. $userId = $this->userId;
  140. $user = UserService::getUserInfo($userId, false);
  141. //验证支付密码是否正确
  142. UserService::validPayPassword($payPassword, $user);
  143. //验证订单有效性
  144. OrderService::check($order, $this->userId);
  145. $typeList = configDict::getConfig('capitalType');
  146. $capitalType = $typeList['xhOrder']['id'];
  147. $totalFee = $order['actPrice'];
  148. $sourceType = 0;
  149. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->userId]);
  150. $actPrice = $discountData['price'];
  151. $respond = xhPayToolService::balancePay($orderSn, $actPrice, $capitalType, $couponId);
  152. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  153. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  154. }
  155. //获取商城下单要用的微信支付和小程序支付参数 shish 2019.21.3
  156. public function actionWxPay()
  157. {
  158. ini_set('date.timezone', 'Asia/Shanghai');
  159. $post = Yii::$app->request->post();
  160. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  161. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  162. $order = OrderService::getByOrderSn($orderSn);
  163. $orderId = $order['id'];
  164. //验证订单有效性
  165. OrderService::check($order, $this->userId);
  166. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  167. $totalFee = $order['actPrice'];
  168. //小程序使用miniOpenId
  169. if (httpUtil::isMiniProgram()) {
  170. $openId = $this->user['miniOpenId'];
  171. } else {
  172. $openId = $this->user['openId'];
  173. }
  174. $typeList = configDict::getConfig('capitalType');
  175. $capitalType = $typeList['xhOrder']['id'];
  176. //将流水类型、代金劵传过去
  177. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType;
  178. //订单30分钟后过期
  179. $now = time();
  180. $expireTime = $now + 1800;
  181. $wx = Yii::getAlias("@vendor/weixin");
  182. require_once($wx . '/lib/WxPay.Api.php');
  183. require_once($wx . '/example/WxPay.JsApiPay.php');
  184. $input = new \WxPayUnifiedOrder();
  185. $input->SetBody($name);
  186. $input->SetOut_trade_no($orderSn);
  187. $input->SetTotal_fee($totalFee * 100);
  188. $input->SetTime_start(date("YmdHis", $now));
  189. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  190. $input->SetTime_expire(date("YmdHis", $expireTime));
  191. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  192. $input->SetTrade_type("JSAPI");
  193. //花卉宝代为申请的微信支付
  194. $merchantExtend = $this->merchantExtend;
  195. if ($merchantExtend['wxPayApply'] == 1) {
  196. $input->SetSub_openid($openId);
  197. } else {
  198. $input->SetOpenid($openId);
  199. }
  200. //小程序使用miniAppId
  201. if (httpUtil::isMiniProgram()) {
  202. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  203. }
  204. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  205. $tools = new \JsApiPay();
  206. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  207. $newParams = json_decode($jsApiParameters, true);
  208. //已请求微信不能修改价格
  209. $updateData = [];
  210. $updateData['modPrice'] = 0;
  211. if (empty($order['deadline'])) {
  212. $updateData['deadline'] = $expireTime;
  213. }
  214. OrderService::updateById($orderId, $updateData);
  215. util::success($newParams);
  216. }
  217. //快捷付款订单
  218. public function actionFastPay()
  219. {
  220. ini_set('date.timezone', 'Asia/Shanghai');
  221. $post = Yii::$app->request->post();
  222. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  223. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->merchant);
  224. //验证门店是否有效
  225. $shopInfo = ShopService::getById($shopId);
  226. ShopService::valid($shopInfo, $this->merchantId);
  227. //默认门店订单
  228. $store = isset($post['store']) ? $post['store'] : 1;
  229. $post['store'] = $store;
  230. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  231. $sourceType = $this->isWx ? 0 : 1;
  232. if (httpUtil::isMiniProgram()) {
  233. $sourceType = 2;
  234. }
  235. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  236. $post['userId'] = $this->userId;
  237. $user = $this->user;
  238. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  239. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  240. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  241. $post['bookMobile'] = $bookMobile;
  242. $prePrice = round($post['prePrice'], 2);
  243. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  244. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->userId]);
  245. $actPrice = $discountData['price'];
  246. $post['discountType'] = $discountData['discountType'];
  247. $post['discountAmount'] = $discountData['discountAmount'];
  248. $post['actPrice'] = $actPrice;
  249. $post['payStyle'] = 0;
  250. $post['merchantId'] = $this->merchantId;
  251. $now = time();
  252. $expireTime = $now + 300;//订单5分钟后过期
  253. $post['createTime'] = date("Y-m-d H:i:s", $now);
  254. $post['deadline'] = $expireTime;
  255. if ($actPrice <= 0) {
  256. util::fail('请填写正确的金额');
  257. }
  258. //微信支付订单提交不能修改价格
  259. $post['modPrice'] = $this->isWx ? 0 : 1;
  260. $post['sourceType'] = $sourceType;
  261. $order = OrderService::addOrder($post);
  262. $orderId = $order['id'];
  263. $orderSn = $order['orderSn'];
  264. $merchantId = $this->merchantId;
  265. if ($payWay == 0) {
  266. $orderId = $order['id'];
  267. $name = '购买商品';
  268. $totalFee = $actPrice;
  269. $user = UserService::getById($this->userId);
  270. $openId = isset($user['openId']) ? $user['openId'] : 0;
  271. if (httpUtil::isMiniProgram()) {
  272. //小程序使用miniOpenId
  273. $openId = $user['miniOpenId'];
  274. }
  275. if (empty($openId)) {
  276. util::fail('没有找到客户的openId');
  277. }
  278. $typeList = configDict::getConfig('capitalType');
  279. $capitalType = $typeList['xhOrder']['id'];
  280. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId;//将流水类型、优惠卷传过去
  281. $wx = Yii::getAlias("@vendor/weixin");
  282. require_once($wx . '/lib/WxPay.Api.php');
  283. require_once($wx . '/example/WxPay.JsApiPay.php');
  284. $input = new \WxPayUnifiedOrder();
  285. $input->SetBody($name);
  286. $input->SetOut_trade_no($orderSn);
  287. $input->SetTotal_fee($totalFee * 100);
  288. $input->SetTime_start(date("YmdHis", $now));
  289. $input->SetAttach($attach);
  290. $input->SetTime_expire(date("YmdHis", $expireTime));//设置订单有效期5分钟
  291. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  292. $input->SetTrade_type("JSAPI");
  293. //花卉宝代为申请的微信支付
  294. $merchantExtend = $this->merchantExtend;
  295. if ($merchantExtend['wxPayApply'] == 1) {
  296. $input->SetSub_openid($openId);
  297. } else {
  298. $input->SetOpenid($openId);
  299. }
  300. //小程序使用miniAppId
  301. if (httpUtil::isMiniProgram()) {
  302. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  303. }
  304. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  305. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  306. $tools = new \JsApiPay();
  307. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  308. $newParams = json_decode($jsApiParameters, true);
  309. $newParams['orderId'] = $orderId;
  310. util::success($newParams);
  311. } elseif ($payWay == 1) {
  312. $extend = MerchantExtendService::getByMerchantId($merchantId);
  313. if (isset($extend['alipayInit']) || $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/alipay-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. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  335. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  336. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  337. $totalFee = $order['actPrice'];
  338. $out_trade_no = $orderId;//商户订单号,商户网站订单系统中唯一订单号,必填
  339. $subject = '购买商品';//订单名称,必填
  340. $total_amount = $totalFee;//付款金额,必填
  341. $body = '';//商品描述,可空
  342. $timeout_express = "1m";//超时时间
  343. $typeList = configDict::getConfig('capitalType');
  344. $capitalType = $typeList['xhOrder']['id'];
  345. $passbackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&merchantId=' . $merchantId;//将流水类型、优惠卷传过去
  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/index?account={$merchantId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  357. //异步通知
  358. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/alipay-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. $typeList = configDict::getConfig('capitalType');
  369. $capitalType = $typeList['xhOrder']['id'];
  370. $respond = xhPayToolService::balancePay($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. //订单列表 shish 2019.12.12
  378. public function actionList()
  379. {
  380. $where = ['userId' => $this->userId];
  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. if ($this->userId != $order['userId']) {
  391. util::fail('您没有权限操作');
  392. }
  393. OrderService::comment($post);
  394. util::complete('提交成功');
  395. }
  396. //订单详情 shish 2019.12.16
  397. public function actionDetail()
  398. {
  399. $id = Yii::$app->request->get('id', 0);
  400. $orderSn = Yii::$app->request->get('orderSn', '');
  401. $detail = [];
  402. if (!empty($id)) {
  403. $detail = OrderService::getOrderById($id);
  404. }
  405. if (!empty($orderSn)) {
  406. $detail = OrderService::getOrderBySn($orderSn);
  407. }
  408. OrderService::valid($detail, $this->merchantId);
  409. util::success($detail);
  410. }
  411. }