PaymentController.php 11 KB

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