PayController.php 11 KB

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