审查视图

app/order/controller/OrderController.php 15.3 KB
1 2
<?php
namespace app\order\controller;
3
use app\coupons\model\CouponModel;
4
use app\order\model\OrderModel;
5 6 7 8 9 10 11 12 13
use cmf\controller\HomeBaseController;
use think\Db;

/**
 * @title 订单模块
 */
class OrderController extends HomeBaseController
{
lihan authored
14
    function _initialize()
15
    {
lihan authored
16
        require_once EXTEND_PATH . '/Payment.php';
17 18
    }
19
    /**
20
     * @title 下单页面
21 22 23 24
     * @description 默认访问接口
     * @author sᴏᴜʟ ᴏғ ᴄɪɴᴅᴇʀ
     * @url /order/Order/confirm
     * @method POST
25 26 27 28
     *
     * @param name:activity_id  type:int require:1 default:19 desc:上一页选中的活动id
     * @param name:schedule_id  type:int require:1 default:68 desc:上一页选中的批次id
     * @param name:num  type:int require:1 default:2 desc:上一页选中的购买数量
29 30 31 32
     */
    public function confirm()
    {
        $request = request();
33 34
        $post = $request->param();
        $coupons = new CouponModel;
lihan authored
35
        $post['num'] = (request()->param('num') == null) ? 1 : request()->param('num');
36 37
        $couponsList = $coupons->orderCoupon($post['activity_id'], $post['schedule_id'], $post['num'], session('user.id'));
        $schedule = Db::name('activity_schedule')
38
            ->field('id as schedule_id,start_time,end_time,maximum,real_join_num,addition_join_num,price')
39 40
            ->where(['activity_id' => $post['activity_id']])
            ->select();
41
        $total = 0;
lihan authored
42
        $choose = [];
43 44 45
        foreach ($schedule as $k => $v) {
            $v['start_time'] = date('Y.m.d', $v['start_time']);
            $v['end_time'] = date('Y.m.d', $v['end_time']);
46
            if ($v['schedule_id'] == $post['schedule_id']) {
lihan authored
47
                $allowMaximum = $v['maximum'] - ($v['real_join_num'] + $v['addition_join_num']);
48
                $total = $v['price'] * $post['num'];
lihan authored
49 50 51 52 53 54
                $choose = [
                    'schedule_id' => $post['schedule_id'],
                    'time_text' => $v['start_time'] . ' 至 ' . $v['end_time'],
                    'num' => $post['num'],
                    'allowMaximum' => $allowMaximum
                ];
55
            }
lihan authored
56 57 58
            unset($v['real_join_num']);
            unset($v['addition_join_num']);
            unset($v['maximum']);
59 60 61
            $schedule[$k] = $v;
        }
        $result = [
62
            'is_first' => Db::name('user')->where(['id' => session('user.id')])->value('is_first'),
63
            'activity' => Db::name('activity')->field('id as activity_id,name, is_down_payment as type')->where(['id' => $post['activity_id']])->find(),
64
            'schedule' => $schedule,
lihan authored
65
            'choose' => $choose,
66 67 68
            'coupons' => $couponsList,
            'down_price' => Db::name('activity')->where(['id' => $post['activity_id']])->value('down_price') * $post['num'],
            'total' => $total
69
        ];
lihan authored
70
        if (request()->isPost()) {
lihan authored
71
            echo json_encode(['data' => $result, 'code' => 20000]);
lihan authored
72 73
            exit();
        } else {
lihan authored
74 75
            require_once EXTEND_PATH . '/WeChatCommon.php';
            $wx = new \WeChatCommon();
lihan authored
76
            return $this->fetch(':confirm', [
lihan authored
77 78
                'data' => $result,
                'js_sdk' => $wx->js_sdk()
lihan authored
79 80
            ]);
        }
81 82 83 84 85 86 87 88 89
    }

    /**
     * @title 提交订单
     * @description 默认访问接口
     * @author sᴏᴜʟ ᴏғ ᴄɪɴᴅᴇʀ
     * @url /order/Order/done
     * @method POST
     *
90 91 92
     * @param name:activity_id  type:int require:1 default:19 desc:活动id
     * @param name:schedule_id  type:int require:1 default:68 desc:批次id
     * @param name:num  type:int require:1 default:2 desc:购买数量
93 94
     * @param name:escort  type:char require:1 default:同行人id字符串(逗号分隔) desc:1,2,3
     * @param name:payment  type:int require:1 default:支付方式 desc:0余额,1微信,2支付宝
95
     * @param name:discount_coupon_id  type:int require:0 default:112 desc:优惠券id
96
     * @param name:room  type:char require:1 default:1 desc:房间信息
97
     * @param name:desc  type:text require:1 default:0 desc:商家备注
98 99 100 101
     */
    public function done()
    {
        $request = request();
102
        if ($request->isPost()) {
103 104 105 106 107 108 109 110 111 112
            $post = $request->param();
            $data['user_id'] = session('user.id');
            $data['order_sn'] = date('YmdHis') . rand(0, 9999);
            $data['activity_id'] = $post['activity_id'];
            $data['schedule_id'] = $post['schedule_id'];
            $data['add_time'] = time();
            $activity = Db::name('activity')->field('is_down_payment,down_price')->where(['id' => $post['activity_id']])->find();
            $data['order_type'] = $activity['is_down_payment'];
            $data['is_use_discount_coupon'] = (empty($post['discount_coupon_id'])) ? 0 : 1;
            $data['discount_coupon_id'] = $post['discount_coupon_id'];
113
            $data['payment'] = $post['payment'];
.  
lihan authored
114
            $data['status'] = 1;
115 116 117
            $data['room'] = $post['room'];
            $data['desc'] = $post['desc'];
            $final_price = $this->getFinalPrice($data['activity_id'], $data['schedule_id'], $post['num'], $data['discount_coupon_id']);
118
            $post['escort'] = substr($post['escort'], 0, strlen($post['escort']) - 1);
.  
lihan authored
119 120 121 122
            if (empty($post['escort'])) {
                echo json_encode(['msg' => '请选择出行人', 'code' => 40000]);
                exit();
            }
123
            $this->checkOrder($data['schedule_id'], $data['payment'], $post['escort'], $post['num'], $final_price);
124 125 126 127 128 129 130 131 132 133 134 135 136
            Db::startTrans();
            if (Db::name('order_info')->insert($data)) {
                $oid = Db::name('order_info')->getLastInsID();
                $detail = [];
                $explode_escort = explode(',', $post['escort']);
                for ($i = 0; $i < $post['num']; $i++) {
                    $detail[$i] = [
                        'oid' => $oid,
                        'escort_id' => $explode_escort[$i],
                        'status' => 0
                    ];
                }
                if (Db::name('order_detail')->insertAll($detail)) {
.  
lihan authored
137 138 139 140 141 142 143 144 145 146 147
                    //☆在这就要将优惠券变为已使用☆
                    if ($data['is_use_discount_coupon'] == 1 && !empty($data['discount_coupon_id'])) {
                        $coupons = [
                            'id' => $post['discount_coupon_id'],
                            'use_time' => time(),
                            'status' => 2
                        ];
                        if (!(Db::name('discount_coupon')->update($coupons))) {
                            Db::rollback();
                        }
                    }
148 149 150 151 152 153 154 155
                    //插入订单记录表(包含订单总价)
                    $log = [
                        'oid' => $oid,
                        'order_amount' => $final_price,
                        'type' => $data['order_type']
                    ];
                    if (Db::name('order_log')->insert($log)) {
                        Db::commit();
.  
lihan authored
156 157
                        //首次下单状态改变
                        Db::name('user')->update(['id' => session('user.id'), 'is_first' => 0]);
lihan authored
158 159

                        //微信支付
.  
lihan authored
160
                        if ($data['payment'] == 1) {
lihan authored
161 162
                            $info = [
                                'attach' => $oid,
lihan authored
163
                                'openid' => session('user.openid'),
lihan authored
164 165 166 167
                                'body' => '萨米户外',
                                'total_fee' => $final_price
                            ];
                            $this->success('微信支付', url('user/Center/orderDetail', ['oid' => $oid]), $this->wxPay($info));
lihan authored
168
                        } //支付宝支付
lihan authored
169 170
                        elseif ($data['payment'] == 2) {
lihan authored
171
                        } //余额支付
lihan authored
172
                        elseif ($data['payment'] == 0) {
.  
lihan authored
173 174
                            $model = new OrderModel;
                            if ($model->orderCallBack($oid)) {
lihan authored
175
                                echo json_encode(['msg' => '下单成功', 'code' => 20000, 'url' => url('user/Center/orderDetail', ['oid' => $oid])]);
.  
lihan authored
176 177 178 179 180
                                exit();
                            } else {
                                echo json_encode(['msg' => '下单失败', 'code' => 40000]);
                                exit();
                            }
181
                        } else {
.  
lihan authored
182
                            echo json_encode(['msg' => '未知错误', 'code' => 40000]);
183
                            exit();
184
                        }
185 186 187 188 189 190 191
                    }
                }
            } else {
                Db::rollback();
                echo json_encode(['msg' => '下单失败', 'code' => 40000]);
                exit();
            }
192
        } else {
.  
lihan authored
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
            echo json_encode(['msg' => '非法操作', 'code' => 40000]);
            exit();
        }
    }

    //个人中心继续付款
    public function done2()
    {
        $request = request();
        if ($request->isPost()) {
            $oid = $request->param('oid');
            $info = Db::name('order_info')->alias('o')
                ->field('status,order_type,a.down_price,s.price')
                ->join('activity a', 'o.activity_id=a.id')
                ->join('activity_schedule s ', 'o.schedule_id=s.id')
                ->where(['o.id' => $oid])->find();
            $num = Db::name('order_detail')->where(['oid' => $oid, 'status' => ['neq', 2]])->count();
            if ($info['status'] == 1) {
                if ($info['order_type'] == 0) {
                    $order_amount = $num * $info['price'];
                } elseif ($info['order_type'] == 1) {
                    $order_amount = $num * $info['down_price'];
                } else {
                    echo json_encode(['msg' => '未知错误', 'code' => 40000]);
                    exit();
                }
            } elseif ($info['status'] == 3) {
                $order_amount = $num * $info['price'];
            } else {
                echo json_encode(['msg' => '未知错误', 'code' => 40000]);
                exit();
            }
lihan authored
225
            //再次支付的支付方式,先更新支付方式
.  
lihan authored
226 227 228 229
            $payment = $request->param('payment');
            Db::name('order_info')->update(['id' => $oid, 'payment' => $payment]);
            if ($payment == 0) {
                $model = new OrderModel;
lihan authored
230 231 232 233 234
                $balance = Db::name('user')->where(['id'=>session('user.id')])->value('balance');
                if($balance < $order_amount) {
                    echo json_encode(['msg' => '您的余额不足', 'code' => 40000]);
                    exit();
                }
.  
lihan authored
235 236 237
                if ($model->orderCallBack($oid, $order_amount)) {
                    //如果是有定金订单,则需要更新order_log
                    if ($info['order_type'] == 1) {
lihan authored
238
                        Db::name('order_log')->where(['oid' => $oid])->update(['order_amount' => $order_amount]);
.  
lihan authored
239
                    }
lihan authored
240
                    echo json_encode(['msg' => '支付成功', 'code' => 20000, 'url' => url('user/Center/orderDetail', ['oid' => $oid])]);
.  
lihan authored
241 242 243 244 245 246
                    exit();
                } else {
                    echo json_encode(['msg' => '支付失败', 'code' => 40000]);
                    exit();
                }
            } elseif ($payment == 1) {
lihan authored
247 248
                $data = [
                    'attach' => $oid,
lihan authored
249
                    'openid' => session('user.openid'),
lihan authored
250 251 252
                    'body' => '萨米户外',
                    'total_fee' => $order_amount
                ];
lihan authored
253 254
                echo json_encode(['msg' => '微信支付', 'data' => $this->wxPay($data), 'code' => 20000, 'url' => url('user/Center/orderDetail', ['oid' => $oid])]);
                exit();
.  
lihan authored
255
            } elseif ($payment == 2) {
lihan authored
256
                echo json_encode(['msg' => '支付宝支付', 'code' => 20000]);
.  
lihan authored
257 258 259 260 261
            } else {
                echo json_encode(['msg' => '未知错误', 'code' => 40000]);
                exit();
            }
        } else {
262 263
            echo json_encode(['msg' => '非法操作', 'code' => 40000]);
            exit();
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
    /**
     * 计算订单最终价格
     * @param $activityId
     * @param $scheduleId
     * @param $num
     * @param null $discountCouponId
     * @return float|int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getFinalPrice($activityId, $scheduleId, $num, $discountCouponId = null)
    {
        $info = Db::name('activity')->field('is_down_payment,down_price')->where(['id' => $activityId])->find();
        //如果有定金则支付定金*数量
        if ($info['is_down_payment'] == 1) {
            $sum = $info['down_price'] * $num;
        } //如果没有定金则支付批次金额*数量
        else {
            $price = Db::name('activity_schedule')->where(['activity_id' => $activityId, 'id' => $scheduleId])->value('price');
            $sum = $price * $num;
        }
        //如果有使用优惠券
        if (!empty($discountCouponId)) {
            //判断该优惠券是否已使用
            $coupons = Db::name('discount_coupon')->field('status,reduce,overflow')->where(['id' => $discountCouponId])->find();
            if ($coupons['status'] == 1) {
                //是否符合满减
                if ($sum >= $coupons['overflow']) {
                    $sum -= $coupons['reduce'];
                }
            }
        }
        return $sum;
    }
303 304 305 306 307 308 309 310
    /**
     * 订单校验
     * @param $scheduleId
     * @param int $payment
     * @param $escort
     * @param $num
     * @param $finalPrice
     */
311 312
    private function checkOrder($scheduleId, $payment = 0, $escort, $num, $finalPrice)
    {
lihan authored
313
        if ($scheduleId == null) {
314
            echo json_encode(['msg' => '请选择活动批次', 'code' => 40000]);
315 316 317 318 319 320 321 322 323 324 325 326 327
            exit();
        }
        //判断活动是否过期
        if (Db::name('activity_schedule')->where(['id' => $scheduleId])->value('deadline') < time()) {
            echo json_encode(['msg' => '本次活动已过期,请重新选择', 'code' => 40000]);
            exit();
        }
        //判断出行人与购买数量是否匹配
        $escortNum = (strlen($escort) == 1) ? 1 : count(explode(',', $escort));
        if ($escortNum != $num) {
            echo json_encode(['msg' => '购买数量需与出行人数量一致', 'code' => 40000]);
            exit();
        }
328 329 330 331 332 333
        //判断支付方式
        if (($payment != 0 && $payment != 1 && $payment != 2 && $payment) || $payment == null) {
            echo json_encode(['msg' => '请选择支付方式', 'code' => 40000]);
            exit();
        }
        //判断用户余额能否支持余额支付
lihan authored
334
        if ($payment == 0) {
lihan authored
335 336 337 338
            if (Db::name('user')->where(['id' => session('user.id')])->value('balance') < $finalPrice) {
                echo json_encode(['msg' => '您的余额不足,请选择其他支付方式', 'code' => 40000]);
                exit();
            }
339
        }
340 341
    }
lihan authored
342 343 344
    //微信支付
    private function wxPay($info)
    {
lihan authored
345
        $pay = new \Payment($info['attach'], $info['openid'], $info['body'], 1/*$info['total_fee'] * 100*/);
lihan authored
346
        return $pay->pay();
lihan authored
347 348
    }
lihan authored
349 350
    public function notify()
    {
lihan authored
351
        $pay = new \Payment();
lihan authored
352 353 354 355 356
        $return = $pay->handleNotify();
        if(!empty($return)) {
            $order = new OrderModel;
            $order->orderCallBack($return['attach'], $return['total_fee']);
        }
lihan authored
357 358
    }
359
}