PayController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. namespace mall\controllers;
  3. use bizMall\goods\services\CategoryRelateService;
  4. use bizMall\goods\services\UsageRelationService;
  5. use bizMall\order\services\OrderService;
  6. use bizMall\promote\services\CouponService;
  7. use common\models\xhShop;
  8. use common\services\xhMerchantExtendService;
  9. use Yii;
  10. use common\services\xhUserAssetService;
  11. use common\services\xhUserService;
  12. use common\services\xhCouponService;
  13. use common\services\xhOrderService;
  14. use common\components\util;
  15. use common\components\stringUtil;
  16. use common\components\dict;
  17. class PayController extends BaseController
  18. {
  19. public $guestAccess = ['get-params'];
  20. //创建订单 ssh 2019.12.3
  21. public function actionCreateOrder()
  22. {
  23. $post = Yii::$app->request->post();
  24. $customId = $this->customId;
  25. $post['customId'] = $customId;
  26. $post['payWay'] = $this->isWx == true ? 0 : 1;
  27. $lat2 = $post['receiveLat'];//收货人纬度
  28. $lng2 = $post['long'];//收货人经度
  29. $lat1 = $this->sj['lat'];//花店纬度
  30. $lng1 = $this->sj['long'];//花店经度
  31. $calcDistance = util::getDistance($lat1, $lng1, $lat2, $lng2);//防止别人改动,PHP计算的距离会比腾讯js算的小,但能保证有一定准确性
  32. $post['sendDistance'] = $post['sendDistance'] >= $calcDistance ? $post['sendDistance'] : $calcDistance;//二地距离
  33. $sendDistance = $post['sendDistance'];
  34. $freight = dict::getDict('freight');
  35. $firstDistance = $freight['firstDistance'];
  36. $firstPrice = $freight['firstPrice'];
  37. $nextDistance = $freight['nextDistance'];
  38. $nextPrice = $freight['nextPrice'];
  39. if ($sendDistance <= $firstDistance && $post['isCharge'] == 1) {
  40. $post['sendCost'] = $firstPrice;
  41. } else if ($post['isCharge'] == 1) {
  42. $subDistance = $sendDistance - $firstDistance;
  43. $addPrice = intval($subDistance / $nextDistance) * $nextPrice;
  44. $post['sendCost'] = $firstPrice + $addPrice;
  45. }
  46. if (empty($this->sjExtend['payment'])) {
  47. util::fail('支付功能未开通,暂时无法购买哦~');
  48. }
  49. $couponAmount = 0;
  50. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;//代金劵
  51. if (!empty($couponId)) {
  52. $coupon = xhCouponService::getById($couponId);
  53. $couponUserId = $coupon['userId'];
  54. if ($couponUserId != $customId) {
  55. util::fail('不是你的代金劵');
  56. }
  57. if ($coupon['useStatus'] == 1 || $coupon['deadline'] < time()) {
  58. util::fail('代金劵已经失效了');
  59. }
  60. $couponAmount = $coupon['amount'];
  61. }
  62. //不要将代金劵保存到订单表,付款成功后再保存进去!!!
  63. unset($post['couponId']);
  64. $post['sjId'] = $this->sjId;
  65. //店铺id
  66. $post['shopId'] = $this->sj['defaultShopId'];
  67. $order = xhOrderService::add($post);//创建订单
  68. if ($order == false) {
  69. util::fail('创建订单失败');
  70. }
  71. $orderId = $order['id'];
  72. $oData = [];
  73. $goodsInfo = $post['goodsInfo'];
  74. $totalFee = 0;//计算总价格
  75. $goodsIdList = [];
  76. $multiPriceIdList = [];
  77. $orderName = '';
  78. $goodsNum = 0;
  79. foreach ($goodsInfo as $key => $val) {
  80. $multiPriceId = 0;//多种价格表Id
  81. $goodsId = $val['goodsId'];
  82. $num = $val['num'];
  83. $goodsNum += $num;
  84. $goods = xhGoodsService::getById($goodsId);
  85. if (empty($orderName)) {
  86. $orderName = $goods['name'];
  87. }
  88. $price = $goods['price'];
  89. if ($val['multiPriceId'] != 0 && $goods['multiPrice'] != '') {
  90. $pos = strpos($goods['multiPrice'], $val['multiPriceId']);
  91. if ($pos === false) {
  92. util::fail('订单的商品不存在');
  93. }
  94. $goodPrice = xhGoodsPriceService::getById($val['multiPriceId']);
  95. //$price = $goodPrice['price'];
  96. $price = xhGoodsSettingService::changePrice($goods, $goodPrice['price']);//统一对商品进行价格等方面设置
  97. //多种价格规格 替换 默认(单价格)
  98. $goods['name'] = $goodPrice['title'];
  99. //$goods['cover'] = $goodPrice['picture'];//后台图片上传功能未开发,暂时使用默认商品图片
  100. $multiPriceId = $val['multiPriceId'];
  101. }
  102. $totalFee += $price * $num;
  103. $goodsIdList[] = $goodsId;
  104. $multiPriceIdList[] = $multiPriceId;
  105. $data = [
  106. 'orderId' => $orderId,
  107. 'goodsId' => $goodsId,
  108. 'customId' => $customId,
  109. 'sjId' => $this->sjId,
  110. 'title' => $goods['name'],
  111. 'cover' => $goods['cover'],
  112. 'unitPrice' => $price,
  113. 'num' => $num,
  114. 'multiPriceId' => $multiPriceId,
  115. 'createTime' => date("Y-m-d H:i:s"),
  116. ];
  117. xhOrderGoodsService::add($data);//创建订单商品列表
  118. }
  119. $sendCost = $post['sendCost'];//运费
  120. $oData['goodsNum'] = $goodsNum;//订单的商品数量类型,单个还是多个的
  121. $oData['prePrice'] = $totalFee + $sendCost;
  122. $oData['orderName'] = $goodsNum > 1 ? $orderName . '等' . $goodsNum . '件商品' : $orderName;
  123. if (isset($post['sourceType']) && $post['sourceType'] == 'cart') {
  124. if (!empty($goodsIdList)) {
  125. foreach ($goodsIdList as $key => $goodsId) {
  126. xhCartService::delByIds($customId, $goodsId, $multiPriceIdList[$key]);//删除购物车($userId, $goodsId, $goodsPriceId, $cartId)
  127. }
  128. }
  129. }
  130. $userAsset = xhUserAssetService::getByUserId($customId);
  131. $level = $userAsset['member'];
  132. if ($level > 0) {
  133. $gradeList = xhMerchantExtendService::getGradeList($this->sjExtend);
  134. $discount = $gradeList[$level]['discount'];
  135. $discount = strlen($discount) == 1 ? $discount * 10 : $discount;
  136. $totalFee = number_format($discount * $totalFee / 100, 2);
  137. }
  138. $oData['actPrice'] = $totalFee + $sendCost - $couponAmount;
  139. xhOrderService::updateById($orderId, $oData);
  140. util::success(['orderId' => $orderId, 'couponId' => $couponId], '订单创建成功');
  141. }
  142. public function actionParams()
  143. {
  144. ini_set('date.timezone', 'Asia/Shanghai');
  145. $post = Yii::$app->request->post();
  146. $payWay = isset($post['payWay']) ? $post['payWay'] : '';
  147. $shopId = isset($post['shopId']) ? $post['shopId'] : 0;
  148. //来源 0自建商城 1门店 2微信朋友圈 3淘宝
  149. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  150. $shopInfo = xhShop::find()->where(['id' => $shopId])->one();
  151. if (empty($shopInfo) || $shopInfo->sjId != $this->sjId) {
  152. util::fail('门店无效');
  153. }
  154. unset($post['payWay']);
  155. $post['userId'] = $this->userId;
  156. $prePrice = round($post['prePrice'], 2);//四舍五入,保留二位小数
  157. $userAsset = xhUserAssetService::getByUserId($this->userId);
  158. $level = isset($userAsset['member']) ? $userAsset['member'] : 0;
  159. $sjExtend = xhMerchantExtendService::getBySjId($this->sjId);
  160. $memberIntegral = xhMerchantExtendService::getGradeList($sjExtend, 'desc');
  161. Yii::info(json_encode($sjExtend));
  162. Yii::info(json_encode($memberIntegral));
  163. //$discount = isset($memberIntegral[$level]['discount']) ? $memberIntegral[$level]['discount'] : $memberIntegral[$level]['discount'];
  164. $discount = 0;
  165. $actPrice = $prePrice;
  166. $couponId = isset($post['couponId']) && !empty($post['couponId']) ? $post['couponId'] : 0;
  167. Yii::info($this->userId . ' ' . $level . ' ' . $discount);
  168. //没有优惠券才能使用会员折扣 ssh 2019.8.30
  169. if (!empty($discount) && $prePrice >= 1 && empty($couponId)) {
  170. $currentPrice = ($prePrice * $discount) / 100;
  171. $actPrice = substr(sprintf("%.3f", $currentPrice), 0, -2);
  172. }
  173. //没有优惠卷,微信朋友圈付款才给随机优惠金额 ssh 2019.9.12
  174. if ($sourceType == 2 && empty($couponId)) {
  175. $discountAmount = OrderService::getRandDiscount($actPrice);
  176. $discountAmount = 0.01;
  177. $actPrice = stringUtil::calcSub($actPrice, $discountAmount);
  178. $post['discountType'] = 2;//优惠类型是:付款随机优惠
  179. $post['discountAmount'] = $discountAmount;
  180. }
  181. $post['actPrice'] = $actPrice;
  182. $post['payStyle'] = 0;
  183. $post['sjId'] = $this->sjId;
  184. $now = time();
  185. $expireTime = $now + 1800;//订单30分钟后过期
  186. $post['createTime'] = date("Y-m-d H:i:s", $now);
  187. $post['deadline'] = $expireTime;
  188. if (!empty($couponId)) {
  189. $time = time();
  190. $coupon = CouponService::getById($couponId);
  191. if ($coupon['deadline'] <= $time) {
  192. util::fail('优惠卷已经过期');
  193. }
  194. if ($coupon['status'] == 1) {
  195. util::fail('优惠卷已经使用');
  196. }
  197. if ($coupon['meetAmount'] > $post['prePrice']) {
  198. util::fail('消费金额不足' . $coupon['meetAmount'] . '元');
  199. }
  200. $post['actPrice'] = stringUtil::calcSub($post['prePrice'], $coupon['amount']);//浮点相减
  201. $post['discountAmount'] = $coupon['amount'];
  202. $post['discountType'] = 0;
  203. }
  204. if ($post['actPrice'] <= 0) {
  205. util::fail('消费金额太低');
  206. }
  207. if ($this->isWx) {
  208. $post['modPriceStatus'] = 1;//微信已经提交不能再修改价格
  209. }
  210. $post['sourceType'] = $sourceType;
  211. $post['id'] = stringUtil::generateOrderNo($this->sjId, $this->userId);
  212. $payment = xhOrderService::add($post);
  213. $orderId = $payment['id'];
  214. if ($payWay == 'balance') {//余额支付
  215. util::success(['orderId' => $orderId]);
  216. }
  217. $name = '购买商品';
  218. $totalFee = $post['actPrice'];
  219. if ($this->isWx) {
  220. $userId = $post['userId'];
  221. $user = xhUserService::getById($userId);
  222. if ($user['sjId'] != $this->sjId) {
  223. util::fail('非法用户');
  224. }
  225. $openId = $user['openId'];
  226. $capitalType = dict::getDict('capitalType','xhOrder','id');
  227. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId;//将流水类型、优惠卷传过去
  228. $weixin = Yii::getAlias("@vendor/weixin");
  229. require_once($weixin . '/lib/WxPay.Api.php');
  230. require_once($weixin . '/example/WxPay.JsApiPay.php');
  231. $input = new \WxPayUnifiedOrder();
  232. $input->SetBody($name);
  233. $input->SetOut_trade_no($orderId);
  234. $input->SetTotal_fee($totalFee * 100);
  235. $input->SetTime_start(date("YmdHis", $now));
  236. $input->SetAttach($attach);
  237. $input->SetTime_expire(date("YmdHis", $expireTime));//设置订单有效期5分钟
  238. $input->SetNotify_url($this->frontUrl . '/notice/weixin-callback/');
  239. $input->SetTrade_type("JSAPI");
  240. //服务商 代设置微信支付,要添加的参数设置
  241. if ($this->sjExtend['wxPayApply'] == 1) {
  242. //$input->SetOpenid($openId);
  243. $input->SetSub_openid($openId);
  244. //自设置 微信支付
  245. } else {
  246. $input->SetOpenid($openId);
  247. }
  248. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $this->sjExtend);
  249. $tools = new \JsApiPay();
  250. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $this->sjExtend);
  251. $newParams = json_decode($jsApiParameters, true);
  252. $newParams['orderId'] = $orderId;
  253. util::success($newParams);
  254. }
  255. util::success(['orderId' => $orderId]);
  256. }
  257. }