OrderController.php 21 KB

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