OrderController.php 18 KB

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