PayCallbackController.php 3.1 KB

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