PayCallbackController.php 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zilongs
  5. * Date: 20-10-2
  6. * Time: 下午8:27
  7. */
  8. namespace App\Http\Controllers\Api\V1;
  9. use App\Http\Controllers\Controller;
  10. use App\Models\Docter;
  11. use App\Models\Order;
  12. use App\Models\Payment;
  13. use DB;
  14. use EasyWeChat\Factory;
  15. class PayCallbackController extends Controller
  16. {
  17. public function wechatPayNotify()
  18. {
  19. $app = Factory::payment(config('config.wechat_pay'));
  20. $response = $app->handlePaidNotify(function($message, $fail){
  21. // 使用通知里的 "交易单号" 去自己的数据库找到订单
  22. $payment = Payment::where('trade_sn', $message['out_trade_no'])->first();
  23. // 如果订单不存在 或者 订单已经支付过了
  24. if (empty($payment) || $payment['status'] != 1) {
  25. return true; // 告诉微信,我已经处理完了或者订单没找到,别再通知我了
  26. }
  27. //使用通知里的 "微信支付订单号" 去自己的数据库找是否已经存在
  28. if(Payment::where('online_sn', $message['transaction_id'])->exists()){
  29. return true; // 告诉微信,我已经处理过这单了,别再通知我了
  30. }
  31. //建议在这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付
  32. // return_code 表示通信状态,不代表支付状态
  33. if ($message['return_code'] === 'SUCCESS') {
  34. // 用户是否支付成功
  35. if ($message['result_code'] === 'SUCCESS') {
  36. // 启动事务
  37. DB::beginTransaction();
  38. try {
  39. //更新payment
  40. Payment::where('id', $payment['id'])->update(['online_sn' => $message['transaction_id'], 'status' => 2, 'payment_time' => time()]);
  41. //更新订单
  42. Order::where('id', $payment['order_id'])->update([
  43. 'order_status' => 2,
  44. 'payment_status' => 2,
  45. 'payment_time' => time(),
  46. ]);
  47. $order = Order::select(['docter_id'])->where('id', $payment['order_id'])->first();
  48. //更新医生的服务人数
  49. Docter::where('id', $order['docter_id'])->increment('service_persons');
  50. // 提交事务
  51. DB::commit();
  52. } catch (\Exception $e) {
  53. // 回滚事务
  54. DB::rollback();
  55. trace(['微信支付回调错误' => $e->getMessage(), '错误数据' => $payment], 'error');
  56. return $fail('内部服务失败,请稍后再通知我');
  57. }
  58. }
  59. elseif ($message['result_code'] === 'FAIL') {
  60. $err_code = $message['err_code'] ?? '';
  61. $err_code_des = $message['err_code_des'] ?? '';
  62. $remark = $err_code.':'.$err_code_des;
  63. Payment::where('id', $payment['id'])->update(['remark' => $remark, 'status' => 3, 'payment_time' => time()]);
  64. }
  65. }
  66. else {
  67. trace(['微信支付回调通知数据错误,返回码return_code:' => $message['return_code'], '错误数据' => $payment], 'error');
  68. return $fail('通信失败,请稍后再通知我');
  69. }
  70. return true; // 返回处理完成
  71. });
  72. return $response;
  73. }
  74. }