OrderFactory.php 41.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 工厂类:订单 工厂类
+-----------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Factories
 * @package   App\Factories
 * @author    Richer <yangzi1028@163.com>
 * @date      2020年12月28日14:39:06
 * @copyright 2021-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
namespace App\Factories;

use App\Models\Cart\CartOrder;
use App\Models\Goods\Goods;
use App\Models\Groupon\Activity;
use App\Models\PointsMall\Goods as PointsMallGoods;
use App\Models\Order\Order;
use App\Models\Shop;
use App\Models\System\SystemSetting;
use App\Models\Traits\CartOrderTrait;
use App\Models\Traits\ScoreTaskTrait;
use App\Models\Traits\SystemSettingTrait;
use App\Models\Traits\UserPointsTrait;
use App\Models\Traits\UserWalletTrait;
use App\Models\User\User;
use App\Models\User\UserPointRecord;
use App\Models\User\UserWallet;
use App\Models\User\UserWalletRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Yansongda\LaravelPay\Facades\Pay;

/**
 * Class OrderFactory
 *
 * @category  App\Factories
 * @package   App\Factories
 * @author    Richer <yangzi1028@163.com>
 * @date      2020年12月28日14:39:06
 * @copyright 2021-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
class OrderFactory
{
    protected $message = "";

    const TOTAL_FEE_TEST = 0.01;

    /**
     * @return string
     */
    public function getMessage()
    {
        return $this->message ? : __('operate_succeeded');
    }

    /**
     * 生成订单
     *
     * @param $model
     * @param $user
     * @param int $quantity
     * @param null $sku
     * @return Order|bool|\Illuminate\Contracts\Foundation\Application|mixed
     */
    public function generateOrder($model, $user, $quantity = 0, $sku = null, $cart_order = null)
    {
        if (empty($model)) {
            $this->message = '暂无当前数据!';
            return false;
        }

        // 判断是否存在方法,不存在退出
        if (!method_exists($model, 'orders')) {
            $this->message = '当前数据无法创建订单!';
            return false;
        }

//        DB::beginTransaction();
        try {
            // 获取 sku :使用mysql排它锁防止超卖
            // 根据商品类型来判断
            $stock  = $model->stock;
            $sku_id = request('sku_id', 0);
            $price  = $model->price;
            $points = 0;
            switch ($model::OBJ_NAME) {
                case Goods::OBJ_NAME:
                    if (!$sku) {
                        $sku = $model->skus()->where('id', $sku_id)->lockForUpdate()
                            ->first(['id','name','content','stock','price','original_price']);
                    } else {
                        $sku_id = $sku->id;
                    }


                    $stock = $sku->stock;
                    $price = $sku->price;
                    break;
                case PointsMallGoods::OBJ_NAME:
                    if (!$sku) {
                        $sku = $model->skus()->where('id', $sku_id)->lockForUpdate()
                            ->first(['id','name','stock','price','points','original_price','original_points']);
                    } else {
                        $sku_id = $sku->id;
                    }

                    $stock = $sku->stock;
                    $price = $sku->price;
                    $points = $sku->points;
                    break;
//                default:
//                    $stock = $model->stock;
            }

            $quantity = $quantity ? : request('quantity', 1);

            if ($stock < $quantity) {
                $this->message ='库存不足!';
                //回滚事务
//                DB::rollBack();
                return false;
            }
            $total_amount = $this->getTotalAmount($price, $quantity);
            $total_points = $points * $quantity;
            $order = $model->orders()->create([
                'number'        => generate_unique_number(),
                'address_id'    => request('address_id', 0),// add by Richer 于 2022-8-11 10:07:57 下单的时候增加地址
                'user_id'       => $user->id,
                'shop_id'       => $model->shop_id ? : 0,
                'can_recycled'  => $model->can_recycled ? : 0,
                'total_amount'  => $total_amount,
                'total_points'  => $total_points,
                'payment_amount'=> $total_amount,
                'quantity'      => $quantity,
                'goods_name'    => $model->name,
                'goods_price'   => $price,
                'goods_points'  => $points,
                'goods_image'   => $model->cover_image_thumb ? : $model->cover_image,
                'goods_amount'  => $model->amount ? : 0,
                'remark'        => request('remark'),
                // update by Richer 于 2022年8月12日15:22:19 修改分销逻辑
                'primary_distributor_id'  => $user->pid ? : 0,
                'secondary_distributor_id'  => $user->gid ? : 0,
//                'primary_distributor_id'  => request('primary_distributor_id', 0),
//                'secondary_distributor_id'=> request('secondary_distributor_id', 0),
                'sku_id'        => $sku_id ? : 0,
                'sku'           => $sku ? : null,
                // add by Richer 于 2022年6月22日17:07:26 ,如果是直接选赠送后支付,需要在订单上面增加赠送相关字段
                'bag_id'        => request('bag_id', 0),
                'given_number'  => request('given_number', 0),
                'given_quantity'=> request('given_quantity', 0),
                'given_message' => request('given_message', ''),
            ]);

            if ($order) {
                switch ($model::OBJ_NAME) {
                    case Goods::OBJ_NAME:
                    case PointsMallGoods::OBJ_NAME:
                        // 库存减少
                        $sku->stock -= $quantity;
                        $sku->save();
                        break;
                    default:
                        // 库存减少
                        $model->stock -= $quantity;
                        $model->save();
                }

                //提交事务
//                DB::commit();

                return $order;
            } else {
                //回滚
                return false;
            }
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
//            DB::rollBack();
            return false;
        }
    }

    /**
     * 支付
     *
     * @param $user
     * @param $model
     * @param $type
     * @param string $notify_url 回调地址
     * @return bool|mixed
     */
    public function pay($user, $model, $type, $notify_url = '')
    {
        // 只有未支付状态才能支付
        if ($model->status != Order::UNPAID) {
            $this->message = '该订单无法支付!';
            return false;
        }

        // 如果支付的时候选择了使用积分抵扣
        // 订单总金额
        $total_amount = $model->total_amount;
        // 订单总积分:积分商城订单
        $total_points = $model->total_points;
        // 用户积分
        $user_points = $user->points;
        // 消耗积分
        $consume_points = 0;
        // 如果是积分商城的商品
        if ($total_points > 0) {
            if (($user_points - $total_points) < 0) {
                $this->message ='支付失败,积分不足!';
                return false;
            }
            $consume_points = $total_points;
        }

//        Log::info('================= points_deducted =================');
//        Log::info(request('points_deducted'));

        // 如果商品积分抵扣
        if (request('points_deducted') === 1) {
            Log::info(request('points_deducted'));

            // 计算抵扣比例
            $rate = $this->getPointsDeductRate();
            // add by Richer 于 2022年7月28日11:42:55 增加抵扣上限
            $limit = $this->getPointsDeductLimit();

            Log::info('$total_amount:' . $total_amount);

            // 最多抵扣的积分
            $deducted_points = floor($total_amount * $limit / $rate);
            Log::info('$deducted_points:' . $deducted_points);

            // 实际需要消耗积分
            $consume_points += $deducted_points;
            Log::info('$consume_points:' . $consume_points);

            if ($consume_points > $user_points) {
                $consume_points = $user_points;
                $deducted_points = $consume_points - $total_points;
            }
            Log::info('$deducted_points:' . $deducted_points);

            // 积分抵扣金额
            $points_deducted_amount = $deducted_points * $rate;
            // 向下取整
//            $points_deducted_amount = floor($points_deducted_amount);
//             获取实际的金额
//            $deducted_points = $points_deducted_amount / $rate;
            // 获取抵扣积分
            Log::info('$deducted_points:' . $deducted_points);
//
//            // 积分抵扣金额
//            $points_deducted_amount = $deducted_points * $rate;
//            Log::info('$points_deducted_amount:' . $points_deducted_amount);

            $payment_amount = $total_amount - $points_deducted_amount;
            Log::info('$payment_amount:' . $payment_amount);

            if (\request('test') === 1) {
                dump($user_points);
                dump($points_deducted_amount);
                dump($payment_amount);
                dump('$rate:' .$rate);
                dump('$limit:' .$limit);
                dump('deducted_points:' .$deducted_points);
                dump('consume_points:' .$consume_points);
                dump('$payment_amount:' .$payment_amount);
                dump('$points_deducted_amount:' .$points_deducted_amount);
                dump('$user_points:' .$user_points);
            }

            $model->points_deducted   = $deducted_points;
            $model->points_deducted_amount  = $points_deducted_amount;
            $model->payment_amount  = $payment_amount;
            $model->points_deduct_rate  = $rate;
            $model->points_deduct_limit  = $limit;
//            // 用户积分减少
//            $user->points -= $consume_points;
//            $user->save();
//            Log::info('================= payment_amount =================');
//            Log::info($payment_amount);
        }

        // 如果积分抵扣后支付为0
        if ($model->payment_amount == 0) {
            // 更新订单
            $model->paid_type   = $type;
            $model->status      = Order::PAID;
            $model->paid_amount = $model->payment_amount;
            $model->paid_at     = now()->toDateTimeString();
            $result             = $model->save();
            if ($result) {
                // 支付成功后处理
                $this->handleAfterPaySuccessed($model);
            }
            return $result ;
        }

        $out_trade_no = $model->number.time();

        $body = config('app.name_zh');

        // 设置提交请求
        $pay = [
            'out_trade_no' => $out_trade_no
        ];

        // 自定义回调地址
        if ($notify_url) {
            $pay['notify_url'] = $notify_url;
        }
        $model->out_trade_no = $out_trade_no;
        switch ($type) {
            case Order::BALANCE:// 余额支付
                return $this->payByBalance($user, $model, $type, $body, $pay);
            case Order::WECHAT_PAY:// 微信支付
            case Order::WECHAT_APPLET_PAY:// 微信小程序支付
            case Order::WECHAT_SCAN_PAY:// 微信扫码支付
                return $this->payByWechat($user, $model, $type, $body, $pay);
//            case Order::WECHAT_APPLET_PAY:// 微信小程序支付
//                return $this->payByWechatApplet($model, $body, $pay);
//            case Order::WECHAT_SCAN_PAY:// 微信扫码支付
//                return $this->payByWechatScan($model, $body, $pay, $user);
            case Order::ALIPAY: // 支付宝支付
                return $this->payByAlipay($model, $type, $body, $pay);
//            case Order::ALIPAY_SCAN_PAY:// 支付宝扫码支付
//                return $this->payByAlipayScan($model, $body, $pay, $user);
                break;

                break;
        }
    }

    /**
     * 积分抵扣支付
     *
     * @param $user
     * @param $model
     * @param $type
     * @return mixed
     */
    protected function pointsDeductedPay($user, $model, $type)
    {
        // 如果支付的时候选择了使用积分抵扣
        // 订单总金额
        $total_amount = $model->total_amount;
        // 订单总积分
        $total_points = $model->total_points;
        // 如果积分抵扣,需要扣除订单中的积分
        $points_deducted = $user->points - $total_points;

        // 计算抵扣比例
        $rate = $this->getPointsExchangeRate();
        // 积分抵扣金额
        $points_deducted_amount = $points_deducted * $rate;
        $payment_amount = $total_amount - $points_deducted_amount;
        if ($payment_amount < 0) {
            // 如果可以全额支付
            $points_deducted = $total_amount / $rate;
            $points_deducted_amount = $total_amount;
            $payment_amount = 0;
        }

        $model->points_deducted         = $points_deducted;
        $model->points_deducted_amount  = $points_deducted_amount;
        $model->payment_amount  = $payment_amount;

        // 如果积分抵扣后支付为0
        if ($model->payment_amount == 0) {
            // 更新订单
            $model->paid_type   = $type;
            $model->status      = Order::PAID;
            $model->paid_amount = $model->payment_amount;
            $model->paid_at     = now()->toDateTimeString();
            $result      = $model->save();
            if ($result) {
                // 支付成功后处理
                $this->handleAfterPaySuccessed($model);
            }
            return $result ;
        }
    }
    /**
     * 根据订单的明细生成订单的金额
     *
     * @param $price
     * @param $quantity
     * @return float
     */
    protected function getTotalAmount($price, $quantity)
    {
        return $price * $quantity;
    }

    /**
     * 获取支付金额:在非生产试环境中,将支付金额设置为0.01,方便测试环境进行支付测试
     *
     * @param float $amount 金额
     *
     * @return float
     */
    protected function getPaidAmount($amount)
    {
        // 测试环境和本地环境支付金额为0.01
        if (config('app.env') !== 'production') {
            $amount = self::TOTAL_FEE_TEST;
        }


        return $amount;
    }

    /**
     * 余额支付
     *
     * @param $user
     * @param $model
     * @param $type
     * @param $body
     * @param $pay
     *
     */
    protected function payByBalance($user, $model, $type, $body, $pay)
    {
        // 获取支付金额
        $payment_amount = $model->payment_amount;
        $wallet = $user->wallet;
        // 获取用户的余额
        $balance = optional($wallet)->balance;
        if ($balance < $payment_amount) {
            $this->message = '支付失败,余额不足!';
            return false;
        }

        // 更新订单
        $model->paid_type = $type;
        $model->status      = Order::PAID;
        $model->paid_amount = $payment_amount;
        $model->paid_at     = now()->toDateTimeString();
        $result = $model->save();
        if ($result) {
            // 用户余额减少
            $this->accountCost($user, $payment_amount, UserWalletRecord::BUY, Order::OBJ_NAME, $model->id);

            // 支付成功后处理
            $this->handleAfterPaySuccessed($model);

            return $result;
        }
    }

    /**
     * 微信支付
     *
     * @param $user
     * @param $model
     * @param $type
     * @param $body
     * @param $pay
     *
     * @return false|mixed|\Yansongda\Supports\Collection
     */
    protected function payByWechat($user, $model, $type, $body, $pay)
    {
//        Log::info('$deducted_points:' . $model->payment_amount);

        // 获取支付金额
        $total_fee = $this->getPaidAmount($model->payment_amount);

        // 设置单独付款
        if ($user->mobile === '18118154730') {
            $total_fee = self::TOTAL_FEE_TEST;
        }
        // 微信支付设置为total_fee 和 body
        // 微信支付提交的金额是不能带小数点的,且是以分为单位,所以我们系统如果是以元为单位要处理下金额,即先乘以100,再去小数点
        // (Math.Round((decimal)order.Amount * 100, 0)).ToString()
        $pay['total_fee'] = $total_fee * 100;// 订单金额,**单位:分**
        $pay['body'] = $body;// 订单描述
        $pay['openid'] = $user->openid ? : request('openid');// 支付人的 openID
        $pay['spbill_create_ip'] = request()->ip();// 支付人的 IP


        // 微信支付
        try {
            $response = null;
            switch ($type) {
                case Order::WECHAT_PAY:// 微信支付
                    $response = Pay::wechat()->mp($pay);
                    break;
                case Order::WECHAT_APPLET_PAY:// 微信小程序支付
                    $response = Pay::wechat()->miniapp($pay);
                    break;
                case Order::WECHAT_SCAN_PAY:// 微信扫码支付
                    $response = Pay::wechat()->scan($pay);
                    break;
            }

            // 更新订单
            $model->paid_type =$type;
            $model->out_trade_no =$pay['out_trade_no'];
            $model->save();
//            Log::info( $response);

            return $response;
        } catch (\Exception $e) {
//            $this->message = $e->getMessage();
            $this->message = '支付失败,' . str_replace('ERROR_GATEWAY: ERROR_BUSINESS: Wechat Business Error: ', '', $e->getMessage());

            return false;
        }
    }

    /**
     * 支付宝支付
     *
     * @param Order $model 订单对象
     * @param string $body 支付
     * @param array $pay 支付主体
     *
     * @return bool|mixed
     */
    protected function payByAlipay($model, $body, $pay)
    {
        // 获取支付金额
        $total_fee = $this->getPaidAmount($model->total_amount);

        // 支付宝支付 设置为 total_amount  和 subject
        $pay['total_amount'] = $total_fee;
        $pay['subject'] = $body;

        $response = Pay::alipay()->app($pay);
        $content = $response->getContent();
        $statuscode = $response->getStatusCode();

        // 返回
        if ($statuscode == 200) {
            return $content;
        }
        return false;
    }

    /**
     * 支付宝支付异步通知支付结果
     *
     * Alipay notify {"gmt_create":"2020-01-08 10:09:50","charset":"utf-8","seller_email":"huntour989@163.com",
     * "subject":"游米游",
     * "sign":"VKFB8HsiKb7Cdoo8Bb9isnNebGJRJfjaOPGiR8piHm/CSpsKYScCvxKs6K+fh2QGptbEx4QWQXgjqs+jdzsqSuILcFI7FwwdPDcQPZsqFTsEz+RETzprtGzF8CjEToIyCYS+AO+V9KsrqaVTKToL9pIHjx2VEaUc5qWmokBdH/K46SQEuIjLisN6wSzMznvqzPstklnkpcR6TSGUKBxIfoQcsAt93T1c/oBS+0v/ihUiYs3QoiyiNp8g3ZRWZsBulKlBebqbVAOm0LUQudmKfVoaqaYmTjcCJPz8DcAxNKwT/SZjDvFEgut785m7M29tbf2zBWzQRS8ibJmJIW1/Jw==",
     * "buyer_id":"2088002048941725","invoice_amount":"0.01",
     * "notify_id":"2020010800222100950041721416256139",
     * "fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]",
     * "notify_type":"trade_status_sync",
     * "trade_status":"TRADE_SUCCESS",
     * "receipt_amount":"0.01",
     * "app_id":"2019041063880127",
     * "buyer_pay_amount":"0.01",
     * "sign_type":"RSA2",
     * "seller_id":"2088431978669735",
     * "gmt_payment":"2020-01-08 10:09:50",
     * "notify_time":"2020-01-08 10:09:50",
     * "version":"1.0","out_trade_no":"1578449382",
     * "total_amount":"0.01","trade_no":"2020010822001441721408484200",
     * "auth_app_id":"2019041063880127","buyer_logon_id":"yan***@163.com","point_amount":"0.00"}
     *
     * @param Request $request request
     *
     * @return bool|mixed
     */
    public function notifyAlipay($request)
    {
        record_log('alipay', 'begin', '支付宝 支付异步回调 Alipay notify');

        // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号;
        // 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额);
        // 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email);
        // 4、验证app_id是否为该商户本身。
        // 5、其它业务逻辑情况

        $alipay = Pay::alipay();

        try {
            $data = $alipay->verify(); // 是的,验签就这么简单!
            record_log('alipay', '', json_encode($data->all()));
            record_log('alipay', '', '交易状态 return_code:' . $data->return_code);
            // 请自行对 trade_status 进行判断及其它逻辑进行判断,在支付宝的业务通知中,只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时,支付宝才会认定为买家付款成功。
            switch ($data->trade_status) {
                case 'TRADE_SUCCESS':
                case 'TRADE_FINISHED':
                    // 获取商户订单号
                    $out_trade_no = $data->out_trade_no;
                    record_log('alipay', '', '$out_trade_no:' .$out_trade_no);
                    // 根据商户订单号获取系统中的订单
                    $model = Order::where('out_trade_no', $out_trade_no)->first();
                    record_log('alipay', '', '订单信息:' . json_encode($model));

                    if ($model) {
                        record_log('alipay', '', '订单状态:' . $model->status);

                        // 更新数据库状态
                        if ($model->status === Order::UNPAID) {
                            $model->status      = Order::PAID;
                            $model->paid_type   = Order::ALIPAY;
                            $model->paid_amount = $data->total_amount;
                            $model->paid_at     = $data->gmt_payment;
                            $model->paid_info = $data;
                            $result = $model->save();
                            record_log('alipay', '', '订单执行:' . json_encode($result));

                            // 订单支付回调成功后
                            $this->handleAfterPaySuccessed($model);
                        }
                    }
                    record_log('alipay', 'end', '支付宝 支付异步回调 Alipay notify');

                    return $alipay->success();
                    return true;
                    break;
            }
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            record_log('alipay', '', '错误:' .$this->message);

            record_log('alipay', 'end', '支付宝 支付异步回调 Alipay notify');

            return false;
        }

        return $alipay->success();// laravel 框架中请直接 `return $alipay->success()`
    }

    /**
     * 微信支付异步通知支付结果
     *
     * {"appid":"wxef22db12a3e9af90","bank_type":"CMB_CREDIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N",
     * "mch_id":"1515000691","nonce_str":"cbT8iCPuIp3JkodY","openid":"othGt1eA5x4HeRhppnzxGnhC-bIo",
     * "out_trade_no":"1578450561","result_code":"SUCCESS","return_code":"SUCCESS",
     * "sign":"9D86849E44A36D362950381EC5213E84",
     * "time_end":"20200108102928",
     * "total_fee":"1","trade_type":"APP",
     * "transaction_id":"4200000504202001086820896950"
     * }
     *
     * @param Request $request request
     *
     * @return bool
     */
    public function notifyWechat($request)
    {
        record_log('wechat-pay', 'begin', '微信 支付异步回调 Wechat notify', true);

        $pay = Pay::wechat();

        try {
            $data = $pay->verify(); // 是的,验签就这么简单!

            record_log('wechat-pay', '', json_encode($data->all()), true);
            record_log('wechat-pay', '', '交易状态 return_code:' . $data->return_code, true);

            switch ($data->return_code) {
                case 'SUCCESS':
                    // 获取商户订单号
                    $out_trade_no = $data->out_trade_no;
                    record_log('wechat-pay', '', '$out_trade_no:' .$out_trade_no);

                    // 根据商户订单号获取系统中的订单
                    $model = Order::where('out_trade_no', $out_trade_no)->first();
                    record_log('wechat-pay', '', '订单信息:' . json_encode($model));
                    if (!$model) {
                        record_log('wechat-pay', 'end', '微信App支付异步回调 Wechat notify');
                        $this->message = '未查询到本地订单!';
                        return false;
                    }

                    record_log('wechat-pay', '', '订单状态:' . $model->status);

                    // 更新数据库状态
                    if ($model->status == Order::UNPAID) {
                        $model->status      = Order::PAID;
                        $model->paid_type   = Order::WECHAT_APPLET_PAY;
                        $model->paid_amount = $data->total_fee / 100;
                        $model->paid_at     = Carbon::parse($data->time_end);
                        $model->paid_info   = $data;
                        $result = $model->save();
                        record_log('wechat-pay', '', '订单执行:' . json_encode($result));

                        // 订单支付回调成功后
                        $this->handleAfterPaySuccessed($model);
                    }
                    record_log('wechat-pay', 'end', '微信App支付异步回调 Wechat notify');
                    return true;
            }
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            record_log('wechat-pay', '', '错误:' .$this->message);

            record_log('wechat-pay', 'end', '微信App支付异步回调 Wechat notify');
            return false;
        }
//        return $pay->success();
    }

    /**
     * 支付回调成功后
     *
     * @param $order
     * @return bool
     */
    public function handleAfterPaySuccessed($order)
    {
        // add by Richer 于 2022年6月17日17:36:30 购买供应商的商品,需要将钱打入供应商的账号
        if ($order->shop_id) {
            // 获取 供应商的信息
            $shop = Shop::with(['user'])->find($order->shop_id);
            $agency_user = optional($shop)->user;
            $total_amount = $order->total_amount;

            $event = UserWalletRecord::BUY;
            if ($order->type === Activity::OBJ_NAME) {
                $event = UserWalletRecord::GROUPON;
            }
            // 钱包入账
            $this->accountEntry($agency_user, $total_amount, $event, Order::OBJ_NAME, $order->id);
        }

        // 支付成功后,设置会员数量和直推间推像相关用户进行分账
        $user = $order->user;
        $total_points = $order->total_points;
        if ($total_points > 0) {
            // 同时用户积分记录
            $this->decreasePoints($user, $total_points, UserPointRecord::EXCHANGE, $order::OBJ_NAME, $order->id);
        }

        $points_deducted = $order->points_deducted;
        if ($points_deducted > 0) {
            // 同时用户积分记录
            $this->decreasePoints($user, $points_deducted, UserPointRecord::BUY, $order::OBJ_NAME, $order->id);
        }

        // 返佣
        $this->rebate($user, $order);

        // 更新拼团信息
        $this->updateGroupon($order);

        // add by Richer 于 2022年6月9日15:54:44 如果是购物车的订单,需要将子订单全部设置为已支付
        $this->updateCartOrder($order);

        // add by Richer 于 2022年6月22日09:19:43 修改业务逻辑,支付成功的订单都自动生成礼物
        // 如果是购物车订单
        if ($order::OBJ_NAME === CartOrder::OBJ_NAME) {
            $this->generateCardOrderGift($order);
        } else {
            $this->generateGift($order);
        }

        return true;
    }

    /**
     * 微信支付订单退款
     *
     * @param $order
     * @return mixed
     */
    public function refund($order)
    {
        // 特殊处理  拼团的订单 才能进行退款
        if ($order->type === Activity::OBJ_NAME) {
            // 如果谁开团的订单,需要同步修改团的状态
            $orderable = $order->orderable;
            if ($orderable->status == Activity::PROCESSING) {
                // 获取拼团任务状态
                // 只有未支付状态才能支付
                if (!in_array($order->status, Order::CAN_REFUND_STATUS_OPTIONS)) {
                    $this->message = '该订单无法取消!';
                    return false;
                }

                $paid_type = $order->paid_type;
                $result = false;
                switch ($paid_type) {
                    case Order::WECHAT_PAY:// 微信支付
                    case Order::WECHAT_APPLET_PAY:// 微信小程序支付
                    case Order::WECHAT_SCAN_PAY:// 微信扫码支付
                        $result =  $this->refundWechat($order);
                        break;
                    case Order::BALANCE:// 余额支付
                        $result =  $this->refundBalance($order);
                        break;
                    case Order::ALIPAY: // 支付宝支付
                }
                if ($result) {
                    // 拼团活动设置为过期
                    $orderable->status = Activity::EXPIRED;
                    $orderable->save();
                    // 同时需要将商家冻结的资金去掉
                    if ($order->shop_id !== 0) {
                        //
                    }
                }
            }
        }
    }

    /**
     * 微信支付订单退款
     *
     * @param $order
     * @return mixed
     */
    public function refundWechat($order)
    {
        record_log('wechat-pay', 'begin', '微信 退款', true);

        // 设置提交请求
        $out_refund_no = $order->number.time();
        $refunded_amount = $order->paid_amount * 100;
        $data = [
            'out_trade_no'  => $order->out_trade_no,
            'out_refund_no' => $out_refund_no,
            'total_fee'     => $refunded_amount,
            'refund_fee'    => $refunded_amount,
            'refund_desc'   => '退款',
//            'amount' => [
//                'refund'    => $refunded_amount,
//                'total'     => $refunded_amount,
//                'currency'  => 'CNY',
//            ],
        ];

        record_log('wechat-pay', '', json_encode($data), true);

        try {
            $result = Pay::wechat()->refund($data);
            record_log('wechat-pay', '', json_encode($result), true);

            $order->out_refund_no = $out_refund_no;
            $order->refunded_amount = $refunded_amount;
            $order->status = Order::REFUNDED;
            $order->refunded_status = 1;
            $order->refunded_reason = '拼团到期未成团自动退款';
            $order->refunded_at = now()->toDateTimeString();
            return $order->save();

        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            record_log('wechat-pay', '', '错误:' .$this->message);

            record_log('wechat-pay', 'end', '微信 退款', true);

            return false;
        }
    }

    /**
     * 微信支付订单退款
     *
     * @param $order
     * @return mixed
     */
    public function refundBalance($order)
    {
        record_log('wechat-pay', 'begin', '余额 退款', true);

        // 余额支付
        $event  = UserWalletRecord::REFUND;
        $user   = $order->user;
        $total_amount = $order->total_amount;

        // 释放资金
        $this->releaseFrozenAmount(UserWalletRecord::INCREASE, $user, $total_amount, $event, Order::OBJ_NAME, $order->id);
        $order->status = Order::REFUNDED;
        $order->refunded_status = 1;
        $order->refunded_reason = '拼团到期未成团自动退款';
        $order->refunded_at = now()->toDateTimeString();

        record_log('wechat-pay', 'end', '余额 退款', true);
        return $order->save();
    }

    /**
     * 账户转账
     *
     * @param $partner_trade_no
     * @param $openid
     * @param int $amount
     * @param string $desc
     * @param string $type
     */
    public function transfer($partner_trade_no, $openid, $amount = 0, $desc = '帐户提现', $type = 'miniapp')
    {
        $order = [
            'partner_trade_no' => $partner_trade_no,  //商户订单号
            'openid'        => $openid,               //收款人的openid
            'check_name'    => 'NO_CHECK',            //NO_CHECK:不校验真实姓名\FORCE_CHECK:强校验真实姓名
            // 're_user_name'=>'张三',              //check_name为 FORCE_CHECK 校验实名的时候必须提交
            'amount'        => $amount,                       //企业付款金额,单位为分
            'desc'          => $desc,                  //付款说明
            'type'          => $type, // 如果您需要通过 APP/小程序 的商户账号appid进行转账,请传入参数:['type' => 'app']/['type' => 'miniapp']
            'spbill_create_ip' => request()->ip(), // 如果您在队列中使用,请自行传参 spbill_create_ip。
        ];

        try {
            $result = Pay::wechat()->transfer($order);
        } catch (\Exception $e) {
            dump($e->getMessage());
        }
    }

    /**
     * 订单取消:
     * update by Richer 于 2020年5月18日10:59:47 修改业务逻辑:增加了退款的逻辑,取消的功能只能是未支付之前的订单才能取消
     *
     * @param Order $order 订单对象
     * @param null $user 用户对象
     * @param string $reason
     * @return bool
     */
    public function cancel($order, $user = null, $reason = '订单未支付自动关闭')
    {
        $status = $order->status;
        // 订单状态可以进行退款
        if (!in_array($status, Order::CAN_CANCEL_STATUS_OPTIONS)) {
            $this->message = '该订单暂时无法取消!';
            return false;
        }

        // 本地订单状态进行修改
        $order->status = Order::CANCELLED;
        $order->cancelled_reason = $reason;
        $order->cancelled_by  = $user->id;
        $order->cancelled_by = $user ? $user->id : 0;
        $order->cancelled_at  = now()->toDateTimeString();
        $result = $order->save();
        // 同时需要将相关的数据状态设置为 取消,主要是定制导游和定制游
        if ($result) {
            $this->generateJobAfterCancel($order);
        }
        return $result;


        // 获取第三方商户号
        $out_trade_no = $order->out_trade_no;
        $out_refund_no = time();
        $total_fee = $this->getPaidAmount($order->amount);

        if ($out_trade_no) {
            //  取消订单关闭
            $data = [
                'out_trade_no' => $out_trade_no,
            ];
            switch ($paid_type) {
                case Order::WECHAT_APPLET_PAY://微信小程序支付
                    // 取消
                    try {
                        if ($order->is_new_pay == 0) {
                            $result = Pay::wechat()->close($data);
                        } else {
                            //$factory = app(UnionPayFactory::class);
                            //$result = $factory->close($order);
                            $result = app(PayFactory::class)->call($order, 'close');
                            if ($result['errCode'] == 'SUCCESS') {
                                $order->paid_info = json_encode($result, JSON_UNESCAPED_UNICODE);
                                $order->save();
                            } else {
                                $this->message = $result['errMsg'];
                                Log::info('订单关闭失败:' . $result['errMsg']);
                                return false;
                            }
                        }
                    } catch (\Exception $e) {
                        $this->message = $e->getMessage();

                        return false;
                    }
                    break;
                case Order::WECHAT://// APP支付 - 微信支付
                    // 取消
                    try {
                        if ($order->is_new_pay == 0) {
                            $result = Pay::wechat()->close($data);
                        } else {
                            //$factory = app(UnionPayFactory::class);
                            //$result = $factory->app()->wechat()->close($order);
                            $result = app(PayFactory::class)->call($order, 'close');
                            if ($result['errCode'] == 'SUCCESS') {
                                $order->paid_info = json_encode($result, JSON_UNESCAPED_UNICODE);
                                $order->save();
                            } else {
                                $this->message = $result['errMsg'];
                                Log::info('订单关闭失败:' . $result['errMsg']);
                                return false;
                            }
                        }
                    } catch (\Exception $e) {
                        $this->message = $e->getMessage();

                        return false;
                    }
                    break;
                case Order::ALIPAY:// 支付宝支付类型
                    // 取消
                    try {
                        if ($order->is_new_pay == 0) {
                            //TODO update by Richer 于2020年4月22日16:17:51 未支付的订单未在支付宝后台生成订单,所以此处不能调用退款接口会提示ACQ.TRADE_NOT_EXIST
                            // $result = Pay::aliPay()->close($data);
                        } else {
                            //$factory = app(UnionPayFactory::class);
                            //$result = $factory->app()->aliPay()->close($order);
                            $result = app(PayFactory::class)->call($order, 'close');
                            if ($result['errCode'] == 'SUCCESS') {
                                $order->paid_info = json_encode($result, JSON_UNESCAPED_UNICODE);
                                $order->save();
                            } else {
                                $this->message = $result['errMsg'];
                                Log::info('订单关闭失败:' . $result['errMsg']);
                                return false;
                            }
                        }
                    } catch (\Exception $e) {
                        $this->message = $e->getMessage();

                        return false;
                    }
                    break;
                case Order::ALIPAYSCAN:
                    //TODO update by Richer 于2020年4月22日16:17:51 未支付的订单未在支付宝后台生成订单,所以此处不能调用退款接口会提示ACQ.TRADE_NOT_EXIST

                    break;
                default:
                    $result = true;
                    break;
            }
        }

        // 本地订单状态进行修改
        $order->status = Order::CANCELLED;
        $order->canceled_by = $user ? $user->id : 0;
        $order->canceled_at = date('Y-m-d H:i:s');
        $order->canceled_reason = request('canceled_reason') ?? '一小时内未支付,系统自定取消订单!';
        $result = $order->save();
        // 同时需要将相关的数据状态设置为 取消,主要是定制导游和定制游
        if ($result) {
            $this->generateJobAfterCancel($order);
        }
        return $result;
    }

    /**
     * 订单取消或者退款成功后,处理定时任务
     *
     * @param Order $order 订单对象
     *
     * @return void
     */
    protected function generateJobAfterCancel($order)
    {
        // 订单创建成功后,需要对库存数据做删除

        switch ($order->type) {
            case Homestay::OBJ_NAME:
            case Hotel::OBJ_NAME:
                $items = $order->items ?? $order->items()->get();
                $orderable = $order->orderable;

                $items->each(function ($item) use ($orderable) {
                    $calendar_info = $item->calendar_info;
                    $calendar_ids = [];
                    if ($calendar_info) {
                        foreach ($calendar_info as $vo) {
                            $calendar_ids[] = $vo['id'];
                        }
                    }
                    $update['ordered_quantity'] = DB::raw('ordered_quantity - '.$item->quantity);
                    $orderable->calendars()->whereIn('id', $calendar_ids)->update($update);
                });
                break;
            case TourGroup::OBJ_NAME:
            case TourSurround::OBJ_NAME:
                $orderable  = $order->orderable;
                $items     = $order->items;
                $items->each(function ($item) use ($orderable) {
                    $update['ordered_quantity'] = DB::raw('ordered_quantity - '.$item->adult_quantity);
                    $orderable->teams()->where('id', $item->tour_team_id)->update($update);
                });
                break;
        }
    }
}