PayController.php 12.9 KB
<?php
namespace app\pay\controller;
use cmf\controller\PayBaseController;
use app\integral\model\IntegralModel;
use think\Db;

class PayController extends PayBaseController
{

    //提交订单
    public function done()
    {
        $request = request();
        $data = [];
        if ($request->isAjax()) {
            if (empty($request->param('address_id'))) {
                $this->success('请填写配送地址', '', false);
            }
            if (empty($request->param('pay_type'))) {
                $this->success('请选择支付方式', '', false);
            }
            $consignee = Db::name('zj_user_place')->field('name,province,city,county,mobile,place')
                ->where(['id' => $request->param('address_id'), 'uid' => session('user.id')])
                ->find();
            if (session('cart.id') != null && session('goods.id') == null) {
                //通过购物车
                $data = Db::name('zj_cart')->alias('c')
                    ->join('zj_goods g', 'c.gid=g.id')
                    ->field('c.num,g.price,g.id')
                    ->where(['c.uid' => session('user.id'), 'c.id' => ['in', session('cart.id')]])
                    ->select();
            } elseif (session('cart.id') == null && session('goods.id') != null) {
                //直接购买
                $data = Db::name('zj_goods')
                    ->field('price,id')
                    ->where(['id' => session('goods.id')])
                    ->select();
            } else {
                $this->success('您已下过该订单', '', false);
            }
            $whole = 0;
            $orderGoods = [];
            foreach ($data as $item) {
                if (session('cart.id') == null && session('goods.id') != null) {
                    $item['num'] = 1;
                }
                $whole += $item['num'] * $item['price'];
            }
            if ($request->param('pay_type') == 2) {
                $whole_num = $request->param('pay_num');
            } elseif ($request->param('pay_type') == 1) {
                $whole_num = 0;
            } else {
                $whole_num = $whole;
            }
            $sn = date('YmdHis') . rand(100000, 999999);
            $order = [
                'order_num' => $sn,
                'step' => 1,
                'uid' => session('user.id'),
                'site' => $consignee['province'] . $consignee['city'] . $consignee['county'] . $consignee['place'],
                'name' => $consignee['name'],
                'mobile' => $consignee['mobile'],
                'remark' => $request->param('remark'),
                'create_time' => time(),
                'whole' => $whole,
                'whole_num' => $whole_num,
                'pay_type' => $request->param('pay_type'),
                'step' => 1,
                //购买同时加入一级分类,用于判断是否赠送积分用
                'cid' => $request->param('cid'),
                //二级分类字符串-1-,-2-,-3-
                'cids' => $this->getSonCategoryStr($data),
                'province' => $consignee['province'],
                'city' => $consignee['city'],
                'county' => $consignee['county'],
                'place' => $consignee['place']
            ];
            Db::startTrans();
            if (Db::name('zj_order')->insert($order)) {
                $oid = Db::name('zj_order')->getLastInsID();
                foreach ($data as $k => $v) {
                    if (session('cart.id') == null && session('goods.id') != null) {
                        $v['num'] = 1;
                    }
                    $orderGoods[$k] = [
                        'oid' => $oid,
                        'gid' => $v['id'],
                        'num' => $v['num'],
                        'price' => Db::name('zj_goods')->where(['id' => $v['id']])->value('price')
                    ];
                }
                if (Db::name('zj_order_goods')->insertAll($orderGoods)) {
                    //微信支付
                    if ($order['pay_type'] == 1) {
                        Db::commit();
                        session('goods.id', null);
                        Db::name('zj_cart')->where(['id' => ['in', session('cart.id')]])->delete();
                        session('cart.id', null);
                        $info = [
                            'attach' => $oid,
                            'openid' => session('user.openid'),
                            'body' => '微信支付-天生红商城',
                            'total_fee' => $order['whole']
                        ];
                        $this->wxPay($info);
                    } //积分支付
                    elseif ($order['pay_type'] == 3) {
                        //先判断剩余积分是否足够支付
                        $balance = Db::name('user')->where(['id' => session('user.id')])->value('balance');
                        if ($balance < $whole) {
                            Db::rollback();
                            $this->success('您的积分不足', '', false);
                        } else {
                            //先减积分
                            $balance -= $whole;
                            if (Db::name('user')->update(['id' => session('user.id'), 'balance' => $balance])) {
                                //记录积分日志
                                $model = new IntegralModel;
                                $model->insertIntegralLog('', session('user.id'), time(), $whole, 2, '', $sn);
                                //支付后改变订单状态
                                $update = [
                                    'id' => $oid,
                                    'step' => 2,
                                    'pay_time' => time()
                                ];
                                if (Db::name('zj_order')->update($update)) {
                                    Db::commit();
                                    session('goods.id', null);
                                    Db::name('zj_cart')->where(['id' => ['in', session('cart.id')]])->delete();
                                    session('cart.id', null);
                                    $this->success('积分支付成功', url('user/Center/orderList'), true);
                                } else {
                                    Db::rollback();
                                }
                            } else {
                                Db::rollback();
                            }
                        }
                    } //组合支付
                    elseif ($order['pay_type'] == 2) {
                        $pay_cash = $request->param('pay_cash');    //支付的金额
                        $pay_num = $request->param('pay_num');      //支付的积分
                        $balance = Db::name('user')->where(['id' => session('user.id')])->value('balance');
                        if ($pay_cash > $balance) {
                            $this->success('您的积分不足', '', false);
                        } else {
                            //先减余额
                            $balance -= $pay_num;
                            Db::name('user')->update(['id' => session('user.id'), 'balance' => (int)$balance]);
                            //记录积分日志
                            $model = new IntegralModel;
                            $model->insertIntegralLog('', session('user.id'), time(), $pay_num, 2, '', $sn);
                            Db::commit();
                            session('goods.id', null);
                            Db::name('zj_cart')->where(['id' => ['in', session('cart.id')]])->delete();
                            session('cart.id', null);
                            $info = [
                                'attach' => $oid,
                                'openid' => session('user.openid'),
                                'body' => '微信支付-天生红商城',
                                'total_fee' => $pay_cash
                            ];
                            $this->wxPay($info);
                        }
                    } else {
                        $this->success('请选择支付方式', '', false);
                    }
                } else {
                    Db::rollback();
                    $this->success('未知错误', '', false);
                }
            } else {
                Db::rollback();
                $this->success('未知错误', '', false);
            }
        }
    }


    //个人中心微信支付
    public function payFromCenter()
    {
        $request = request();
        if ($request->isAjax()) {
            $oid = $request->param('oid');
            $total_fee = Db::name('zj_order')->where(['id' => $oid])->value('whole');
            if (Db::name('zj_order')->where(['id' => $oid])->value('pay_type') == 2) {
                $total_fee -= Db::name('zj_order')->where(['id' => $oid])->value('whole_num');
            }
            $info = [
                'attach' => $oid,
                'openid' => session('user.openid'),
                'body' => '微信支付-天生红商城',
                'total_fee' => $total_fee
            ];
            $this->wxPay($info);
        }
    }

    private function wxPay($info)
    {
        //只有未支付的订单才能唤起微信支付
        if (Db::name('zj_order')->where(['id' => $info['attach']])->value('step') == 1) {
            require_once EXTEND_PATH . '/Payment.php';
            $pay = new \Payment($info['attach'], $info['openid'], $info['body'], $info['total_fee'] * 100);
            $this->success('ok', url('user/center/orderList'), $pay->pay());
        } else {
            $this->success('该订单禁止支付', '', false);
        }
    }

    public function notify()
    {
        require_once EXTEND_PATH . '/Payment.php';
        $pay = new \Payment();
        $notify = $pay->handleNotify();
        if (!empty($notify)) {
            $oid = $notify['attach'];
            if (Db::name('zj_order')->where(['id' => $oid])->value('step') == 2) {
                echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                exit();
            } else {
                //改变订单状态
                $update = [
                    'id' => $oid,
                    'step' => 2,
                    'out_trade_no' => $notify['out_trade_no'],
                    'pay_time' => time()
                ];
                if (Db::name('zj_order')->update($update)) {
                    //赠送积分逻辑
                    $this->integral($oid);
                    echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    exit();
                }
            }
        }
    }

    //赠送积分模块
    private function integral($oid)
    {
        //判断该订单是否属于赠送积分订单
        $info = Db::name('zj_order')->field('uid,step,cid,pay_type')->where(['id' => $oid])->find();
        if ($info['cid'] == 2 && $info['step'] == 2) {
            if ($info['pay_type'] == 1 || $info['pay_type'] == 2) {
                //计算该笔订单应给积分总额
                $data = Db::name('zj_order_goods')->alias('o')
                    ->field('g.price,o.num')
                    ->join('zj_goods g', 'g.id=o.gid')
                    ->where(['oid' => $oid])
                    ->select();
                $integral = 0;
                foreach ($data as $item) {
                    $integral += $item['price'] * $item['num'] * 1.5;
                }

                $ratio = Db::name('zj_system')->where(['id' => 1])->value('integral');
                $model = new IntegralModel;

                //插入配送计划表,先将此积分的一半立刻给用户,剩余一半每日按固定百分比给用户,直到发完为止
                $integral_half = $integral / 2;
                Db::startTrans();
                $integral_give_id = $model->insertIntegralGive($info['uid'], $ratio, $integral_half, $integral_half, time());
                if ($integral_give_id) {
                    if ($model->insertIntegralLog($integral_give_id, $info['uid'], time(), $integral_half, 1)) {
                        if (Db::name('user')->where(['id' => $info['uid']])->setInc('balance', $integral_half)) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    } else {
                        Db::rollback();
                    }
                } else {
                    Db::rollback();
                }
            }
        }
    }

    //获取购买商品的二级分类字符串
    private function getSonCategoryStr($data)
    {
        $str = '';
        foreach ($data as $item) {
            $str .= '-' . Db::name('zj_goods')->where(['id' => $item['id']])->value('cid') . '-,';
        }
        return substr($str, 0, strlen($str) - 1);
    }

}