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
<?php
/**
 * Created by PhpStorm.
 * User: 86132
 * Date: 2020/11/19
 * Time: 22:23
 */

namespace app\api\controller;


use app\common\controller\Api;
use think\Db;

/**
 * 支付接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 订单接口
     * @ApiTitle    (支付)
     * @ApiSummary  (支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Pay/Wechat)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="OrderSn", type="integer", required=true, description="订单号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function Wechat()
    {
        $UserId = $this->is_token($this->request->header());
        $OrderSn = input('OrderSn');
        $Openid = Db::name('user')->where('id', $UserId)->value('openid');
        //查询订单
        $OrderArray = Db::name('order')->where('OrderSn', $OrderSn)->find();
        //生成支付订单号
        $PayOrder = $this->PayOrder();
        //生成支付订单
        $data = [
            'PayOrder' => $PayOrder,
            'OrderSn' => $OrderSn,
            'status' => 0,
            'user_id' => $UserId,
            'money' => $OrderArray['total'],
            'createtime' => time(),
            'updatetime' => time()
        ];
        $InsertPayOrder = Db::name('pay_order')->insert($data);
        if (!$InsertPayOrder) {
            $this->error('支付订单生成失败', 0);
            die;
        }
        $domain = $this->request->domain();
        $data = [
            'amount' => $OrderArray['total'],
            'orderid' => $PayOrder,
            'type' => "wechat",
            'title' => "会员开通",
            'notifyurl' => $domain . "/api/pay/WechatNotify/paytype/wechat",
            'returnurl' => $domain . "/api/pay/baidu",
            'method' => "miniapp",
            'openid' => $Openid
        ];
        $return = \addons\epay\library\Service::submitOrder($data);
        echo $return;
    }


    /**
     * 订单接口
     * @ApiTitle    (支付回调)
     * @ApiSummary  (支付回调)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Pay/WechatNotify)
     * @ApiParams   (name="paytype", type="string", required=true, description="")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function WechatNotify()
    {
        $paytype = $this->request->param('paytype');
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            die;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            //$data['out_trade_no'] 支付单号
            $order_sn = $data['out_trade_no'];
            $order = Db::name('pay_order')->where('PayOrder', $order_sn)->find();
            if ($order['status'] == 1) {
                return $pay->success('支付成功');
                die;
            }
            //在此编写订单逻辑
            //修改支付订单状态
            $UpdateStatus = Db::name('pay_order')->where('PayOrder', $data['out_trade_no'])->update(
                [
                    'status' => 1,
                    'updatetime' => time(),
                    'WeChatOrder' => $data['transaction_id'],
                    'pay_time' => time()
                ]
            );
            $PayOrderInfo = Db::name('pay_order')->where('PayOrder', $data['out_trade_no'])->find();
            $OrderInfo = Db::name('order')->where('OrderSn', $PayOrderInfo['OrderSn'])->find();
            $UnionID = Db::name('user')->where('id', $PayOrderInfo['user_id'])->value('UnionID');

            if (!$UpdateStatus) {
                $this->error('修改支付订单状态失败', 0);
                die;
            }
            //修改订单状态
            $UpdateOrder = Db::name('order')->where('OrderSn', $PayOrderInfo['OrderSn'])->update([
                'status' => 1,
                'updatetime' => time()
            ]);
            if (!$UpdateOrder) {
                $this->error('修改订单状态失败', 0);
                die;
            }
            /*订单推送到管易*/
            $GuanYiCloud = new GuanYiCloud();
            $City = explode('/', $OrderInfo['city']);
            //查询订单详情
            $GoodsArray = Db::name('order_con')
                ->alias('o')
                ->where('o.OrderSn', $PayOrderInfo['OrderSn'])
                ->join('goods g', 'g.id=o.Goods_id')
                ->field('g.goods_code,o.num,g.price')
                ->select();
            foreach ($GoodsArray as $k => $v) {
                $details[$k]['item_code'] = $v['goods_code'];
                $details[$k]['qty'] = $v['num'];
                $details[$k]['price'] = $v['price'];
                $details[$k]['oid'] = $PayOrderInfo['OrderSn'];
            }
            $PayTime = $PayOrderInfo['pay_time'] * 1000;
            $GuanYiCloud->addOrder($PayOrderInfo['OrderSn'], date('Y-m-d H:i:s', $OrderInfo['createtime']), $PayTime, $UnionID, $OrderInfo['name'], $OrderInfo['mobile'], $OrderInfo['address'] . '/' . $OrderInfo['address_con'], $City[0], $City[1], $City[2], $details, $PayOrderInfo['money'], $PayOrderInfo['PayOrder']);
            /*补充逻辑*/
            $WaterUserNum = Db::name('user')->where('id', $PayOrderInfo['user_id'])->find();
            //更改用户积分
            Db::name('user')->where('id', $PayOrderInfo['user_id'])->update(['num' => $WaterUserNum['num'] + floor($OrderInfo['total'])]);
            //添加用户积分记录
            $WaterUserNumPay = [
                'user_id' => $PayOrderInfo['user_id'],
                'status' => 1,
                'type' => 10,
                'num' => floor($OrderInfo['total']),
                'up_num' => $WaterUserNum['num'] + floor($OrderInfo['total']),
                'createtime' => time()
            ];
            Db::name('num')->insert($WaterUserNumPay);
            /*补充逻辑*/
            //是否首次下单
            $FirstPay = Db::name('order')->where('OrderSn', 'NEQ', $PayOrderInfo['OrderSn'])->where('status', 'IN', '1,2,3,4,5')->find();
            if (empty($FirstPay)) {
                //新用户首次下单双倍积分
//                Db::name('pay_order')->where('PayOrder', $data['out_trade_no'])->update(
//                    [
//                        'is_new' => 1,
//                    ]
//                );
//                //查询用户积分
//                $FirstPayUserinfo = Db::name('user')->where('id', $PayOrderInfo['user_id'])->find();
//                //更改用户积分
//                $UpdateFirstPay = Db::name('user')->where('id', $PayOrderInfo['user_id'])->update(['num' => $FirstPayUserinfo['num'] + (floor($OrderInfo['total']) * 2)]);
//                if (!$UpdateFirstPay) {
//                    $this->error('更改用户积分失败失败', 0);
//                    die;
//                }
//                //添加用户积分记录
//                $InserNumSql = [
//                    'user_id' => $PayOrderInfo['user_id'],
//                    'status' => 1,
//                    'type' => 5,
//                    'num' => floor($OrderInfo['total']) * 2,
//                    'up_num' => $FirstPayUserinfo['num'] + (floor($OrderInfo['total']) * 2),
//                    'createtime' => time()
//                ];
//                Db::name('num')->insert($InserNumSql);


                //新用户消费  上级增加积分
                $Fuser_id = Db::name('group')->where('user_id', $PayOrderInfo['user_id'])->value('fuser_id');
                if (!empty($Fuser_id)) {
                    $FuserInfo = Db::name('user')->where('id', $Fuser_id)->find();
                    Db::name('user')->where('id', $Fuser_id)->update(
                        [
                            'num' => $FuserInfo['num'] + floor($OrderInfo['total'])
                        ]
                    );
                    //添加用户积分记录
                    $Fuser_idSql2 = [
                        'user_id' => $Fuser_id,
                        'status' => 1,
                        'type' => 9,
                        'num' => floor($OrderInfo['total']),
                        'up_num' => $FuserInfo['num'] + floor($OrderInfo['total']),
                        'createtime' => time()
                    ];
                    Db::name('num')->insert($Fuser_idSql2);
                }
            }
//            //是否升级
//            //已消费金额 $Consumed
//            $Consumed = $this->YiXiaofeiMoney($PayOrderInfo['user_id']);
//            $Level = Db::name('user')->where('id', $PayOrderInfo['user_id'])->value('level');
//            $LevelSql = Db::name('level')->where('type', $Level + 1)->find();
//            if ($Consumed > $LevelSql['price'] && $Consumed == $LevelSql['price']) {
//                $LevelUserInfo = Db::name('user')->where('id', $PayOrderInfo['user_id'])->find();
//                //更改用户积分
//                $UpdateLevelUserInfo = Db::name('user')->where('id', $PayOrderInfo['user_id'])->update(['num' => $LevelUserInfo['num'] + $LevelSql['num']]);
//                if (!$UpdateLevelUserInfo) {
//                    $this->error('更改用户积分失败失败2', 0);
//                    die;
//                }
//                //添加用户积分记录
//                $InserNumSql2 = [
//                    'user_id' => $PayOrderInfo['user_id'],
//                    'status' => 1,
//                    'type' => 6,
//                    'num' => $LevelSql['num'],
//                    'up_num' => $LevelUserInfo['num'] + $LevelSql['num'],
//                    'createtime' => time()
//                ];
//                Db::name('num')->insert($InserNumSql2);
//            }
            //好友下单奖励
//            $Fuser_id = Db::name('group')->where('user_id', $PayOrderInfo['user_id'])->value('fuser_id');
//            if (!empty($Fuser_id)) {
//                $FuserInfo = Db::name('user')->where('id', $Fuser_id)->find();
//                Db::name('user')->where('id', $Fuser_id)->update(
//                    [
//                        'num' => $FuserInfo['num'] + 300
//                    ]
//                );
//                //添加用户积分记录
//                $Fuser_idSql2 = [
//                    'user_id' => $PayOrderInfo['user_id'],
//                    'status' => 1,
//                    'type' => 9,
//                    'num' => 300,
//                    'up_num' => $FuserInfo['num'] + 300,
//                    'createtime' => time()
//                ];
//                Db::name('num')->insert($Fuser_idSql2);
//            }
            //活动逻辑  单笔订单满100元,额外奖励5元。单笔订单满399,额外奖励50元,单笔订单满699元,额外奖励100元;(下级下单)奖励到活动收益表
            $Part = Db::name('huodong')->find();
            $i = 0;
            if ($Part['start_time'] < time() && time() < $Part['end_time']) {
                $i++;
            }
            if ($i != 0) {
                //活动开放
                $Fuser_id = Db::name('group')->where('user_id', $PayOrderInfo['user_id'])->value('fuser_id');
                if (!empty($Fuser_id)) {
                    if ($OrderInfo['total'] > 99) {
                        $RedBad = 5;
                    } elseif ($OrderInfo['total'] > 398) {
                        $RedBad = 50;
                    } elseif ($OrderInfo['total'] > 698) {
                        $RedBad = 100;
                    }
                    //给上级加收益到活动钱包
                    //查询上级钱包
                    $huodong_money = Db::name('huodong_money')->where('user_id', $Fuser_id)->find();
                    Db::name('huodong_money')->where('user_id', $Fuser_id)->update(
                        [
                            'count_money' => $huodong_money['count_money'] + $RedBad,
                            'befor_money' => $huodong_money['befor_money'] + $RedBad
                        ]
                    );
                }
            }
            //自购返现
//            $ZiGou = Db::name('user')->where('id', $PayOrderInfo['user_id'])->find();
//            if ($ZiGou['level'] != 1) {
//                //不是普通会员 产生自购返现
//                //自购折扣
//                $buycount = Db::name('level')->where('type', $ZiGou['level'])->value('buycount');
//                $ZigouMoney = (1 - $buycount) * $OrderInfo['total'];
//                //扣除积分
//                Db::name('user')->where('id', $PayOrderInfo['user_id'])->update(
//                    [
//                        'num' => $ZiGou['num'] - $ZigouMoney,
//                        'money' => $ZiGou['money'] + $ZigouMoney
//                    ]
//                );
//                //积分表添加记录
//                //添加用户积分记录
//                $ZiGouSql = [
//                    'user_id' => $PayOrderInfo['user_id'],
//                    'status' => 0,
//                    'type' => 4,
//                    'num' => $ZigouMoney,
//                    'up_num' => $ZiGou['num'] - $ZigouMoney,
//                    'createtime' => time()
//                ];
//                Db::name('num')->insert($ZiGouSql);
//                //添加收益记录
//                $ZiGouSqlMoney = [
//                    'user_id' => $PayOrderInfo['user_id'],
//                    'money' => $ZigouMoney,
//                    'touser_id' => $PayOrderInfo['user_id'],
//                    'status' => 0,
//                    'type' => 1,
//                    'createtime' => time(),
//                    'OrderSn' => $PayOrderInfo['OrderSn']
//                ];
//                Db::name('money')->insert($ZiGouSqlMoney);
//            }
            //二级分佣
            //查询用户上级和上级的上级
            $FatherUserId = Db::name('group')->where('user_id', $PayOrderInfo['user_id'])->value('fuser_id');
            if (!empty($FatherUserId)) {
                //一级分佣
                //一级精品比例
                $FirstBiliJingpin = Db::name('bili')->where('type', 1)->value('first');
                //一级通品比例
                $FirstBilitongpin = Db::name('bili')->where('type', 2)->value('first');
                //查询订单详情
                $FirstOrderConArray = Db::name('order_con')->where('OrderSn', $PayOrderInfo['OrderSn'])->select();
                if (!empty($FirstOrderConArray)) {
                    foreach ($FirstOrderConArray as $k => $v) {
                        $GoodsType = Db::name('goods')->where('id', $v['Goods_id'])->find();
                        if (!empty($GoodsType)) {
                            if ($GoodsType == 1) {
                                //精品
                                $FirstMoney[] = $GoodsType['price'] * $FirstBiliJingpin;
                            } else {
                                //通品
                                $FirstMoney[] = $GoodsType['price'] * $FirstBilitongpin;
                            }
                        }
                    }
                    //总收益 $FirstMoney
                    $RecordedFirstMoney = array_sum($FirstMoney);
                    $FirstUserInfoArray = Db::name('user')->where('id', $FatherUserId)->find();
                    //扣除积分 增加余额
//                    Db::name('user')->where('id', $FatherUserId)->update(
//                        [
////                            'num' => $FirstUserInfoArray['num'] - $RecordedFirstMoney,
//                            'money' => $FirstUserInfoArray['money'] + $RecordedFirstMoney
//                        ]
//                    );
                    //添加用户积分记录
//                    $FirstNumuSql = [
//                        'user_id' => $FatherUserId,
//                        'status' => 0,
//                        'type' => 3,
//                        'num' => $RecordedFirstMoney,
//                        'up_num' => $FirstUserInfoArray['num'] - $RecordedFirstMoney,
//                        'createtime' => time()
//                    ];
//                    Db::name('num')->insert($FirstNumuSql);
                    //添加收益记录
                    $FirstSqlMoney = [
                        'user_id' => $FatherUserId,
                        'money' => $RecordedFirstMoney,
                        'touser_id' => $PayOrderInfo['user_id'],
                        'status' => 0,
                        'type' => 2,
                        'createtime' => time(),
                        'OrderSn' => $PayOrderInfo['OrderSn']
                    ];
                    Db::name('money')->insert($FirstSqlMoney);
                }
                $GroundFatherUserId = Db::name('group')->where('user_id', $FatherUserId)->value('fuser_id');
                if (!empty($GroundFatherUserId)) {
                    //二级分佣
                    //二级精品比例
                    $SecondBiliJingpin = Db::name('bili')->where('type', 1)->value('first');
                    //二级通品比例
                    $SecondBilitongpin = Db::name('bili')->where('type', 2)->value('first');
                    //查询订单详情
                    $SecondOrderConArray = Db::name('order_con')->where('OrderSn', $PayOrderInfo['OrderSn'])->select();
                    if (!empty($SecondOrderConArray)) {
                        foreach ($SecondOrderConArray as $k => $v) {
                            $GoodsType = Db::name('goods')->where('id', $v['Goods_id'])->find();
                            if (!empty($GoodsType)) {
                                if ($GoodsType == 1) {
                                    //精品
                                    $SecondMoney[] = $GoodsType['price'] * $SecondBiliJingpin;
                                } else {
                                    //通品
                                    $SecondMoney[] = $GoodsType['price'] * $SecondBilitongpin;
                                }
                            }
                        }
                        //总收益 $FirstMoney
                        $RecordedSecondMoney = array_sum($SecondMoney);
                        $SecondUserInfoArray = Db::name('user')->where('id', $GroundFatherUserId)->find();
                        //扣除积分 增加余额
//                        Db::name('user')->where('id', $GroundFatherUserId)->update(
//                            [
////                                'num' => $SecondUserInfoArray['num'] - $RecordedSecondMoney,
//                                'money' => $SecondUserInfoArray['money'] + $RecordedSecondMoney
//                            ]
//                        );
//                        //添加用户积分记录
//                        $SecondNumuSql = [
//                            'user_id' => $GroundFatherUserId,
//                            'status' => 0,
//                            'type' => 3,
//                            'num' => $RecordedSecondMoney,
//                            'up_num' => $SecondUserInfoArray['num'] - $RecordedSecondMoney,
//                            'createtime' => time()
//                        ];
//                        Db::name('num')->insert($SecondNumuSql);
                        //添加收益记录
                        $SecondSqlMoney = [
                            'user_id' => $GroundFatherUserId,
                            'money' => $RecordedSecondMoney,
                            'touser_id' => $PayOrderInfo['user_id'],
                            'status' => 0,
                            'type' => 2,
                            'createtime' => time(),
                            'OrderSn' => $PayOrderInfo['OrderSn']
                        ];
                        Db::name('money')->insert($SecondSqlMoney);
                    }
                }
            }
        } catch (Exception $e) {
        }
        echo $pay->success('支付成功');
    }
}