Checkout.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\index\controller;
  13. use app\common\model\User as UserAlias;
  14. use app\index\model\Order;
  15. use app\index\model\Order as OrderModel;
  16. use app\index\model\ShareKey;
  17. use app\index\model\User as UserModel;
  18. use app\index\service\order\PaySuccess;
  19. use app\index\service\User;
  20. use app\index\service\User as UserService;
  21. use app\index\service\Cart as CartService;
  22. use app\index\service\order\Checkout as CheckoutService;
  23. use app\index\validate\order\Checkout as CheckoutValidate;
  24. use app\common\enum\order\PayType as OrderPayTypeEnum;
  25. use app\common\library\paypal\PayPal;
  26. use cores\exception\BaseException;
  27. use think\facade\Cache;
  28. use think\facade\Session;
  29. use think\response\Json;
  30. /**
  31. * 订单结算控制器
  32. * Class Checkout
  33. * @package app\api\controller
  34. */
  35. class Checkout extends Controller
  36. {
  37. // 结算台验证器
  38. /* @var CheckoutValidate $validate */
  39. private $validate;
  40. /**
  41. * 结算台订单信息
  42. * @param string $mode
  43. * @return Json
  44. * @throws BaseException
  45. * @throws \think\db\exception\DataNotFoundException
  46. * @throws \think\db\exception\DbException
  47. * @throws \think\db\exception\ModelNotFoundException
  48. */
  49. public function order(string $mode = 'buyNow'): Json
  50. {
  51. if ($mode === 'buyNow') {
  52. return $this->buyNow();
  53. } elseif ($mode === 'cart') {
  54. return $this->cart();
  55. }
  56. return $this->renderError('结算模式不合法');
  57. }
  58. /**
  59. * 订单提交
  60. * @param string $mode
  61. * @return Json
  62. * @throws BaseException
  63. * @throws \think\db\exception\DataNotFoundException
  64. * @throws \think\db\exception\DbException
  65. * @throws \think\db\exception\ModelNotFoundException
  66. */
  67. public function submit(string $mode = 'buyNow'): Json
  68. {
  69. $userId = Session::get('user_id');
  70. if (empty($userId)) {
  71. return $this->renderJson(config('status.not_logged'), 'Log in please!');
  72. }
  73. return $this->order($mode);
  74. }
  75. /**
  76. * 订单确认-立即购买
  77. * @return Json
  78. * @throws BaseException
  79. * @throws \think\db\exception\DataNotFoundException
  80. * @throws \think\db\exception\DbException
  81. * @throws \think\db\exception\ModelNotFoundException
  82. */
  83. private function buyNow(): Json
  84. {
  85. // 实例化结算台服务
  86. $Checkout = new CheckoutService;
  87. // 订单结算api参数
  88. $params = $Checkout->setParam($this->getParam([
  89. 'goodsId' => 0,
  90. 'goodsSkuId' => '',
  91. 'goodsNum' => 0,
  92. ]));
  93. // 表单验证
  94. if (!$this->getValidate()->scene('buyNow')->check($params)) {
  95. return $this->renderError($this->getValidate()->getError(), ['isCreated' => false]);
  96. }
  97. // 立即购买:获取订单商品列表
  98. $model = new OrderModel;
  99. $goodsList = $model->getOrderGoodsListByNow(
  100. (int)$params['goodsId'],
  101. (string)$params['goodsSkuId'],
  102. (int)$params['goodsNum']
  103. );
  104. // 获取订单确认信息
  105. $orderInfo = $Checkout->onCheckout($goodsList);
  106. if ($this->request->isGet()) {
  107. return $this->renderSuccess([
  108. 'order' => $orderInfo,
  109. 'personal' => $Checkout->getPersonal(),
  110. 'setting' => $Checkout->getSetting(),
  111. ]);
  112. }
  113. // 验证订单是否存在错误
  114. if ($Checkout->hasError()) {
  115. return $this->renderError($Checkout->getError(), ['is_created' => false]);
  116. }
  117. // 创建订单
  118. if (!$Checkout->createOrder($orderInfo)) {
  119. return $this->renderError($Checkout->getError() ?: '订单创建失败', ['is_created' => false]);
  120. }
  121. // 构建微信支付请求
  122. $payment = $model->onOrderPayment($Checkout->model, $params['payType']);
  123. // 返回结算信息
  124. return $this->renderSuccess([
  125. 'orderId' => $Checkout->model['order_id'], // 订单id
  126. 'payType' => $params['payType'], // 支付方式
  127. 'payment' => $payment // 微信支付参数
  128. ]);
  129. }
  130. /**
  131. * 订单确认-购物车结算
  132. * @return Json
  133. * @throws BaseException
  134. * @throws \think\db\exception\DataNotFoundException
  135. * @throws \think\db\exception\DbException
  136. * @throws \think\db\exception\ModelNotFoundException
  137. */
  138. private function cart(): Json
  139. {
  140. // 实例化结算台服务
  141. $Checkout = new CheckoutService;
  142. // 订单结算api参数
  143. $params = $Checkout->setParam($this->getParam());
  144. // 购物车ID集
  145. //$cartIds = $this->getCartIds();//不需要接口传过来
  146. $CartModel = new CartService;
  147. $cartIds = $CartModel->getCartIds();
  148. // 商品结算信息
  149. // 购物车商品列表
  150. $goodsList = $CartModel->getOrderGoodsList($cartIds);
  151. if (empty($goodsList)) {
  152. return $this->renderError('Please add items to your shopping cart first');
  153. }
  154. // 获取订单结算信息
  155. $orderInfo = $Checkout->onCheckout($goodsList);
  156. if ($this->request->isGet()) {
  157. return $this->renderSuccess([
  158. 'order' => $orderInfo,
  159. 'personal' => $Checkout->getPersonal(),
  160. 'setting' => $Checkout->getSetting(),
  161. ]);
  162. }
  163. $userInfo = User::getCurrentLoginUser();
  164. $points = $userInfo['points'];
  165. if ($params['payType'] == OrderPayTypeEnum::POINTS) {
  166. $payPoints = intval(bcmul(strval($orderInfo['orderPayPrice']), strval(UserAlias::POINTS_FOR_ONE_DOLLAR), 0));//订单所需积分
  167. if (intval($points) < $payPoints) {
  168. return $this->renderError('Not enough points');
  169. }
  170. }
  171. // 验证订单是否存在错误
  172. if ($Checkout->hasError()) {
  173. return $this->renderError($Checkout->getError(), ['is_created' => false]);
  174. }
  175. // 创建订单
  176. if (!$Checkout->createOrder($orderInfo)) {
  177. return $this->renderError($Checkout->getError() ?: 'Order creation failed, please try again later');
  178. }
  179. // 移出购物车中已下单的商品
  180. $CartModel->clear($cartIds);
  181. // 构建微信支付请求
  182. $payment = $Checkout->onOrderPayment();
  183. if ($params['payType'] == OrderPayTypeEnum::POINTS) {
  184. if (!$payment['flag']) {
  185. return $this->renderError($payment['message'] ?? 'Redemption failed, please try again later');
  186. }
  187. }
  188. // 返回状态,如果是paypal支付,需要给用户跳转页面之外,还需要轮训查询订单的支付情况,如果支付成功,则弹窗提示,超过一分钟的话,提示支付超时,请重试
  189. return $this->renderSuccess([
  190. 'orderId' => $Checkout->model['order_id'], // 订单id
  191. 'payType' => $params['payType'], // 支付方式
  192. 'payment' => $payment // 微信支付参数
  193. ]);
  194. }
  195. /**
  196. * @return \think\response\View
  197. */
  198. public function payPayExecutePay($orderNo = '', $token = '')
  199. {
  200. if (empty($orderNo) || empty($token)) {
  201. //return view('payError', ['notice' => lang('login success')]);
  202. return view('payError', ['notice' => 'Payment failed']);
  203. }
  204. $oriToken = Cache::get(PayPal::PRE_STR . $orderNo);
  205. if ($token != $oriToken) {
  206. return view('payError', ['notice' => 'Payment failed']);
  207. }
  208. $paymentId = $this->request->param('paymentId');
  209. $confs = config('paypal');
  210. if (is_debug()) {
  211. $conf = $confs['sandbox'];
  212. } else {
  213. $conf = $confs['live'];
  214. }
  215. $pp = new PayPal($conf);
  216. $flag = $pp->executePayment($paymentId);
  217. if ($flag) {
  218. $orderModel = new PaySuccess($orderNo);
  219. $status = $orderModel->onPaySuccess(OrderPayTypeEnum::PAYPAL, ['transaction_id' => $paymentId]);
  220. if (!$status) {
  221. return view('payError', ['notice' => 'Payment failed']);
  222. }
  223. Cache::delete(PayPal::PRE_STR . $orderNo);
  224. }
  225. //todo 等会测试
  226. $order = Order::detail(['order_no' => $orderNo]);
  227. //如果有分享人,给分享人送积分
  228. if (isset($order['user_id'])) {
  229. $key = Cache::get(UserModel::SHARE_PREFIX . $order['user_id']);
  230. if (!empty($key)) {
  231. $dbKey = ShareKey::getShareKey($key);
  232. //没使用过的key才发放积分
  233. if (!empty($dbKey) && $dbKey['is_delete'] == 0) {
  234. $fromUserId = decrypt($key);
  235. if ($fromUserId && $fromUserId != $order['user_id']) {
  236. $describe = "Giveaway after sharing";
  237. $payPoints = intval(bcmul($order['pay_price'], strval(UserAlias::POINTS_FOR_SHARE), 0));
  238. UserModel::setIncPoints(intval($fromUserId), $payPoints, $describe);
  239. Cache::delete(UserModel::SHARE_PREFIX . $order['user_id']);
  240. ShareKey::delKey($key);
  241. }
  242. }
  243. } else {
  244. //自己购买获得积分
  245. $describe = "Purchase goods to earn points.";
  246. UserModel::setIncPoints(intval($order['user_id']), UserAlias::POINTS_FOR_BUY, $describe);
  247. }
  248. }
  249. return view('paySuccessful', ['notice' => 'Payment Successful']);
  250. }
  251. /**
  252. * 获取结算台验证器
  253. * @return CheckoutValidate
  254. */
  255. private function getValidate(): CheckoutValidate
  256. {
  257. if (!$this->validate) {
  258. $this->validate = new CheckoutValidate;
  259. }
  260. return $this->validate;
  261. }
  262. /**
  263. * 获取购物车ID集
  264. * @return false|string[]
  265. */
  266. private function getCartIds()
  267. {
  268. $cartIds = $this->request->param('cartIds');
  269. return explode(',', $cartIds);
  270. }
  271. /**
  272. * 订单结算提交的参数
  273. * @param array $define
  274. * @return array
  275. */
  276. private function getParam(array $define = []): array
  277. {
  278. return array_merge($define, $this->request->param());
  279. }
  280. public function goldTest()
  281. {
  282. return view('paySuccessful', ['notice' => 'Payment Successful']);
  283. }
  284. }