OrderController.php 18 KB

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