PayNotifyController.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Models\PaymentLogModel;
  4. use App\Models\User;
  5. use App\Models\UserVipLogModel;
  6. use App\Services\PayService;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use PHPUnit\Util\Exception;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Yansongda\Pay\Pay;
  12. class PayNotifyController extends Controller
  13. {
  14. /**
  15. * 微信支付回调
  16. */
  17. public function wx_notify(){
  18. Log::info(Request::createFromGlobals()->getContent());
  19. $wxpay = Pay::wechat(PayService::wx_config());
  20. DB::beginTransaction();
  21. try{
  22. $data = $wxpay->verify();
  23. Log::info($data);
  24. $order_no = $data->out_trade_no;
  25. $this->order_do_sth($order_no);
  26. DB::commit();
  27. } catch (\Exception $e) {
  28. DB::rollBack();
  29. Log::info($e->getMessage());
  30. }
  31. return $wxpay->success();
  32. }
  33. /**
  34. * 支付宝支付回调
  35. */
  36. public function ali_notify(){
  37. $alipay = Pay::alipay(PayService::ali_config());
  38. DB::beginTransaction();
  39. try{
  40. $data = $alipay->verify();
  41. Log::info($data);
  42. $order_no = $data->out_trade_no;
  43. $this->order_do_sth($order_no);
  44. DB::commit();
  45. } catch (\Exception $e) {
  46. DB::rollBack();
  47. Log::info($e->getMessage());
  48. }
  49. return $alipay->success();
  50. }
  51. /**
  52. * 支付回调业务处理
  53. */
  54. public function order_do_sth($order_no){
  55. $order = PaymentLogModel::query()->where(['order_no'=>$order_no])->first();
  56. if(!$order){
  57. throw new Exception("订单不存在");
  58. }
  59. if($order['status']==1){
  60. return true;
  61. }
  62. //修改订单状态
  63. $order->status = 1;
  64. $order->save();
  65. $vip_info = json_decode($order->content,true);
  66. //修改用户vip状态
  67. $user = User::query()->where(['id'=>$order->user_id])->first();
  68. if($user->is_vip==0){
  69. $user->is_vip = 1;
  70. $user->save();
  71. }
  72. //变更vip记录
  73. $user_vip_log = UserVipLogModel::query()->where(['user_id'=>$order->user_id])->first();
  74. if(!$user_vip_log){
  75. UserVipLogModel::query()->create([
  76. 'user_id'=>$order->user_id,
  77. 'status'=>1,
  78. 'day'=>$vip_info['day'],
  79. 'end_day'=> date("Y-m-d H:i:s",strtotime("+".$vip_info['day']." day")),
  80. ]);
  81. }elseif($user_vip_log->status==1){
  82. $user_vip_log->end_day = date("Y-m-d H:i:s",strtotime($user_vip_log->end_day."+".$vip_info['day']." day"));
  83. $user_vip_log->save();
  84. }elseif ($user_vip_log->status==0){
  85. $user_vip_log->end_day = date("Y-m-d H:i:s",strtotime("+".$vip_info['day']." day"));
  86. $user_vip_log->status = 1;
  87. $user_vip_log->save();
  88. }
  89. return true;
  90. }
  91. }