PaymentController.php 13 KB

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