OrderController.php 18 KB

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