OrderController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. namespace ghs\controllers;
  3. use biz\merchant\services\ExpressService;
  4. use biz\merchant\services\MerchantAssetService;
  5. use biz\merchant\services\MerchantExtendService;
  6. use biz\merchant\services\MerchantService;
  7. use bizGhs\merchant\services\ShopService;
  8. use biz\order\classes\OrderSendClass;
  9. use bizGhs\order\services\OrderService;
  10. use biz\saas\services\RegionService;
  11. use biz\user\services\UserService;
  12. use common\components\configDict;
  13. use common\components\httpUtil;
  14. use common\services\xhPayToolService;
  15. use Yii;
  16. use common\components\util;
  17. use common\components\stringUtil;
  18. class OrderController extends BaseController
  19. {
  20. public $withoutLogin = ['order-relate', 'fast-pay'];
  21. //商城下单操作 shish 2021.1.14
  22. public function actionCreateOrder()
  23. {
  24. $post = Yii::$app->request->post();
  25. $goodsId = isset($post['goodsId']) ? $post['goodsId'] : 0;
  26. $goodsNum = isset($post['goodsNum']) && $post['goodsNum'] > 0 ? $post['goodsNum'] : 1;
  27. $needSend = $post['needSend'] ?? 1;
  28. // if (empty($goodsId)) {
  29. // util::fail('请选择商品');
  30. // }
  31. // $goodsInfo = GoodsService::getGoodsInfo($goodsId);
  32. // if (empty($goodsInfo)) {
  33. // util::fail('没有找到商品');
  34. // }
  35. // if (isset($goodsInfo['stock']) == false || $goodsInfo['stock'] == 0) {
  36. // util::fail('已经卖完了');
  37. // }
  38. //运费计算方式
  39. $freightType = $goodsInfo['freightType'] ?? 0;
  40. //$post['adminId'] = $this->adminId;
  41. $post['adminId'] = 0;
  42. $user = $this->admin;
  43. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  44. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  45. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  46. $post['bookMobile'] = $bookMobile;
  47. $post['payWay'] = $this->isWx == true ? 0 : 1;
  48. $defaultShopId = MerchantService::getDefaultShopId($this->ghs);
  49. if (empty($defaultShopId)) {
  50. util::fail('没有找到门店');
  51. }
  52. //计算运费
  53. $post['sendDistance'] = isset($post['sendDistance']) ? $post['sendDistance'] : 0;
  54. $sendCost = 0;
  55. //按距离计算运费并且客户要求送的
  56. if ($freightType == 0 && $needSend == 1) {
  57. $lat = $post['latitude'];//收货人纬度
  58. $lng = $post['longitude'];//收货人经度
  59. $respond = ExpressService::getUserDistance($lng, $lat, $defaultShopId, $this->ghsExtend);
  60. $sendCost = isset($respond['fee']) ? $respond['fee'] : 0;
  61. }
  62. $post['sendCost'] = $sendCost;
  63. $post['merchantId'] = $this->ghsId;
  64. $post['shopId'] = $defaultShopId;
  65. //计算总金额
  66. //$unitPrice = $goodsInfo['price'];
  67. $unitPrice = 1;
  68. $goodsPrice = $unitPrice * $goodsNum;
  69. $prePrice = stringUtil::calcAdd($sendCost, $goodsPrice);
  70. //非门店订单
  71. $store = 0;
  72. $post['store'] = $store;
  73. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  74. $sourceType = $this->isWx ? 0 : 1;
  75. if (httpUtil::isMiniProgram()) {
  76. $sourceType = 2;
  77. }
  78. $couponId = isset($post['couponId']) && !empty($post['couponId']) ? $post['couponId'] : 0;
  79. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  80. $actPrice = $discountData['price'];
  81. $post['discountType'] = $discountData['discountType'];
  82. $post['discountAmount'] = $discountData['discountAmount'];
  83. $now = time();
  84. $expireTime = $now + 1800;//订单30分钟后过期
  85. $post['deadline'] = $expireTime;
  86. $post['fromType'] = 1;//商城
  87. $post['prePrice'] = $prePrice;
  88. $post['actPrice'] = $actPrice;
  89. $order = OrderService::addOrder($post);
  90. $orderId = $order['id'];
  91. $orderSn = $order['orderSn'];
  92. $data = [
  93. 'orderId' => $orderId,
  94. 'goodsId' => $goodsId,
  95. 'userId' => $this->adminId,
  96. 'merchantId' => $this->ghsId,
  97. 'title' => '苏醒',
  98. 'cover' => isset($goodsInfo['shortImgList']) && !empty($goodsInfo['shortImgList']) ? current($goodsInfo['shortImgList']) : '',
  99. 'unitPrice' => $unitPrice,
  100. 'num' => $goodsNum,
  101. 'goodsStyleName' => isset($goodsInfo['goodsStyleList'][$goodsStyleId]['title']) ? $goodsInfo['goodsStyleList'][$goodsStyleId]['title'] : '',
  102. 'goodsStyleId' => $goodsStyleId,
  103. 'createTime' => date("Y-m-d H:i:s"),
  104. ];
  105. OrderGoodsService::add($data);//创建订单商品列表
  106. util::success(['orderSn' => $orderSn, 'totalPrice' => $actPrice, 'couponId' => $couponId]);
  107. }
  108. //下单要用到的相关信息 shish 2019.12.6
  109. public function actionOrderRelate()
  110. {
  111. $regionTree = RegionService::tree();
  112. $shop = ShopService::getDefaultShop($this->ghs);
  113. $freight = MerchantExtendService::getFreight($this->ghsExtend);
  114. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  115. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'txMapKey' => $mapKey, 'merchant' => $this->ghs];
  116. util::success($out);
  117. }
  118. //余额支付 shish 2019.12.6
  119. public function actionBalancePay()
  120. {
  121. $post = Yii::$app->request->post();
  122. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  123. $payPassword = isset($post['payPassword']) ? $post['payPassword'] : 0;
  124. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  125. //验证优惠券是否还有效
  126. if (!empty($couponId)) {
  127. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  128. }
  129. $order = OrderService::getByOrderSn($orderSn);
  130. $userId = $this->adminId;
  131. $user = UserService::getUserInfo($userId, false);
  132. //验证支付密码是否正确
  133. UserService::validPayPassword($payPassword, $user);
  134. //支付前验证订单有效性
  135. OrderService::checkBeforePay($order, $this->adminId);
  136. $typeList = configDict::getConfig('capitalType');
  137. $capitalType = $typeList['xhOrder']['id'];
  138. $totalFee = $order['prePrice'];
  139. $sourceType = 0;
  140. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  141. $actPrice = $discountData['price'];
  142. $callbackParams = [];
  143. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  144. $balance = isset($respond['balance']) ? $respond['balance'] : 0;
  145. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  146. }
  147. //获取商城下单要用的微信支付和小程序支付参数 shish 2019.21.3
  148. public function actionWxPay()
  149. {
  150. ini_set('date.timezone', 'Asia/Shanghai');
  151. $post = Yii::$app->request->post();
  152. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  153. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  154. $order = OrderService::getByOrderSn($orderSn);
  155. $orderId = $order['id'];
  156. //验证优惠券是否还有效
  157. if (!empty($couponId)) {
  158. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  159. }
  160. //支付前验证订单有效性
  161. OrderService::checkBeforePay($order, $this->adminId);
  162. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  163. $totalFee = $order['actPrice'];
  164. //小程序使用miniOpenId
  165. if (httpUtil::isMiniProgram()) {
  166. $openId = $this->admin['miniOpenId'];
  167. } else {
  168. $openId = $this->admin['openId'];
  169. }
  170. $typeList = configDict::getConfig('capitalType');
  171. $capitalType = $typeList['xhOrder']['id'];
  172. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  173. $wxPayType = 0;
  174. if (httpUtil::isMiniProgram()) {
  175. $wxPayType = 1;
  176. }
  177. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  178. //订单30分钟后过期
  179. $now = time();
  180. $expireTime = $now + 1800;
  181. $wx = Yii::getAlias("@vendor/weixin");
  182. require_once($wx . '/lib/WxPay.Api.php');
  183. require_once($wx . '/example/WxPay.JsApiPay.php');
  184. $input = new \WxPayUnifiedOrder();
  185. $input->SetBody($name);
  186. $input->SetOut_trade_no($orderSn);
  187. $input->SetTotal_fee($totalFee * 100);
  188. $input->SetTime_start(date("YmdHis", $now));
  189. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  190. $input->SetTime_expire(date("YmdHis", $expireTime));
  191. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  192. $input->SetTrade_type("JSAPI");
  193. //花卉宝代为申请的微信支付
  194. $merchantExtend = $this->ghsExtend;
  195. if ($merchantExtend['wxPayApply'] == 1) {
  196. $input->SetSub_openid($openId);
  197. } else {
  198. $input->SetOpenid($openId);
  199. }
  200. //小程序使用miniAppId
  201. if (httpUtil::isMiniProgram()) {
  202. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  203. }
  204. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  205. $tools = new \JsApiPay();
  206. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  207. $newParams = json_decode($jsApiParameters, true);
  208. //已请求微信不能修改价格
  209. $updateData = [];
  210. $updateData['modPrice'] = 0;
  211. if (empty($order['deadline'])) {
  212. $updateData['deadline'] = $expireTime;
  213. }
  214. OrderService::updateById($orderId, $updateData);
  215. util::success($newParams);
  216. }
  217. //快捷付款订单
  218. public function actionFastPay()
  219. {
  220. ini_set('date.timezone', 'Asia/Shanghai');
  221. $post = Yii::$app->request->post();
  222. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  223. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->ghs);
  224. //验证门店是否有效
  225. $shopInfo = ShopService::getById($shopId);
  226. ShopService::valid($shopInfo, $this->ghsId);
  227. $post['shopId'] = $shopId;
  228. //默认门店订单
  229. $store = isset($post['store']) ? $post['store'] : 1;
  230. $post['store'] = $store;
  231. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  232. $sourceType = $this->isWx ? 0 : 1;
  233. if (httpUtil::isMiniProgram()) {
  234. $sourceType = 2;
  235. }
  236. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  237. //兼容旧系统sourceType=3表示朋友圈来源
  238. $fromType = $sourceType == 3 ? 2 : 0;
  239. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  240. $post['userId'] = $this->adminId;
  241. $user = $this->admin;
  242. $post['bookName'] = isset($user['userName']) ? $user['userName'] : '';
  243. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  244. $bookMobile = empty($bookMobile) && isset($user['mobile']) && !empty($user['mobile']) ? $user['mobile'] : $bookMobile;
  245. $post['bookMobile'] = $bookMobile;
  246. $prePrice = round($post['prePrice'], 2);
  247. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  248. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  249. $actPrice = $discountData['price'];
  250. $post['discountType'] = $discountData['discountType'];
  251. $post['discountAmount'] = $discountData['discountAmount'];
  252. $post['actPrice'] = $actPrice;
  253. $post['payStyle'] = 0;
  254. $post['merchantId'] = $this->ghsId;
  255. $now = time();
  256. $expireTime = $now + 300;//订单5分钟后过期
  257. $post['createTime'] = date("Y-m-d H:i:s", $now);
  258. $post['deadline'] = $expireTime;
  259. if ($actPrice <= 0) {
  260. util::fail('请填写正确的金额');
  261. }
  262. //微信支付订单提交不能修改价格
  263. $post['modPrice'] = $this->isWx ? 0 : 1;
  264. $post['sourceType'] = $sourceType;
  265. $post['goodsNum'] = 1;
  266. $post['fromType'] = $fromType;
  267. $order = OrderService::addOrder($post);
  268. $orderId = $order['id'];
  269. $orderSn = $order['orderSn'];
  270. $merchantId = $this->ghsId;
  271. if ($payWay == 0) {
  272. $orderId = $order['id'];
  273. $name = '购买商品';
  274. $totalFee = $actPrice;
  275. $user = UserService::getById($this->adminId);
  276. $openId = isset($user['openId']) ? $user['openId'] : 0;
  277. if (httpUtil::isMiniProgram()) {
  278. //小程序使用miniOpenId
  279. $openId = $user['miniOpenId'];
  280. }
  281. if (empty($openId)) {
  282. util::fail('没有找到客户的openId');
  283. }
  284. $typeList = configDict::getConfig('capitalType');
  285. $capitalType = $typeList['xhOrder']['id'];
  286. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  287. $wxPayType = 0;
  288. if (httpUtil::isMiniProgram()) {
  289. $wxPayType = 1;
  290. }
  291. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  292. $wx = Yii::getAlias("@vendor/weixin");
  293. require_once($wx . '/lib/WxPay.Api.php');
  294. require_once($wx . '/example/WxPay.JsApiPay.php');
  295. $input = new \WxPayUnifiedOrder();
  296. $input->SetBody($name);
  297. $input->SetOut_trade_no($orderSn);
  298. $input->SetTotal_fee($totalFee * 100);
  299. $input->SetTime_start(date("YmdHis", $now));
  300. $input->SetAttach($attach);
  301. //设置订单有效期5分钟
  302. $input->SetTime_expire(date("YmdHis", $expireTime));
  303. $input->SetNotify_url(Yii::$app->params['mallHost'] . '/notice/wx-callback/');
  304. $input->SetTrade_type("JSAPI");
  305. //花卉宝代为申请的微信支付
  306. $merchantExtend = $this->ghsExtend;
  307. if ($merchantExtend['wxPayApply'] == 1) {
  308. $input->SetSub_openid($openId);
  309. } else {
  310. $input->SetOpenid($openId);
  311. }
  312. //小程序使用miniAppId
  313. if (httpUtil::isMiniProgram()) {
  314. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  315. }
  316. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  317. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  318. $tools = new \JsApiPay();
  319. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  320. $newParams = json_decode($jsApiParameters, true);
  321. $newParams['orderId'] = $orderId;
  322. util::success($newParams);
  323. } elseif ($payWay == 1) {
  324. $extend = MerchantExtendService::getByMerchantId($merchantId);
  325. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  326. util::fail('支付宝付款即将开通...');
  327. }
  328. $config = [
  329. //应用ID,您的APPID。
  330. 'app_id' => $extend['alipayPId'],
  331. //商户私钥,您的原始格式RSA私钥
  332. 'merchant_private_key' => $extend['alipayKey'],
  333. //异步通知地址
  334. 'notify_url' => Yii::$app->params['mallHost'] . "/notice/alipay-callback",
  335. //同步跳转
  336. 'return_url' => "",
  337. //编码格式
  338. 'charset' => "UTF-8",
  339. //签名方式
  340. 'sign_type' => "RSA2",
  341. //支付宝网关
  342. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  343. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  344. 'alipay_public_key' => $extend['alipayPublicKey'],
  345. ];
  346. Yii::info(json_encode($config) . ' aplipay config');
  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 = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  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->adminId, 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. }