PaymentController.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\AlipaySubmit;
  4. use App\Components\Callback;
  5. use App\Components\Helpers;
  6. use App\Http\Models\Coupon;
  7. use App\Http\Models\Goods;
  8. use App\Http\Models\Order;
  9. use App\Http\Models\Payment;
  10. use App\Http\Models\PaymentCallback;
  11. use App\Http\Models\User;
  12. use Auth;
  13. use DB;
  14. use Exception;
  15. use Illuminate\Http\Request;
  16. use Log;
  17. use Payment\Client\Charge;
  18. use Response;
  19. use Validator;
  20. /**
  21. * 支付控制器
  22. *
  23. * Class PaymentController
  24. *
  25. * @package App\Http\Controllers
  26. */
  27. class PaymentController extends Controller
  28. {
  29. use Callback;
  30. // 创建支付订单
  31. public function create(Request $request)
  32. {
  33. $goods_id = $request->input('goods_id');
  34. $coupon_sn = $request->input('coupon_sn');
  35. $pay_type = $request->input('pay_type');
  36. $goods = Goods::query()->where('status', 1)->where('id', $goods_id)->first();
  37. if(!$goods){
  38. return Response::json(['status' => 'fail', 'data' => '', 'message' => '订单创建失败:商品或服务已下架']);
  39. }
  40. // 是否有生效的套餐
  41. $activePlan = Order::uid()->with(['goods'])->whereHas('goods', function($q){ $q->where('type', 2); })->where('status', 2)->where('is_expire', 0)->doesntExist();
  42. //无生效套餐,禁止购买加油包
  43. if($goods->type == 1 && $activePlan){
  44. return Response::json(['status' => 'fail', 'data' => '', 'message' => '购买加油包前,请先购买套餐']);
  45. }
  46. //非余额付款下,检查对应的在线支付是否开启
  47. if($pay_type != 1){
  48. // 判断是否开启在线支付
  49. if(!self::$systemConfig['is_alipay'] && !self::$systemConfig['is_f2fpay']){
  50. return Response::json(['status' => 'fail', 'data' => '', 'message' => '订单创建失败:系统并未开启在线支付功能']);
  51. }
  52. // 判断是否存在同个商品的未支付订单
  53. $existsOrder = Order::uid()->where('status', 0)->where('goods_id', $goods_id)->exists();
  54. if($existsOrder){
  55. return Response::json(['status' => 'fail', 'data' => '', 'message' => '订单创建失败:尚有未支付的订单,请先去支付']);
  56. }
  57. }
  58. // 单个商品限购
  59. if($goods->limit_num){
  60. $count = Order::uid()->where('status', '>=', 0)->where('goods_id', $goods_id)->count();
  61. if($count >= $goods->limit_num){
  62. return Response::json(['status' => 'fail', 'data' => '', 'message' => '此商品/服务限购'.$goods->limit_num.'次,您已购买'.$count.'次']);
  63. }
  64. }
  65. // 使用优惠券
  66. if($coupon_sn){
  67. $coupon = Coupon::query()->where('status', 0)->whereIn('type', [1, 2])->where('sn', $coupon_sn)->first();
  68. if(!$coupon){
  69. return Response::json(['status' => 'fail', 'data' => '', 'message' => '订单创建失败:优惠券不存在']);
  70. }
  71. // 计算实际应支付总价
  72. $amount = $coupon->type == 2? $goods->price*$coupon->discount/10 : $goods->price-$coupon->amount;
  73. $amount = $amount > 0? round($amount, 2) : 0; // 四舍五入保留2位小数,避免无法正常创建订单
  74. }else{
  75. $amount = $goods->price;
  76. }
  77. // 价格异常判断
  78. if($amount < 0){
  79. return Response::json(['status' => 'fail', 'data' => '', 'message' => '订单创建失败:订单总价异常']);
  80. }elseif($amount == 0 && $pay_type != 1){
  81. return Response::json(['status' => 'fail', 'data' => '', 'message' => '订单创建失败:订单总价为0,无需使用在线支付']);
  82. }
  83. // 验证账号余额是否充足
  84. if($pay_type == 1 && Auth::user()->balance < $amount){
  85. return Response::json(['status' => 'fail', 'data' => '', 'message' => '您的余额不足,请先充值']);
  86. }
  87. DB::beginTransaction();
  88. try{
  89. $orderSn = date('ymdHis').mt_rand(100000, 999999);
  90. // 生成订单
  91. $order = new Order();
  92. $order->order_sn = $orderSn;
  93. $order->user_id = Auth::user()->id;
  94. $order->goods_id = $goods_id;
  95. $order->coupon_id = !empty($coupon)? $coupon->id : 0;
  96. $order->origin_amount = $goods->price;
  97. $order->amount = $amount;
  98. $order->expire_at = date("Y-m-d H:i:s", strtotime("+".$goods->days." days"));
  99. $order->is_expire = 0;
  100. $order->pay_way = $pay_type;
  101. $order->status = 0;
  102. $order->save();
  103. // 生成支付单
  104. if($pay_type == 1){
  105. // 扣余额
  106. User::query()->where('id', Auth::user()->id)->decrement('balance', $amount*100);
  107. // 记录余额操作日志
  108. $this->addUserBalanceLog(Auth::user()->id, $order->oid, Auth::user()->balance, Auth::user()->balance-$amount, -1*$amount, '购买商品:'.$goods->name);
  109. $data = [];
  110. $data['out_trade_no'] = $orderSn;
  111. $this->tradePaid($data, 1);
  112. }else{
  113. if(self::$systemConfig['is_alipay'] && $pay_type == 4){
  114. $pay_way = 2;
  115. $parameter = [
  116. "service" => "create_forex_trade", // WAP:create_forex_trade_wap ,即时到帐:create_forex_trade
  117. "partner" => self::$systemConfig['alipay_partner'],
  118. "notify_url" => self::$systemConfig['website_url']."/api/alipay", // 异步回调接口
  119. "return_url" => self::$systemConfig['website_url'],
  120. "out_trade_no" => $orderSn, // 订单号
  121. "subject" => "Package", // 订单名称
  122. //"total_fee" => $amount, // 金额
  123. "rmb_fee" => $amount, // 使用RMB标价,不再使用总金额
  124. "body" => "", // 商品描述,可为空
  125. "currency" => self::$systemConfig['alipay_currency'], // 结算币种
  126. "product_code" => "NEW_OVERSEAS_SELLER",
  127. "_input_charset" => "utf-8"
  128. ];
  129. // 建立请求
  130. $alipaySubmit = new AlipaySubmit(self::$systemConfig['alipay_sign_type'], self::$systemConfig['alipay_partner'], self::$systemConfig['alipay_key'], self::$systemConfig['alipay_private_key']);
  131. $result = $alipaySubmit->buildRequestForm($parameter, "post", "确认");
  132. }elseif(self::$systemConfig['is_f2fpay'] && $pay_type == 5){
  133. $pay_way = 2;
  134. // TODO:goods表里增加一个字段用于自定义商品付款时展示的商品名称,
  135. // TODO:这里增加一个随机商品列表,根据goods的价格随机取值
  136. $result = Charge::run("ali_qr", [
  137. 'use_sandbox' => FALSE,
  138. "partner" => self::$systemConfig['f2fpay_app_id'],
  139. 'app_id' => self::$systemConfig['f2fpay_app_id'],
  140. 'sign_type' => 'RSA2',
  141. 'ali_public_key' => self::$systemConfig['f2fpay_public_key'],
  142. 'rsa_private_key' => self::$systemConfig['f2fpay_private_key'],
  143. 'notify_url' => self::$systemConfig['website_url']."/api/f2fpay", // 异步回调接口
  144. 'return_url' => self::$systemConfig['website_url'],
  145. 'return_raw' => FALSE
  146. ],
  147. [
  148. 'body' => '',
  149. 'subject' => self::$systemConfig['f2fpay_subject_name'],
  150. 'order_no' => $orderSn,
  151. 'amount' => $amount,
  152. ]);
  153. }else{
  154. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:未知支付类型']);
  155. }
  156. $sn = makeRandStr(12);
  157. $payment = new Payment();
  158. $payment->sn = $sn;
  159. $payment->user_id = Auth::user()->id;
  160. $payment->oid = $order->oid;
  161. $payment->order_sn = $orderSn;
  162. $payment->pay_way = $pay_way? : 1;
  163. $payment->amount = $amount;
  164. if(self::$systemConfig['is_alipay'] && $pay_type == 4){
  165. $payment->qr_code = $result;
  166. }elseif(self::$systemConfig['is_f2fpay'] && $pay_type == 5){
  167. $payment->qr_code = $result;
  168. $payment->qr_url = 'http://qr.topscan.com/api.php?text='.$result.'&bg=ffffff&fg=000000&pt=1c73bd&m=10&w=400&el=1&inpt=1eabfc&logo=https://t.alipayobjects.com/tfscom/T1Z5XfXdxmXXXXXXXX.png';
  169. $payment->qr_local_url = $payment->qr_url;
  170. }
  171. $payment->status = 0;
  172. $payment->save();
  173. }
  174. // 优惠券置为已使用
  175. if(!empty($coupon)){
  176. if($coupon->usage == 1){
  177. $coupon->status = 1;
  178. $coupon->save();
  179. }
  180. Helpers::addCouponLog($coupon->id, $goods_id, $order->oid, '订单支付使用');
  181. }
  182. DB::commit();
  183. if($pay_type == 1){
  184. return Response::json(['status' => 'success', 'data' => '', 'message' => '支付成功']);
  185. }elseif($pay_type == 4){ // Alipay返回支付信息
  186. return Response::json(['status' => 'success', 'data' => $result, 'message' => '创建订单成功,正在转到付款页面,请稍后']);
  187. }elseif($pay_type == 5){
  188. return Response::json(['status' => 'success', 'data' => $sn, 'message' => '创建订单成功,正在转到付款页面,请稍后']);
  189. }
  190. } catch(Exception $e){
  191. DB::rollBack();
  192. Log::error('创建支付订单失败:'.$e->getMessage());
  193. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建订单失败:'.$e->getMessage()]);
  194. }
  195. return Response::json(['status' => 'fail', 'data' => '', 'message' => '未知错误']);
  196. }
  197. // 支付单详情
  198. public function detail(Request $request, $sn)
  199. {
  200. $view['payment'] = Payment::uid()->with(['order', 'order.goods'])->where('sn', $sn)->firstOrFail();
  201. return Response::view('payment.detail', $view);
  202. }
  203. // 获取订单支付状态
  204. public function getStatus(Request $request)
  205. {
  206. $validator = Validator::make($request->all(), ['sn' => 'required|exists:payment,sn'], ['sn.required' => '请求失败:缺少sn', 'sn.exists' => '支付失败:支付单不存在']);
  207. if($validator->fails()){
  208. return Response::json(['status' => 'error', 'data' => '', 'message' => $validator->getMessageBag()->first()]);
  209. }
  210. $payment = Payment::uid()->where('sn', $request->sn)->first();
  211. if($payment->status > 0){
  212. return Response::json(['status' => 'success', 'data' => '', 'message' => '支付成功']);
  213. }elseif($payment->status < 0){
  214. return Response::json(['status' => 'error', 'data' => '', 'message' => '订单超时未支付,已自动关闭']);
  215. }else{
  216. return Response::json(['status' => 'fail', 'data' => '', 'message' => '等待支付']);
  217. }
  218. }
  219. // 回调日志
  220. public function callbackList(Request $request)
  221. {
  222. $status = $request->input('status', 0);
  223. $query = PaymentCallback::query();
  224. if(isset($status)){
  225. $query->where('status', $status);
  226. }
  227. $view['list'] = $query->orderBy('id', 'desc')->paginate(10)->appends($request->except('page'));
  228. return Response::view('payment.callbackList', $view);
  229. }
  230. }