OrderController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. //默认门店订单
  243. $store = isset($post['store']) ? $post['store'] : 1;
  244. $post['store'] = $store;
  245. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  246. $sourceType = $this->isWx ? 0 : 1;
  247. if (httpUtil::isMiniProgram()) {
  248. $sourceType = 2;
  249. }
  250. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  251. $post['userId'] = $this->userId;
  252. $user = $this->user;
  253. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  254. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  255. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  256. $post['bookMobile'] = $bookMobile;
  257. $prePrice = round($post['prePrice'], 2);
  258. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  259. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->userId]);
  260. $actPrice = $discountData['price'];
  261. $post['discountType'] = $discountData['discountType'];
  262. $post['discountAmount'] = $discountData['discountAmount'];
  263. $post['actPrice'] = $actPrice;
  264. $post['payStyle'] = 0;
  265. $post['merchantId'] = $this->merchantId;
  266. $now = time();
  267. $expireTime = $now + 300;//订单5分钟后过期
  268. $post['createTime'] = date("Y-m-d H:i:s", $now);
  269. $post['deadline'] = $expireTime;
  270. if ($actPrice <= 0) {
  271. util::fail('请填写正确的金额');
  272. }
  273. //微信支付订单提交不能修改价格
  274. $post['modPrice'] = $this->isWx ? 0 : 1;
  275. $post['sourceType'] = $sourceType;
  276. $order = OrderService::addOrder($post);
  277. $orderId = $order['id'];
  278. $orderSn = $order['orderSn'];
  279. $merchantId = $this->merchantId;
  280. if ($payWay == 0) {
  281. $orderId = $order['id'];
  282. $name = '购买商品';
  283. $totalFee = $actPrice;
  284. $user = UserService::getById($this->userId);
  285. $openId = isset($user['openId']) ? $user['openId'] : 0;
  286. if (httpUtil::isMiniProgram()) {
  287. //小程序使用miniOpenId
  288. $openId = $user['miniOpenId'];
  289. }
  290. if (empty($openId)) {
  291. util::fail('没有找到客户的openId');
  292. }
  293. $typeList = configDict::getConfig('capitalType');
  294. $capitalType = $typeList['xhOrder']['id'];
  295. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  296. $wxPayType = 0;
  297. if (httpUtil::isMiniProgram()) {
  298. $wxPayType = 1;
  299. }
  300. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  301. $wx = Yii::getAlias("@vendor/weixin");
  302. require_once($wx . '/lib/WxPay.Api.php');
  303. require_once($wx . '/example/WxPay.JsApiPay.php');
  304. $input = new \WxPayUnifiedOrder();
  305. $input->SetBody($name);
  306. $input->SetOut_trade_no($orderSn);
  307. $input->SetTotal_fee($totalFee * 100);
  308. $input->SetTime_start(date("YmdHis", $now));
  309. $input->SetAttach($attach);
  310. //设置订单有效期5分钟
  311. $input->SetTime_expire(date("YmdHis", $expireTime));
  312. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  313. $input->SetTrade_type("JSAPI");
  314. //花卉宝代为申请的微信支付
  315. $merchantExtend = $this->merchantExtend;
  316. if ($merchantExtend['wxPayApply'] == 1) {
  317. $input->SetSub_openid($openId);
  318. } else {
  319. $input->SetOpenid($openId);
  320. }
  321. //小程序使用miniAppId
  322. if (httpUtil::isMiniProgram()) {
  323. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  324. }
  325. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  326. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  327. $tools = new \JsApiPay();
  328. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  329. $newParams = json_decode($jsApiParameters, true);
  330. $newParams['orderId'] = $orderId;
  331. util::success($newParams);
  332. } elseif ($payWay == 1) {
  333. $extend = MerchantExtendService::getByMerchantId($merchantId);
  334. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  335. util::fail('支付宝付款即将开通...');
  336. }
  337. $config = [
  338. //应用ID,您的APPID。
  339. 'app_id' => $extend['alipayPId'],
  340. //商户私钥,您的原始格式RSA私钥
  341. 'merchant_private_key' => $extend['alipayKey'],
  342. //异步通知地址
  343. 'notify_url' => Yii::$app->params['mallHost'] . "/notice/alipay-callback",
  344. //同步跳转
  345. 'return_url' => "",
  346. //编码格式
  347. 'charset' => "UTF-8",
  348. //签名方式
  349. 'sign_type' => "RSA2",
  350. //支付宝网关
  351. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  352. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  353. 'alipay_public_key' => $extend['alipayPublicKey'],
  354. ];
  355. Yii::info(json_encode($config).' aplipay config');
  356. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  357. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  358. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  359. $totalFee = $order['actPrice'];
  360. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  361. $subject = '购买商品';//订单名称,必填
  362. $total_amount = $totalFee;//付款金额,必填
  363. $body = '';//商品描述,可空
  364. $timeout_express = "1m";//超时时间
  365. $typeList = configDict::getConfig('capitalType');
  366. $capitalType = $typeList['xhOrder']['id'];
  367. $passbackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&merchantId=' . $merchantId;//将流水类型、优惠卷传过去
  368. $passbackParams = urlencode($passbackParams);
  369. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  370. $payRequestBuilder->setBody($body);
  371. $payRequestBuilder->setSubject($subject);
  372. $payRequestBuilder->setOutTradeNo($out_trade_no);
  373. $payRequestBuilder->setTotalAmount($total_amount);
  374. $payRequestBuilder->setTimeExpress($timeout_express);
  375. //在异步通知时将该参数原样返回
  376. $payRequestBuilder->setPassbackParams($passbackParams);
  377. //同步通知
  378. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$merchantId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  379. //异步通知
  380. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/alipay-callback";
  381. $payResponse = new \AlipayTradeService($config);
  382. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  383. //直接将支付宝的html返回给前端
  384. echo $result;
  385. } elseif ($payWay == 2) {
  386. //余额支付,验证支付密码是否正确
  387. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  388. $user = UserService::getUserInfo($this->userId, false);
  389. UserService::validPayPassword($payPassword, $user);
  390. $typeList = configDict::getConfig('capitalType');
  391. $capitalType = $typeList['xhOrder']['id'];
  392. $callbackParams = [];
  393. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  394. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  395. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'orderSn' => $orderSn, 'orderId' => $orderId, 'balance' => $balance]);
  396. } else {
  397. util::fail('无效的支付方式');
  398. }
  399. }
  400. //订单列表 shish 2019.12.12
  401. public function actionList()
  402. {
  403. $where = ['userId' => $this->userId];
  404. $list = OrderService::getOrderList($where);
  405. util::success($list);
  406. }
  407. //订单评价
  408. public function actionComment()
  409. {
  410. $post = Yii::$app->request->post();
  411. $id = $post['id'];
  412. $order = OrderService::getById($id);
  413. OrderService::valid($order, $this->merchantId);
  414. if ($order['grade'] > 0) {
  415. util::fail('您已经评过了');
  416. }
  417. OrderService::comment($post);
  418. util::complete('提交成功');
  419. }
  420. //订单详情 shish 2019.12.16
  421. public function actionDetail()
  422. {
  423. $id = Yii::$app->request->get('id', 0);
  424. $orderSn = Yii::$app->request->get('orderSn', '');
  425. $detail = [];
  426. if (!empty($id)) {
  427. $detail = OrderService::getOrderById($id);
  428. }
  429. if (!empty($orderSn)) {
  430. $detail = OrderService::getOrderBySn($orderSn);
  431. }
  432. OrderService::valid($detail, $this->merchantId);
  433. util::success($detail);
  434. }
  435. }