PaymentController.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Created by ${PRODUCT_NAME}
  4. * User: JianJia.Zhou
  5. * DateTime: 2021/8/16 23:14
  6. * @description
  7. */
  8. namespace App\Http\Controllers\Api;
  9. use App\Models\ShareConfig;
  10. use App\Models\User;
  11. use App\Models\UserShare;
  12. use App\Models\UserVip;
  13. use Carbon\Carbon;
  14. use EasyWeChat\Factory;
  15. use EasyWeChat\Kernel\Exceptions\Exception;
  16. class PaymentController extends Controller
  17. {
  18. public function notice()
  19. {
  20. $app = Factory::payment(config('wechat.payment.default'));
  21. $response = $app->handlePaidNotify(function ($message, $fail) {
  22. trace(json_encode($message,JSON_UNESCAPED_UNICODE),'debug');
  23. // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
  24. $order = UserVip::where('order_id', $message['out_trade_no'])->first();
  25. if (!$order) { // 如果订单不存在
  26. return true;
  27. }
  28. if ($message['return_code'] === 'SUCCESS') {
  29. if ($message['result_code'] === 'SUCCESS') {
  30. $order->pay_at = Carbon::now()->toDateTimeString(); // 更新支付时间为当前时间
  31. $order->status = 1;
  32. $order->serial_number = $message['transaction_id'];
  33. }elseif ($message['result_code'] === 'FAIL') {
  34. $order->status = 2;
  35. }
  36. } else {
  37. return $fail('通信失败,请稍后再通知我');
  38. }
  39. if($order->status == 1){
  40. $user = User::find($order->user_id);
  41. $user->is_vip = 1;
  42. $user->become_vip_at = Carbon::now()->toDateTimeString();
  43. $user->save();
  44. // 一级分销
  45. $this->shareIncome($user);
  46. }
  47. $order->save();
  48. return true;
  49. });
  50. return $response;
  51. }
  52. /**
  53. * @create JianJia.Zhou<z656123456@gmail.com>
  54. * @param User $user
  55. * @return bool
  56. */
  57. private function shareIncome($user)
  58. {
  59. if($user->parent_id){
  60. $shareConfig = ShareConfig::orderBy('id','asc')->first()->toArray();
  61. if(empty($shareConfig['is_open'])){
  62. return true;
  63. }
  64. UserShare::create([
  65. 'user_id' => $user->parent_id,
  66. 'child_id' => $user->id,
  67. 'income' => $shareConfig['price'],
  68. ]);
  69. $parent = User::find($user->parent_id);
  70. $parent->overage = $parent->overage + $shareConfig['price'];
  71. $parent->income = $parent->income + $shareConfig['price'];
  72. $parent->save();
  73. }
  74. }
  75. }