OrderController.php 21 KB

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