PayNotifyController.php 2.8 KB

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