PaymentController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\AlipaySubmit;
  4. use App\Components\Helpers;
  5. use App\Components\Yzy;
  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 Auth;
  12. use DB;
  13. use Illuminate\Http\Request;
  14. use Log;
  15. use Payment\Client\Charge;
  16. use Response;
  17. use Validator;
  18. /**
  19. * 支付控制器
  20. *
  21. * Class PaymentController
  22. *
  23. * @package App\Http\Controllers
  24. */
  25. class PaymentController extends Controller
  26. {
  27. protected static $systemConfig;
  28. function __construct()
  29. {
  30. self::$systemConfig = Helpers::systemConfig();
  31. }
  32. // 创建支付单
  33. public function create(Request $request)
  34. {
  35. $goods_id = intval($request->get('goods_id'));
  36. $coupon_sn = $request->get('coupon_sn');
  37. $goods = Goods::query()->where('status', 1)->where('id', $goods_id)->first();
  38. if (!$goods) {
  39. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:商品或服务已下架']);
  40. }
  41. // 判断是否开启有赞云支付
  42. if (!self::$systemConfig['is_youzan'] && !self::$systemConfig['is_alipay'] && !self::$systemConfig['is_f2fpay']) {
  43. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:系统并未开启在线支付功能']);
  44. }
  45. // 判断是否存在同个商品的未支付订单
  46. $existsOrder = Order::uid()->where('status', 0)->where('goods_id', $goods_id)->exists();
  47. if ($existsOrder) {
  48. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:尚有未支付的订单,请先去支付']);
  49. }
  50. // 限购控制
  51. $strategy = self::$systemConfig['goods_purchase_limit_strategy'];
  52. if ($strategy == 'all' || ($strategy == 'package' && $goods->type == 2) || ($strategy == 'free' && $goods->price == 0) || ($strategy == 'package&free' && ($goods->type == 2 || $goods->price == 0))) {
  53. $noneExpireOrderExist = Order::uid()->where('status', '>=', 0)->where('is_expire', 0)->where('goods_id', $goods_id)->exists();
  54. if ($noneExpireOrderExist) {
  55. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:商品不可重复购买']);
  56. }
  57. }
  58. // 单个商品限购
  59. if ($goods->is_limit == 1) {
  60. $noneExpireOrderExist = Order::uid()->where('status', '>=', 0)->where('goods_id', $goods_id)->exists();
  61. if ($noneExpireOrderExist) {
  62. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:此商品每人限购1次']);
  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) {
  81. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:订单总价为0,无需使用在线支付']);
  82. }
  83. // 验证账号是否存在有效期更长的套餐
  84. if ($goods->type == 2) {
  85. $existOrderList = Order::uid()
  86. ->with(['goods'])
  87. ->whereHas('goods', function ($q) {
  88. $q->where('type', 2);
  89. })
  90. ->where('is_expire', 0)
  91. ->where('status', 2)
  92. ->get();
  93. foreach ($existOrderList as $vo) {
  94. if ($vo->goods->days > $goods->days) {
  95. return Response::json(['status' => 'fail', 'data' => '', 'message' => '支付失败:您已存在有效期更长的套餐,只能购买流量包']);
  96. }
  97. }
  98. }
  99. DB::beginTransaction();
  100. try {
  101. $orderSn = date('ymdHis') . mt_rand(100000, 999999);
  102. $sn = makeRandStr(12);
  103. // 支付方式
  104. if (self::$systemConfig['is_youzan']) {
  105. $pay_way = 2;
  106. } elseif (self::$systemConfig['is_alipay']) {
  107. $pay_way = 4;
  108. } elseif (self::$systemConfig['is_f2fpay']) {
  109. $pay_way = 5;
  110. }
  111. // 生成订单
  112. $order = new Order();
  113. $order->order_sn = $orderSn;
  114. $order->user_id = Auth::user()->id;
  115. $order->goods_id = $goods_id;
  116. $order->coupon_id = !empty($coupon) ? $coupon->id : 0;
  117. $order->origin_amount = $goods->price;
  118. $order->amount = $amount;
  119. $order->expire_at = date("Y-m-d H:i:s", strtotime("+" . $goods->days . " days"));
  120. $order->is_expire = 0;
  121. $order->pay_way = $pay_way;
  122. $order->status = 0;
  123. $order->save();
  124. // 生成支付单
  125. if (self::$systemConfig['is_youzan']) {
  126. $yzy = new Yzy();
  127. $result = $yzy->createQrCode($goods->name, $amount * 100, $orderSn);
  128. if (isset($result['error_response'])) {
  129. Log::error('【有赞云】创建二维码失败:' . $result['error_response']['msg']);
  130. throw new \Exception($result['error_response']['msg']);
  131. }
  132. } elseif (self::$systemConfig['is_alipay']) {
  133. $parameter = [
  134. "service" => "create_forex_trade", // WAP:create_forex_trade_wap ,即时到帐:create_forex_trade
  135. "partner" => self::$systemConfig['alipay_partner'],
  136. "notify_url" => self::$systemConfig['website_url'] . "/api/alipay", // 异步回调接口
  137. "return_url" => self::$systemConfig['website_url'],
  138. "out_trade_no" => $orderSn, // 订单号
  139. "subject" => "Package", // 订单名称
  140. //"total_fee" => $amount, // 金额
  141. "rmb_fee" => $amount, // 使用RMB标价,不再使用总金额
  142. "body" => "", // 商品描述,可为空
  143. "currency" => self::$systemConfig['alipay_currency'], // 结算币种
  144. "product_code" => "NEW_OVERSEAS_SELLER",
  145. "_input_charset" => "utf-8"
  146. ];
  147. // 建立请求
  148. $alipaySubmit = new AlipaySubmit(self::$systemConfig['alipay_sign_type'], self::$systemConfig['alipay_partner'], self::$systemConfig['alipay_key'], self::$systemConfig['alipay_private_key']);
  149. $result = $alipaySubmit->buildRequestForm($parameter, "post", "确认");
  150. } elseif (self::$systemConfig['is_f2fpay']) {
  151. // TODO:goods表里增加一个字段用于自定义商品付款时展示的商品名称,
  152. // TODO:这里增加一个随机商品列表,根据goods的价格随机取值
  153. $result = Charge::run("ali_qr", [
  154. 'use_sandbox' => false,
  155. "partner" => self::$systemConfig['f2fpay_app_id'],
  156. 'app_id' => self::$systemConfig['f2fpay_app_id'],
  157. 'sign_type' => 'RSA2',
  158. 'ali_public_key' => self::$systemConfig['f2fpay_public_key'],
  159. 'rsa_private_key' => self::$systemConfig['f2fpay_private_key'],
  160. 'notify_url' => self::$systemConfig['website_url'] . "/api/f2fpay", // 异步回调接口
  161. 'return_url' => self::$systemConfig['website_url'],
  162. 'return_raw' => false
  163. ], [
  164. 'body' => '',
  165. 'subject' => self::$systemConfig['f2fpay_subject_name'],
  166. 'order_no' => $orderSn,
  167. 'amount' => $amount,
  168. ]);
  169. }
  170. $payment = new Payment();
  171. $payment->sn = $sn;
  172. $payment->user_id = Auth::user()->id;
  173. $payment->oid = $order->oid;
  174. $payment->order_sn = $orderSn;
  175. $payment->pay_way = 1;
  176. $payment->amount = $amount;
  177. if (self::$systemConfig['is_youzan']) {
  178. $payment->qr_id = $result['response']['qr_id'];
  179. $payment->qr_url = $result['response']['qr_url'];
  180. $payment->qr_code = $result['response']['qr_code'];
  181. $payment->qr_local_url = $this->base64ImageSaver($result['response']['qr_code']);
  182. } elseif (self::$systemConfig['is_alipay']) {
  183. $payment->qr_code = $result;
  184. } elseif (self::$systemConfig['is_f2fpay']) {
  185. $payment->qr_code = $result;
  186. $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';
  187. $payment->qr_local_url = $payment->qr_url;
  188. }
  189. $payment->status = 0;
  190. $payment->save();
  191. // 优惠券置为已使用
  192. if (!empty($coupon)) {
  193. if ($coupon->usage == 1) {
  194. $coupon->status = 1;
  195. $coupon->save();
  196. }
  197. Helpers::addCouponLog($coupon->id, $goods_id, $order->oid, '在线支付使用');
  198. }
  199. DB::commit();
  200. if (self::$systemConfig['is_alipay']) { // Alipay返回支付信息
  201. return Response::json(['status' => 'success', 'data' => $result, 'message' => '创建订单成功,正在转到付款页面,请稍后']);
  202. } else {
  203. return Response::json(['status' => 'success', 'data' => $sn, 'message' => '创建订单成功,正在转到付款页面,请稍后']);
  204. }
  205. } catch (\Exception $e) {
  206. DB::rollBack();
  207. Log::error('创建支付订单失败:' . $e->getMessage());
  208. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建订单失败:' . $e->getMessage()]);
  209. }
  210. }
  211. // 支付单详情
  212. public function detail(Request $request, $sn)
  213. {
  214. $view['payment'] = Payment::uid()->with(['order', 'order.goods'])->where('sn', $sn)->firstOrFail();
  215. return Response::view('payment.detail', $view);
  216. }
  217. // 获取订单支付状态
  218. public function getStatus(Request $request)
  219. {
  220. $validator = Validator::make($request->all(), [
  221. 'sn' => 'required|exists:payment,sn'
  222. ], [
  223. 'sn.required' => '请求失败:缺少sn',
  224. 'sn.exists' => '支付失败:支付单不存在'
  225. ]);
  226. if ($validator->fails()) {
  227. return Response::json(['status' => 'error', 'data' => '', 'message' => $validator->getMessageBag()->first()]);
  228. }
  229. $payment = Payment::uid()->where('sn', $request->sn)->first();
  230. if ($payment->status > 0) {
  231. return Response::json(['status' => 'success', 'data' => '', 'message' => '支付成功']);
  232. } elseif ($payment->status < 0) {
  233. return Response::json(['status' => 'error', 'data' => '', 'message' => '订单超时未支付,已自动关闭']);
  234. } else {
  235. return Response::json(['status' => 'fail', 'data' => '', 'message' => '等待支付']);
  236. }
  237. }
  238. // 回调日志
  239. public function callbackList(Request $request)
  240. {
  241. $status = $request->get('status', 0);
  242. $query = PaymentCallback::query();
  243. if ($status) {
  244. $query->where('status', $status);
  245. }
  246. $view['list'] = $query->orderBy('id', 'desc')->paginate(10);
  247. return Response::view('payment.callbackList', $view);
  248. }
  249. }