Ejemplo n.º 1
0
    def post(self, request):

        res = BaseResponse()
        # 1.取值
        course_id = request.data.get('courseId')
        price_policy_id = request.data.get('validPeriodId')

        user_id = request.user.pk

        # 2.校验数据
        try:
            course_obj = Course.objects.get(pk=course_id)
            relate_price_police = course_obj.price_policy.all()
            if price_policy_id not in [obj.pk for obj in relate_price_police]:
                raise CommonException(1002, '价格策略非法')
            # 3.存到缓存
            # 3.1 构建redis的键
            shoppingcar_key = settings.SHOPPINGCAR_REDIS_KEY % (user_id,
                                                                course_id)
            # 3.2 构建redis的值-shoppingcar_val
            relate_price_policy_dict = {}
            for price_policy in relate_price_police:
                relate_price_policy_dict[price_policy.pk] = {
                    'pk': price_policy.pk,
                    'valid_period': price_policy.valid_period,
                    'valid_period_text':
                    price_policy.get_valid_period_display(),
                    'price': price_policy.price,
                    'default': False,
                }
            relate_price_policy_dict[price_policy_id]['default'] = True
            shoppingcar_val = {
                'id':
                course_obj.id,
                'title':
                course_obj.name,
                'img':
                course_obj.course_img,
                'relate_price_policy':
                relate_price_policy_dict,
                'choosen_price_policy_id':
                price_policy_id,
                'choosen_price':
                relate_price_policy_dict[price_policy_id]['price'],
                'choosen_valid_period':
                relate_price_policy_dict[price_policy_id]['valid_period'],
                'choosen_valid_period_text':
                relate_price_policy_dict[price_policy_id]['valid_period_text'],
            }
            cache.set(shoppingcar_key, json.dumps(shoppingcar_val))
            res.data = '加入购物车成功'
        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = '提交异常,课程对象不存在!'
        except CommonException as e:
            res.code = e.code
            res.msg = e.msg
        return Response(res.dict)
Ejemplo n.º 2
0
    def post(self, request):
        """
        模拟请求数据:
        {
            "course_id_list":[1, 2]
        }
        :param request:
        :return:
        """

        # 1 获取请求数据
        course_id_list = request.data.get("course_id_list")
        user_id = request.user.pk
        res = BaseResponse()

        # 2.校验数据
        try:
            # 2.1 校验课程是否存在
            for course_id in course_id_list:  # 结算情况: 1. 直接购买 2.购物车购买

                # 结算 key
                account_key = settings.ACCOUNT_KEY % (user_id, course_id)
                # 结算字典
                account_val = {}

                # 获取课程基本信息
                shoppingcar_key = settings.SHOPPINGCAR_KEY % (user_id,
                                                              course_id)
                course_obj = Course.objects.get(pk=course_id)
                course_info = json.loads(cache.get(shoppingcar_key))

                # 添加到结算字典中
                account_val["course_info"] = course_info

                # 获取优惠卷信息:查询当前用户的当前课程的有效的未使用的优惠卷
                coupons = self.get_coupon_dict(request, course_id)
                # 将优惠卷字典添加到结算字典中
                account_val["coupons"] = coupons
                print("account_val", type(account_val))

                cache.set(account_key, json.dumps(account_val))

            # 获取通用优惠卷
            global_coupons = self.get_coupon_dict(request)
            cache.set("global_coupons_%s" % user_id,
                      json.dumps(global_coupons))

        except CommonException as e:
            res.code = e.code
            res.msg = "课程不存在"

        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在"

        return Response(res.dict)
Ejemplo n.º 3
0
    def post(self, request):
        response = BaseResponse()

        receive = request.data
        if request.method == 'POST':
            print(receive)
            is_valid = verify(receive)
            print("is_valid", is_valid)
            if is_valid:

                username = receive.get("username")
                password = receive.get("password")
                user = auth.authenticate(username=username, password=password)
                # 用户名+密码验证成功
                if user is not None:
                    # update the token
                    key = self.generate_key()
                    from django.utils.timezone import utc
                    import datetime
                    now = datetime.datetime.now()
                    Token.objects.update_or_create(user=user,
                                                   defaults={
                                                       "key": key,
                                                       "created": now
                                                   })
                    user_info = UserInfo.objects.get(pk=user.pk)
                    serializer = UserInfoSerializer(user_info)
                    data = serializer.data

                    response.msg = "验证成功!"
                    response.userinfo = data
                    response.token = key

                # 用户名+密码匹配失败
                else:
                    # 只匹配用户名
                    try:
                        UserInfo.objects.get(username=username)
                        response.msg = "密码错误!"
                        response.code = 1002
                    except UserInfo.DoesNotExist:
                        response.msg = "用户不存在!"
                        response.code = 1003
            else:

                response.code = 1001
                response.msg = "请完成滑动验证!"

            return Response(response.dict)
Ejemplo n.º 4
0
    def post(self, request):
        res = BaseResponse()
        try:
            # 1 获取前端传过来的course_id 以及price_policy_id user_id
            course_id = request.data.get("course_id", "")
            price_policy_id = request.data.get("price_policy_id", "")
            user_id = request.user.id
            # 2 验证数据的合法性
            # 2.1 验证course_id是否合法
            course_obj = Course.objects.get(pk=course_id)
            # 2.2 校验价格策略是否能合法

            # 查找课程关联的价格策略
            price_policy_list = course_obj.price_policy.all()
            price_policy_dict = {}
            for price_policy in price_policy_list:
                price_policy_dict[price_policy.pk] = {
                    "prcie": price_policy.price,
                    "valid_period": price_policy.valid_period,
                    "valid_period_text":
                    price_policy.get_valid_period_display(),
                    "default": price_policy.pk == price_policy_id
                }

            if price_policy_id not in price_policy_dict:
                raise CommonException(1001, "价格策略异常!")

                # 3 构建我们想要的数据结构
                # 价格策略对象
            pp = PricePolicy.objects.get(pk=price_policy_id)
            course_info = {
                "id": course_id,
                "name": course_obj.name,
                "course_img": course_obj.course_img,
                "relate_price_policy": price_policy_dict,
                "default_price": pp.price,
                "default_price_period": pp.valid_period,
                "default_price_policy_id": pp.pk
            }

            # 4 写入redis
            # 4.1 先拼接购物车的key
            shopping_car_key = settings.SHOPPING_CAR_KEY % (user_id, course_id)
            # 4.2 写入redis
            print("------>")
            REDIS_CONN.set(shopping_car_key, json.dumps(course_info))
            res.msg = "加入购物车成功!"

        except CommonException as e:
            res.code = e.code
            res.error = e.error
        except Exception as e:
            res.code = 1030
            res.error = "加入购物车失败!"

        return Response(res.dict)
Ejemplo n.º 5
0
 def destroy(self, request, *args, **kwargs):
     response = BaseResponse()
     try:
         course_id = request.query_params.get('course_id')
         key = settings.SHOPPING_CAR_KEY % (request.user.pk, course_id)
         redis = get_redis_connection()
         redis.delete(key)
         response.msg = "删除成功"
     except Exception as e:
         response.data = 1006
         response.error = "删除不成功"
     return Response(response.dict)
Ejemplo n.º 6
0
    def create(self, request, *args, **kwargs):
        response = BaseResponse()
        try:
            user_id = request.user.pk  # auth_class中传过来的 token.user, token.token
            course_id = request.data.get("course_id")
            price_policy_id = request.data.get("price_policy_id")

            course_obj = Course.objects.get(pk=course_id)  #第一次可能报错

            price_policy_list = course_obj.price_policy.all()
            price_policy_dict = {}
            for price_policy_obj in price_policy_list:
                price_policy_dict[price_policy_obj.pk] = {
                    'price':
                    price_policy_obj.price,
                    "valid_period":
                    price_policy_obj.valid_period,
                    "valid_period_text":
                    price_policy_obj.get_valid_period_display(),
                }
            print(price_policy_id)
            print(price_policy_dict)
            if price_policy_id not in price_policy_dict:  #第二次可能报错
                raise PriceDoseNotExist

            # redis = get_redis_connection("default")
            shopping_car_key = settings.SHOPPING_CAR_KEY % (user_id, course_id)
            course_info = {
                'name': course_obj.name,
                "course_img": course_obj.course_img,
                "price_policy_dict": json.dumps(price_policy_dict),
                "default_price_policy_id": price_policy_id
            }
            # print(shopping_car_key)
            # print(course_info)
            redis.hmset(shopping_car_key, course_info)
            print(redis.hgetall('shopping_car_1_1'))
            # for key,val in redis.hgetall("shopping_car_1_1").items():
            #     print(key.decode('utf-8'),':',val.decode('utf-8'))
            response.msg = "成功加入购物车"

        except ObjectDoesNotExist as e:
            response.code = 1002
            response.error = "没有该课程"

        except PriceDoseNotExist as e:
            response.code = 1003
            response.error = e.error
        except Exception as e:
            response.code = 1004
            response.error = str(e)
        return Response(response.dict)
Ejemplo n.º 7
0
def get_pay_url(request):
    res = BaseResponse()
    order_number = request.GET.get("order_number")
    final_price = request.GET.get("final_price")
    stat = Order.objects.filter(order_number=order_number,
                                actual_amount=float(final_price))
    if stat:
        pay_url = ali_api.pay.get_pay_url(out_trade_no=order_number,
                                          total_amount=final_price,
                                          subject="test")
        res.data = {"pay_url": pay_url}
    else:
        res.code = 1402
        res.msg = '订单不存在'
    return JsonResponse(res.dict)
Ejemplo n.º 8
0
    def get(self, request):
        '''
        :param request:
        :return: ret_dict==.> ret_dict['data']为购物车列表信息
        '''
        res = BaseResponse()
        try:
            added_goods_list = []
            shopping_car_list = []
            user_id = request.user.id
            shoppingcar_key_pattern = settings.SHOPPINGCAR_REDIS_KEY % (
                user_id, '*')
            shoppingcar_key_list = cache.keys(shoppingcar_key_pattern)

            for shoppingcar_key in shoppingcar_key_list:
                goods_obj_info = json.loads(cache.get(shoppingcar_key))
                added_goods_list.append(goods_obj_info)
                '''
                    # 转换格式  将缓存中的数据格式转换成目标格式然后添加到shopping_car_list中
                    # shopping_car_item_dict = {}
                    # shopping_car_item_dict['id'] = shoppingcar_key
                    # shopping_car_item_dict['default_price_period'] = goods_obj_info['choosen_price_policy_id']
                    # shopping_car_item_dict['relate_price_policy'] = goods_obj_info['relate_price_policy']
                    # shopping_car_item_dict['name'] = goods_obj_info['title']
                    # shopping_car_item_dict['course_img'] = goods_obj_info['img']
                    # shopping_car_item_dict['default_price'] = goods_obj_info['choosen_price']
               
                '''
                shopping_car_list.append(goods_obj_info)
            # 存入data
            res.data = {
                "shopping_car_list": shopping_car_list,
                "total": len(shopping_car_list)
            }
        except Exception as e:
            res.code = 1033
            res.msg = '获取购物车数据失败'
        return Response(res.dict)
Ejemplo n.º 9
0
    def post(self, request):
        '''
        状态码:
             1000: 成功
             1001: 课程不存在

        模拟请求数据:
        {
          "course_id":1,
          "price_policy_id":2
        }
        '''
        # 1 获取请求数据
        course_id = request.data.get('course_id')
        price_policy_id = request.data.get('price_policy_id')
        user_id = request.user.pk
        res = BaseResponse()

        try:
            # 2 校验数据
            # 2.1 校验课程是否存在
            course_obj = Course.objects.get(pk=course_id)
            # 2.2 校验价格策略是否合法
            price_policy_dict = {}
            for price_policy in course_obj.price_policy.all():
                price_policy_dict[price_policy.pk] = {
                    'pk': price_policy.pk,
                    'valid_period': price_policy.valid_period,
                    'valid_period_text': price_policy.get_valid_period_display(),
                    'price': price_policy.price,
                    'default': price_policy_id == price_policy.pk
                }
            if price_policy_id not in price_policy_dict:
                raise CommonException(1002, '价格策略错误!')
            pp = PricePolicy.objects.get(pk=price_policy_id)

            # 3 写入redis
            shoppingcart_key = settings.SHOPPINGCART_KEY%(user_id,course_id)
            shoppingcart_val = {
                'title': course_obj.name,
                'img': course_obj.course_img,
                'relate_price_policy': price_policy_dict,
                'choose_price_policy_id': price_policy_id,
                'price': pp.price,
                'valid_period': pp.valid_period,
                'valid_period_text': pp.get_valid_period_display()
            }

            cache.set(shoppingcart_key, json.dumps(shoppingcart_val))
            res.data = "加入购物车成功!"

            '''
            REDIS={
                  shoppingcart_1_1:{
                          "title":"....",
                          "img":"...."
                      }
                      
                  shoppingcart_1_2:{
                          "title":"....",
                          "img":"...."
                      }
            '''
        except CommonException as e:
            res.code = e.code
            res.msg = e.msg
        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在"
        return Response(res.dict)
Ejemplo n.º 10
0
    def post(self, request, *args, **kwargs):
        print(request.data)
        response = BaseResponse()
        # 1 获取数据
        user_id = request.user.pk
        global_coupon_id = request.data.get("global_coupon_id")
        pay_money = request.data.get("pay_money")
        course_list = request.data.get("course_list")
        is_beli = request.data.get("is_beli")
        now = datetime.datetime.now()
        try:
            # 2 校验数据
            # 2.2 校验课程
            course_price_list = []
            for course_dict in course_list:
                # 2.2.1 校验课程id

                course_id = course_dict.get("course_id")
                print("course_id",course_id)
                course_obj = Course.objects.get(pk=course_id)
                # 2.2.2 价格策略id
                if course_dict.get("default_price_policy_id") not in [obj.pk for obj in course_obj.price_policy.all()]:
                    raise CommonException("价格策略异常!", 1002)
                # 2.2.3 课程优惠券id

                price_policy_obj = PricePolicy.objects.get(pk=course_dict.get("default_price_policy_id"))
                course_dict["original_price"]=price_policy_obj.price
                course_dict["valid_period_display"]=price_policy_obj.get_valid_period_display()
                course_dict["valid_period"]=price_policy_obj.valid_period
                coupon_record_id = course_dict.get("coupon_record_id")
                if coupon_record_id:

                    coupon_record_list = CouponRecord.objects.filter(account=request.user,
                                                                     status=0,
                                                                     coupon__valid_begin_date__lt=now,
                                                                     coupon__valid_end_date__gt=now,
                                                                     coupon__content_type_id=14,
                                                                     coupon__object_id=course_id
                                                                     )
                    print("coupon_record_id",coupon_record_id)

                    if coupon_record_id and coupon_record_id not in [obj.pk for obj in coupon_record_list]:
                        raise CommonException("课程优惠券异常!", 1006)

                    # 计算循环课程的课程优惠券优惠后的价格
                    coupon_record_obj = CouponRecord.objects.get(pk=coupon_record_id)
                    rebate_price = self.cal_coupon_price(price_policy_obj.price, coupon_record_obj)
                    course_price_list.append(rebate_price)
                    course_dict["rebate_price"]=rebate_price
                else:
                    course_price_list.append(price_policy_obj.price)

            # 2.3 校验通用优惠券id
            global_coupon_record_list = CouponRecord.objects.filter(account=request.user,
                                                                    status=0,
                                                                    coupon__valid_begin_date__lt=now,
                                                                    coupon__valid_end_date__gt=now,
                                                                    coupon__content_type_id=14,
                                                                    coupon__object_id=None
                                                                    )
            if global_coupon_id and global_coupon_id not in [obj.pk for obj in global_coupon_record_list]:
                raise CommonException("通用优惠券异常", 1006)

            if global_coupon_id:
                global_coupon_record_obj = CouponRecord.objects.get(pk=global_coupon_id)
                final_price = self.cal_coupon_price(sum(course_price_list), global_coupon_record_obj)
            else:
                final_price=sum(course_price_list)
            # 2.4 计算实际支付价格与money做校验
            cost_beli_num=0
            if is_beli:
                final_price = final_price - request.user.beli / 10
                cost_beli_num=request.user.beli
                if final_price < 0:
                    final_price = 0
                    cost_beli_num=final_price*10
                print(final_price)

            if final_price != float(pay_money):
                raise CommonException(1008, "支付总价格异常!")

            # 3 生成订单记录
            # Order记录
            # orderDetail
            # orderDetail
            # orderDetail
            order_number=self.get_order_num()
            print("order_number",order_number)
            order_obj=Order.objects.create(
                payment_type=1,
                order_number=order_number,
                account=request.user,
                status=1,
                order_type=1,
                actual_amount=pay_money,
            )
            print("course_list",course_list)

            for course_item in course_list:
                OrderDetail.objects.create(
                    order=order_obj,
                    content_type_id=14,
                    object_id=course_item.get("course_id"),
                    original_price=course_item.get("original_price"),
                    price=course_item.get("rebate_price") or course_item.get("original_price"),
                    valid_period=course_item.get("valid_period"),
                    valid_period_display=course_item.get("valid_period_display"),
                )

            request.user.beli=request.user.beli-cost_beli_num
            request.user.save()
            REDIS_CONN.set(order_number+"|"+str(cost_beli_num),"",20)
            account_key=settings.ACCOUNT_KEY%(user_id,"*")
            REDIS_CONN.delete(*REDIS_CONN.keys(account_key))
            '''
               [
                  {  course_id:1
                     default_price_policy_id:1,
                     coupon_record_id:2
                   },
                  {
                     course_id:2
                     default_price_policy_id:4,
                     coupon_record_id:6
                   }
               ]
            '''


            response.data = self.get_pay_url(request,order_number,final_price)

        except ObjectDoesNotExist as e:
            response.code = 1001
            response.msg = "课程不存在!"
        except CommonException as e:
            response.code = e.code
            response.msg = e.error
        except Exception as e:
            response.code = 500
            response.msg = str(e)

        return Response(response.dict)
Ejemplo n.º 11
0
    def post(self, request):
        '''
           request.data=>course_list=[{
                             "course_id":1,
                             "price_policy_id":2
                           },
        '''
        # self.dispatch()
        res = BaseResponse()
        # 1.取值
        course_list = request.data
        user_id = request.user.id
        # 2.校验数据
        try:
            del_list = cache.keys(settings.ACCOUNT_REDIS_KEY % (user_id, "*"))
            if del_list:
                cache.delete(*del_list)
            price_list = []
            for course_dict in course_list:

                course_id = course_dict.get("course_id")
                price_policy_id = course_dict.get("price_policy_id")
                # 校验课程是否存在
                course_obj = Course.objects.get(pk=course_id)
                # 查找课程关联的价格策略
                price_policy_list = course_obj.price_policy.all()
                price_policy_dict = {}
                for price_policy in price_policy_list:
                    price_policy_dict[price_policy.pk] = {
                        "prcie":
                        price_policy.price,
                        "valid_period":
                        price_policy.valid_period,
                        "valid_period_text":
                        price_policy.get_valid_period_display(),
                        "default":
                        price_policy.pk == price_policy_id
                    }

                if price_policy_id not in price_policy_dict:
                    raise CommonException(1001, "价格策略异常!")
                pp = PricePolicy.objects.get(pk=price_policy_id)
                # 将课程信息加入到每一个课程结算字典中
                account_dict = {
                    "id": course_id,
                    "name": course_obj.name,
                    "course_img": course_obj.course_img,
                    "relate_price_policy": price_policy_dict,
                    "default_price": pp.price,
                    "rebate_price": pp.price,
                    "default_price_period": pp.valid_period,
                    "default_price_policy_id": pp.pk
                }
                # 课程价格加入到价格列表
                price_list.append(float(pp.price))

                # 查询当前用户拥有未使用的,在有效期的且与当前课程相关的优惠券
                account_dict["coupon_list"] = self.get_coupon_list(
                    request, course_id)

                # 存储结算信息
                account_key = settings.ACCOUNT_REDIS_KEY % (user_id, course_id)
                cache.set(account_key, json.dumps(account_dict))

            # 获取通用优惠券,加入redis中
            cache.set("global_coupon_%s" % user_id,
                      json.dumps(self.get_coupon_list(request)))
            cache.set("total_price", sum(price_list))
        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = '提交异常,课程对象不存在!'
        except CommonException as e:
            res.code = e.code
            res.msg = e.msg
        except Exception as e:
            print(e)
        return Response(res.dict)
Ejemplo n.º 12
0
    def post(self, request):
        print(request.data)
        """
        状态码:
            1000:成功
            1001:课程不存在
            1002:价格策略错误
        :return:

        模拟请求数据
        {
        "course_id":1,
        "prcie_policy_id":2
        }
        """
        # 1.获取请求数据
        course_id = request.data.get("course_id")
        price_policy_id = request.data.get("price_policy_id")

        # 在liginAuth 里面讲
        user_id = request.user.pk
        # 实例化一个响应类
        res = BaseResponse()

        # 2 校验数据(这里yuan先生try的,)
        '''
        我这样写有很多分支,而且还得总返回一个字典,yuan先生抛异常这个好,学习
        '''
        # if course_id not in [obj.pk for obj in Course.objects.all()]:
        #     res.code=1001auth_permission
        #     res.data="课程不存在"
        #
        # else:
        try:
            # 2.1效验课程数据
            course_obj = Course.objects.get(pk=course_id)
            # 2.2 效验价格策略数据
            price_policy_dict = {}
            for price_policy in course_obj.price_policy.all():
                price_policy_dict[price_policy.pk] = {
                    "pk": price_policy.pk,
                    "valid_period": price_policy.valid_period,
                    "valid_period_text":
                    price_policy.get_valid_period_display(),
                    "price": price_policy.price,
                    # 为了前端默认显示
                    "default": int(price_policy_id) == price_policy.pk
                }
                print(price_policy_id, price_policy.pk)
            print(price_policy_dict)
            #  因为有课程策略的替换,而且还有默认值显示 所以需要将价格策略全部存储起来,然后还需要当前价格策略id设置默认显示
            if int(price_policy_id) not in price_policy_dict:
                print(type(price_policy_id))
                print([obj.pk for obj in course_obj.price_policy.all()])

                raise CommonException("1002", "价格策略错误")
            price_policy_obj = PricePolicy.objects.filter(
                pk=price_policy_id).first()
            """
             # 想要购建的数据结构
              REDIS={

                  shoppingcar_1_1:{
                          "title":"....",
                          "img":"...."
                      }

                  shoppingcar_1_2:{
                          "title":"....",
                          "img":"...."
                      }



              }
            """

            # 3 写进redis 中
            # 哪个用户的哪个课程
            pp = PricePolicy.objects.get(pk=price_policy_id)
            shoppingcar_key = settings.SHOPPING_CAR_KEY % (user_id,
                                                           course_obj.pk)
            shoppingcar_val = {
                "id":
                course_obj.pk,
                "default_price_period":
                PricePolicy.objects.filter(
                    pk=price_policy_id).first().valid_period,
                "title":
                course_obj.name,
                "img":
                course_obj.course_img,
                "relate_price_policy":
                price_policy_dict,
                "choose_price_policy_id":
                price_policy_id,
                "default_price":
                pp.price,
                "valid_period":
                price_policy_obj.valid_period,
                "valid_period_text":
                price_policy_obj.get_valid_period_display(),
            }
            print(shoppingcar_key, shoppingcar_val)
            r.set(shoppingcar_key, json.dumps(shoppingcar_val))

        except CommonException as e:
            res.code = e.code
            res.msg = e.__str__()
        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在"
        return Response(res.dict)
Ejemplo n.º 13
0
    def create(self, request, *args, **kwargs):
        response = BaseResponse()

        course_id_list = request.data.get("course_id_list")
        print(course_id_list)

        # 清除
        keys = self.redis.keys("account_%s_*" % (request.user.pk))
        if keys:
            self.redis.delete(*keys)

        account_course = {}
        try:
            for course_id in course_id_list:
                account_key = settings.ACCOUNT_KEY % (request.user.pk,
                                                      course_id)

                course_obj = Course.objects.get(pk=course_id)

                course_detail_list = self.redis.hgetall(
                    "shopping_car_%s_%s" % (request.user.pk, course_id))
                # print(course_detail_list)
                course_detail = {}
                for key, val in course_detail_list.items():
                    if key.decode('utf-8') == 'price_policy_dict':
                        course_detail[key.decode('utf8')] = json.loads(
                            val.decode('utf8'))
                    else:
                        course_detail[key.decode('utf8')] = val.decode('utf8')
                # print(course_detail)
                account_course["course_detail"] = course_detail

                # coupon_record_list
                time_now = datetime.datetime.now()
                coupon_record_list = CouponRecord.objects.filter(
                    user=request.user,
                    status=0,
                    coupon__valid_begin_date__lt=time_now,
                    coupon__valid_end_date__gt=time_now,
                )

                coupon_course = {}
                coupon_global = {}
                for coupon_record_obj in coupon_record_list:
                    coupon_info = {
                        "name":
                        coupon_record_obj.coupon.name,
                        "coupon_type":
                        coupon_record_obj.coupon.get_coupon_type_display(),
                        "money_equivalent_value":
                        coupon_record_obj.coupon.money_equivalent_value,
                        "off_percent":
                        coupon_record_obj.coupon.off_percent,
                        "minimum_consume":
                        coupon_record_obj.coupon.minimum_consume,
                        "object_id":
                        coupon_record_obj.coupon.object_id,
                    }
                    object_id = coupon_info.get("object_id")
                    if object_id:
                        coupon_course[coupon_record_obj.pk] = coupon_info
                    else:
                        coupon_global[coupon_record_obj.pk] = coupon_info

                account_course["course_coupon"] = json.dumps(coupon_course)
                # print(account_course)
                # print("|"*50)
                # print(coupon_global)
                # print("========================================================")
                self.redis.hmset(account_key, account_course)
                self.redis.hmset("coupon_global_%s" % request.user.pk,
                                 coupon_global)
            response.msg = "结算成功"
            return Response(response.dict)

        except ObjectDoesNotExist as e:
            response.code = 1002
            response.error = "课程不存在"
            return Response(response.dict)
            '''
Ejemplo n.º 14
0
    def post(self, request):
        """
        模拟前端数据:
            {
                is_bei: true,
                course_list = [
                    {
                        course_id: 1,
                        default_price_policy_id: 1,
                        coupon_record_id: 2
                    },
                    {
                        course_id: 2,
                        default_price_policy_id: 4,
                        coupon_record_id: 6
                    }
                ],
                global_coupon_id: 3,
                pay_money: 298
            }

        :param request:
        :return:
        """

        # 1. 获取数据
        is_bei = request.data.get("is_beili")
        course_list = request.data.get("course_list")
        global_coupon_id = request.data.get("global_coupon_id")
        pay_money = request.data.get("pay_money")
        user_id = request.user.pk

        res = BaseResponse()

        # 2. 校验数据
        # 2.1 校验每一个课程
        try:
            price_list = []
            for course in course_list:
                course_id = course.gat("course_id")
                default_price_policy_id = course.gat("default_price_policy_id")
                coupon_record_id = course.gat("coupon_record_id")

                # 2.1.1 校验课程是否存在
                course_obj = Course.objects.get(pk=course_id)

                # 2.1.2 校验价格策略
                if default_price_policy_id not in [
                        obj.pk for obj in course_obj.price_policy.all()
                ]:
                    raise CommonException(1002, "价格策略错误!")

                pp = PricePolicy.objects.get(pk=default_price_policy_id)
                if coupon_record_id:
                    # 2.1.3 校验课程优惠卷

                    now = datetime.datetime.now()
                    coupon_record_obj = CouponRecord.objects.filter(
                        pk=coupon_record_id,
                        account=request.user,
                        coupon__content_type=9,
                        coupon__object_id=course_id,
                        status=0,
                        coupon__valid_begin_date__lte=now,
                        coupon__valid_end_date__gte=now).first()

                    if not coupon_record_obj:
                        raise CommonException(1003, "课程优惠卷异常!")

                    # 计算折后价格
                    rebate_money = self.cal_coupon_price(
                        pp.price, coupon_record_obj)
                    price_list.append(rebate_money)
                else:
                    price_list.append(pp.price)

            final_price = sum(price_list)

            # 2.2校验通用优惠卷
            if global_coupon_id:
                # 2.2.1 校验通用优惠卷合法
                now = datetime.datetime.now()
                g_coupon_record_obj = CouponRecord.objects.filter(
                    pk=global_coupon_id,
                    account=request.user,
                    coupon__content_type=9,
                    coupon__object_id=None,
                    status=0,
                    coupon__valid_begin_date__lte=now,
                    coupon__valid_end_date__gte=now).first()
                if not g_coupon_record_obj:
                    raise CommonException(1004, "通用优惠卷异常!")

                # 2.2.2 计算折后价格
                final_price = self.cal_coupon_price(final_price,
                                                    g_coupon_record_obj)

            # 2.3校验贝里
            if json.loads(is_bei):
                final_price = final_price - request.user.beili / 10

                if final_price < 0:
                    final_price = 0

            # 2.4 校验最终价格
            if final_price != pay_money:
                raise CommonException(1005, "支付价格异常!")

            # 3.生成订单
            # 生成订单表

            order_obj = Order.objects.create(payment_type=1,
                                             order_number=uuid.uuid4(),
                                             account=request.user,
                                             status=1,
                                             order_type=1,
                                             actual_amount=pay_money)
            print("course_list", course_list)

            for course_item in course_list:
                OrderDetail.objects.create(
                    order=order_obj,
                    content_type_id=14,
                    object_id=course_item.get("course_id"),
                    original_price=course_item.get("original_price"),
                    price=course_item.get("valid_period"),
                    valid_period=course_item.get("valid_period"),
                    valid_period_display=course_item.get(
                        "valid_period_display"))

            # 4. 调用 alipay 接口
            alipay = self.get_alipay()
            # 生成支付的url
            query_params = alipay.direct_pay(
                subject="路飞学城",  # 商品简单描述
                out_trade_no="x345" + str(time.time()),  # 商户订单号
                total_amount=pay_money,  # 交易金额(单位: 元 保留俩位小数)
            )

            pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(
                query_params)
            res.data = {"url": pay_url}

        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在!"

        except CommonException as e:
            res.code = e.code
            res.msg = e.msg

        return Response(res.dict)
Ejemplo n.º 15
0
    def post(self, request):
        # 1.获取数据
        is_beli = request.data.get('is_beli')
        course_list = request.data.get('course_list')
        global_coupon_id = request.data.get('global_coupon_id')
        pay_money = request.data.get('pay_money')
        user_id = request.user.pk
        # 2.校验
        res = BaseResponse()
        price_list = []
        try:
            now = datetime.datetime.now()
            # 2.1 每个课程
            for course_dict in course_list:
                course_id = course_dict.get("course_id")
                default_price_policy_id = course_dict.get(
                    'default_price_policy_id')
                # coupon_record_id = course_dict.get('coupon_record_id','')
                course_obj = Course.objects.get(pk=course_id)

                if default_price_policy_id not in [
                        obj.pk for obj in course_obj.price_policy.all()
                ]:
                    raise CommonException(1002, '价格策略不存在')
                content_obj = ContentType.objects.get(
                    app_label='api',
                    model='course',
                )

                price_policy_obj = PricePolicy.objects.get(
                    pk=course_dict.get("default_price_policy_id"))
                course_dict["original_price"] = price_policy_obj.price
                course_dict[
                    "valid_period_display"] = price_policy_obj.get_valid_period_display(
                    )
                course_dict["valid_period"] = price_policy_obj.valid_period
                coupon_record_id = course_dict.get("coupon_record_id")
                # 检验课程优惠券,并计算出折后的总价格(不带通用优惠券和贝利)
                if not coupon_record_id:
                    price_list.append(price_policy_obj.price)
                else:
                    coupon_record_list = CouponRecord.objects.filter(
                        account=request.user,
                        coupon__content_type=content_obj,
                        coupon__object_id=course_id,
                        status=0,
                        coupon__valid_begin_date__lte=now,
                        coupon__valid_end_date__gte=now,
                    )
                    if coupon_record_id and coupon_record_id not in [
                            obj.pk for obj in coupon_record_list
                    ]:
                        raise CommonException("课程优惠券异常!", 1006)
                    coupon_record_obj = CouponRecord.objects.get(
                        pk=coupon_record_id)
                    rebate_money = self.cal_coupon_price(
                        price_policy_obj.price, coupon_record_obj)
                    price_list.append(rebate_money)
            # 2.2 通用优惠券
            global_coupon_record_list = CouponRecord.objects.filter(
                account=request.user,
                status=0,
                coupon__valid_begin_date__lt=now,
                coupon__valid_end_date__gt=now,
                coupon__content_type_id=14,
                coupon__object_id=None)
            if not global_coupon_record_list: global_coupon_record_list = []
            if global_coupon_id and global_coupon_id not in [
                    obj.pk for obj in global_coupon_record_list
            ]:
                raise CommonException("通用优惠券异常", 1006)
            if global_coupon_id:
                global_coupon_record_obj = CouponRecord.objects.get(
                    pk=global_coupon_id)
                final_price = self.cal_coupon_price(sum(price_list),
                                                    global_coupon_record_obj)
            else:
                final_price = sum(price_list)
            # 2.3 贝利
            cost_beli_num = 0
            if is_beli:
                final_price = final_price - request.user.beli / 10
                cost_beli_num = request.user.beli
                if final_price < 0:
                    final_price = 0
                    cost_beli_num = final_price * 10
            if final_price != float(pay_money):
                raise CommonException(1008, "支付总价格异常!")

            # 生成订单
            order_number = self.get_order_num()
            order_obj = Order.objects.create(
                payment_type=1,
                order_number=order_number,
                account=request.user,
                status=1,
                order_type=1,
                actual_amount=pay_money,
            )

            for course_item in course_list:
                OrderDetail.objects.create(
                    order=order_obj,
                    content_type_id=14,
                    object_id=course_item.get("course_id"),
                    original_price=course_item.get("original_price"),
                    price=course_item.get("rebate_price")
                    or course_item.get("original_price"),
                    valid_period=course_item.get("valid_period"),
                    valid_period_display=course_item.get(
                        "valid_period_display"),
                )

            request.user.beli = request.user.beli - cost_beli_num
            request.user.save()

            cache.set(order_number + "|" + str(cost_beli_num), "", 20)
            account_key = settings.ACCOUNT_REDIS_KEY % (user_id, "*")

            cache.delete(*cache.keys(account_key))
            res.data = self.get_pay_url(request, order_number, final_price)

        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = '课程不存在!'
        except CommonException as e:
            res.code = e.code
            res.msg = e.msg
        return Response(res.dict)
Ejemplo n.º 16
0
    def post(self, request):
        """
        模拟请求数据:
        {
            "course_id": 1,
            "price_policy_id": 2
        }
        :param request:
        :return:
        """

        # 1 获取请求数据
        course_id = request.data.get("course_id")
        price_policy_id = request.data.get("price_policy_id")
        user_id = request.user.pk

        res = BaseResponse()

        # 2.校验数据
        try:
            # 2.1 校验课程是否存在
            course_obj = Course.objects.get(pk=course_id)
            # 2.2 校验价格策略是否合法
            # ret = course_obj.price_policy.all()
            # print(ret)
            price_policy_dict = {}
            for price_policy in course_obj.price_policy.all():
                price_policy_dict[price_policy.pk] = {
                    "valid_period": price_policy.valid_period,
                    "valid_period_text":
                    price_policy.get_valid_period_display(),
                    "price": price_policy.price,
                    "default": price_policy_id == price_policy.pk
                }

            if price_policy_id not in price_policy_dict:
                raise CommonException(1002, "价格策略错误!")
            pp = PricePolicy.objects.get(pk=price_policy_id)

            # 3 写入 redis

            shoppingcar_key = settings.SHOPPINGCAR_KEY % (user_id, course_id)
            shoppingcar_val = {
                "title": course_obj.name,
                "img": course_obj.course_img,
                "relate_price_policy": price_policy_dict,
                "choose_price_policy_id": price_policy_id,
                "price": pp.price,
                "valid_period": pp.valid_period,
                "valid_period_text": pp.get_valid_period_display(),
            }

            cache.set(shoppingcar_key, json.dumps(shoppingcar_val))
            res.data = "加入购物车成功!"

        except CommonException as e:
            res.code = e.code
            res.msg = "课程不存在"

        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在"

        return Response(res.dict)
Ejemplo n.º 17
0
    def post(self, request):
        '''
        状态码:
             1000: 成功
             1001: 课程不存在
        模拟请求数据:
        {
          "course_id_list":[1,2]
        }
        '''
        # 1 获取请求数据
        course_id_list = request.data.get('course_id_list')
        user_id = request.user.pk
        res = BaseResponse()
        try:
            # 结算情况: 1 直接购买 2 购物车结算
            # 2 创建数据结构
            # 清空操作,找到所有account_userid_*,全部清空
            del_list = cache.keys(settings.ACCOUNT_KEY % (user_id, '*'))
            if del_list:
                cache.delete(*del_list)

            price_list = []
            for course_id in course_id_list:
                # 结算key
                account_key = settings.ACCOUNT_KEY % (user_id, course_id)
                # 结算字典
                account_val = {}
                # 获取课程基本信息
                shoppingcart_key = settings.SHOPPINGCART_KEY % (user_id,
                                                                course_id)

                # 判断课程是否存在购物车中
                if not cache.exists(shoppingcart_key):
                    raise CommonException('购物车不存在该课程', 1040)

                course_obj = Course.objects.get(pk=course_id)
                course_info = json.loads(cache.get(shoppingcart_key))
                # 添加到结算字典中
                account_val['course_info'] = course_info

                # 课程价格加入到价格列表
                price_list.append(float(course_info['price']))

                # 获取优惠券信息:查询当前用户当前课程有效的未使用的优惠券
                coupons = self.get_coupon_dict(request, course_id)
                # 将优惠券字典添加到结算字典中
                account_val['coupons'] = coupons
                cache.set(account_key, json.dumps(account_val))

            # 获取通用优惠券
            global_coupons = self.get_coupon_dict(request)

            cache.set('global_coupons_%s' % user_id,
                      json.dumps(global_coupons))
            cache.set('total_price', sum(price_list))

        except CommonException as e:
            res.code = e.code
            res.msg = e.msg
        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在"

        return Response(res.dict)
Ejemplo n.º 18
0
    def put(self, request):
        """
        # 更改优惠券信息
        choose_coupons:{
            choose_coupons:{'1':'2','2':'3','global_coupon_id':5}
            is_beli:true
        }
        """
        res = BaseResponse()
        try:
            # 获取数据
            choose_coupons = request.data.get('choose_coupons')
            is_beli = request.data.get('is_beli')
            user_pk = request.user.pk

            # 获取结算课程列表
            cal_price = {}
            data = self.get(request).data.get('data')
            account_course_list = data.get('account_course_list')
            account_course_info = {}
            for account_course in account_course_list:
                temp = {
                    'coupons': {},
                    'default_price': account_course['default_price']
                }
                account_course_info[account_course['id']] = temp

                for item in account_course['coupon_list']:
                    coupon_id = choose_coupons.get(str(account_course['id']))
                    if coupon_id == item['pk']:
                        temp['coupon'] = item

            price_list = []
            total_price = 0
            '''
               {
                    2: {
                        'coupon': {
                            'money_equivalent_value': 0.0,
                            'name': '清明节活动',
                            'pk': 3,
                            'off_percent': 80,
                            'coupon_type': '折扣券',
                            'minimum_consume': 0
                        },
                        'default_price': 200.0
                    }
                }
            '''
            for key, val in account_course_info.items():
                if not val.get('coupon'):
                    price_list.append(val['default_price'])
                    cal_price[key] = val['default_price']
                else:
                    coupon_info = val.get('coupon')
                    default_price = val['default_price']
                    # 计算折扣之后的价格
                    rebate_price = self.cal_coupon_price(
                        default_price, coupon_info)
                    price_list.append(rebate_price)
                    cal_price[key] = rebate_price

            total_price = sum(price_list)

            # 计算通用优惠券的价格
            global_coupon_id = choose_coupons.get('global_coupon_id')
            if global_coupon_id:
                global_coupons = data.get('global_coupons')
                global_coupon_dict = {}
                for item in global_coupons:
                    global_coupon_dict[item['pk']] = item
                total_price = self.cal_coupon_price(
                    total_price, global_coupon_dict[global_coupon_id])

            # 计算贝里
            if json.loads(is_beli):
                total_price = total_price - request.user.beli / 10
                if total_price < 0:
                    total_price = 0

            cal_price['total_price'] = total_price
            res.data = cal_price
        except Exception as e:
            res.code = 500
            res.msg = "结算错误!" + str(e)

        return Response(res.dict)
Ejemplo n.º 19
0
 def put(self, request, *args, **kwargs):
     """
     根据前端传来 {"is_beli":"true","choose_coupons":{"global_coupon_id":id,course_id:coupon_id}} ,动态计算总价格返回
     :param request:
     :param args:
     :param kwargs:
     :return:
     """
     res = BaseResponse()
     try:
         # 获取数据
         choose_coupons = request.data.get("choose_coupons")
         is_beli = request.data.get("is_beli")
         # 获取结算课程列表
         cal_price = {}
         account_key = settings.ACCOUNT_KEY % request.user.pk
         data = json.loads(REDIS_CONN.get(account_key))
         account_course_list = data.get("account_course_list")
         # 构建 account_courses_info 数据结构
         '''
         account_courses_info = {
             'id': {
                 'coupon': {
                     'pk': '',
                     'name': '',
                     'coupon_type': '',
                     'money_equivalent_value': '',
                     'off_percent': 111,
                     'minimum_consume': 111
                 },
                 'default_price': 11
             }
         }
         '''
         account_courses_info = {}
         for account_course in account_course_list:
             temp = {
                 "coupon": {},
                 "default_price": account_course["default_price"]
             }
             account_courses_info[account_course["id"]] = temp
             for item in account_course["coupon_list"]:
                 coupon_id = choose_coupons.get(str(account_course["id"]))
                 if coupon_id == item["pk"]:
                     temp["coupon"] = item
         # 计算每个课程优惠后的价格
         price_list = []
         for key, val in account_courses_info.items():
             if not val.get("coupon"):
                 price_list.append(val["default_price"])
                 cal_price[key] = val["default_price"]
             else:
                 coupon_info = val.get("coupon")
                 default_price = val["default_price"]
                 rebate_price = self.cal_coupon_price(
                     default_price, coupon_info)
                 price_list.append(rebate_price)
                 cal_price[key] = rebate_price
         # 总价格
         total_price = sum(price_list)
         # 计算通用优惠券的价格
         global_coupon_id = choose_coupons.get("global_coupon_id")
         if global_coupon_id:
             global_coupons = data.get("global_coupons")
             global_coupon_dict = {}
             for item in global_coupons:
                 global_coupon_dict[item["pk"]] = item
             total_price = self.cal_coupon_price(
                 total_price, global_coupon_dict[global_coupon_id])
         # 计算贝里,贝里——》平台货币
         if json.loads(is_beli):
             total_price = total_price - request.user.beli / 10
             if total_price < 0:
                 total_price = 0
         cal_price["total_price"] = total_price
         res.data = cal_price
     except CommonException as e:
         res.code = e.code
         res.msg = e.error
     except Exception as e:
         res.code = 5000
         res.msg = str(e)
     return Response(res.dict)
Ejemplo n.º 20
0
    def post(self, request, *args, **kwargs):
        """
        重新计算总价格,生成订单,返回支付URL
        模拟请求数据格式:
        {
        is_beli:true,
        course_list=[
            {
                course_id:1
                default_price_policy_id:1,
                coupon_record_id:2
            },
            {
                course_id:2
                default_price_policy_id:4,
                coupon_record_id:6
            }
            ],
        global_coupon_id:3,
        pay_money:298
        }

        状态码:
            1300:  成功
            1301:  课程不存在
            1302:  价格策略不合法
            1303:  加入购物车失败
            1304:  获取购物车失败
            1305:  贝里数有问题
            1306:  优惠券异常
            1307:  优惠券未达到最低消费
            1308:  支付总价格异常

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        response = BaseResponse()
        # 1 获取数据
        user_id = request.user.pk
        global_coupon_id = request.data.get("global_coupon_id")
        pay_money = request.data.get("pay_money")
        course_list = request.data.get("course_list")
        is_beli = request.data.get("is_beli")
        now = timezone.now()
        try:
            # 2 校验数据
            # 2.2 校验课程
            course_price_list = []
            for course_dict in course_list:
                # 2.2.1 校验课程id
                course_id = course_dict.get("course_id")
                course_obj = Course.objects.get(pk=course_id)
                # 2.2.2 价格策略id
                if course_dict.get("default_price_policy_id") not in [
                        obj.pk for obj in course_obj.price_policy.all()
                ]:
                    raise CommonException("价格策略异常!", 1302)
                # 2.2.3 课程优惠券id
                price_policy_obj = PricePolicy.objects.get(
                    pk=course_dict.get("default_price_policy_id"))
                course_dict["original_price"] = price_policy_obj.price
                course_dict[
                    "valid_period_display"] = price_policy_obj.get_valid_period_display(
                    )
                course_dict["valid_period"] = price_policy_obj.valid_period
                coupon_record_id = course_dict.get("coupon_record_id")
                if coupon_record_id:
                    coupon_record_list = CouponRecord.objects.filter(
                        account=request.user,
                        status=0,
                        coupon__valid_begin_date__lt=now,
                        coupon__valid_end_date__gt=now,
                        coupon__content_type_id=9,
                        coupon__object_id=course_id)
                    if coupon_record_id and coupon_record_id not in [
                            obj.pk for obj in coupon_record_list
                    ]:
                        raise CommonException("课程优惠券异常!", 1306)
                    # 计算循环课程的课程优惠券优惠后的价格
                    coupon_record_obj = CouponRecord.objects.get(
                        pk=coupon_record_id)
                    rebate_price = self.cal_coupon_price(
                        price_policy_obj.price, coupon_record_obj)
                    course_price_list.append(rebate_price)
                    course_dict["rebate_price"] = rebate_price
                else:
                    course_price_list.append(price_policy_obj.price)
            # 2.3 校验通用优惠券id
            if global_coupon_id:
                global_coupon_record_list = CouponRecord.objects.filter(
                    account=request.user,
                    status=0,
                    coupon__valid_begin_date__lt=now,
                    coupon__valid_end_date__gt=now,
                    coupon__content_type_id=9,
                    coupon__object_id=None)
                if global_coupon_id and global_coupon_id not in [
                        obj.pk for obj in global_coupon_record_list
                ]:
                    raise CommonException("通用优惠券异常", 1306)
                global_coupon_record_obj = CouponRecord.objects.get(
                    pk=global_coupon_id)
                final_price = self.cal_coupon_price(sum(course_price_list),
                                                    global_coupon_record_obj)
            else:
                final_price = sum(course_price_list)
            # 2.4 计算实际支付价格与money做校验
            cost_beli_num = 0
            if is_beli:
                final_price = final_price - request.user.beli / 10
                cost_beli_num = request.user.beli
                if final_price < 0:
                    final_price = 0
                    cost_beli_num = int(final_price * 10)
            if final_price != float(pay_money):
                raise CommonException(1308, "支付总价格异常!")

            # 3 生成订单记录
            order_number = self.get_order_num()
            order_obj = Order.objects.create(
                payment_type=1,
                order_number=order_number,
                account=request.user,
                status=1,
                actual_amount=pay_money,
            )
            for course_item in course_list:
                OrderDetail.objects.create(
                    order=order_obj,
                    content_type_id=9,
                    object_id=course_item.get("course_id"),
                    original_price=course_item.get("original_price"),
                    price=course_item.get("rebate_price")
                    or course_item.get("original_price"),
                    valid_period=course_item.get("valid_period"),
                    valid_period_display=course_item.get(
                        "valid_period_display"),
                )
            # 3 保存数据
            request.user.beli = request.user.beli - cost_beli_num
            request.user.save()
            REDIS_CONN.set(order_number + "|" + str(cost_beli_num), "", 20)
            # 删除 redis 中 account 信息
            account_key = settings.ACCOUNT_KEY % user_id
            REDIS_CONN.delete(account_key)
            # 4 获取支付URL
            response.data = self.get_pay_url(request, order_number,
                                             final_price)

        except ObjectDoesNotExist as e:
            response.code = 1301
            response.msg = "课程不存在!"
        except CommonException as e:
            response.code = e.code
            response.msg = e.error
        except Exception as e:
            response.code = 5000
            response.msg = str(e)

        return Response(response.dict)
Ejemplo n.º 21
0
    def post(self, request):
        res = BaseResponse()
        # 1 获取数据
        user_id = request.user.pk
        global_coupon_id = request.data.get('global_coupon_id')
        pay_money = request.data.get('pay_money')
        course_list = request.data.get('course_list')
        is_beli = request.data.get('is_beli')
        now = datetime.datetime.now()

        try:
            # 2 校验数据
            # 2.1 校验课程
            course_price_list = []
            for course_dict in course_list:
                # 校验课程id
                course_id = course_dict.get('course_id')
                course_obj = Course.objects.get(pk=course_id)
                # 价格策略id
                if course_dict.get('default_price_id') not in [
                        obj.pk for obj in course_obj.price_policy.all()
                ]:
                    raise CommonException("价格策略异常!", 1002)
                # 课程优惠券id
                price_policy_obj = PricePolicy.objects.get(
                    pk=course_dict.get('default_price_policy_id'))
                course_dict['original_price'] = price_policy_obj.price
                course_dict[
                    'valid_period_display'] = price_policy_obj.get_valid_period_display
                course_dict['valid_period'] = price_policy_obj.valid_period
                coupon_record_id = course_dict.get('coupon_record_id')

                if coupon_record_id:
                    coupon_record_list = CouponRecord.objects.filter(
                        account=request.user,
                        status=0,
                        coupon__valid_begin_date__lt=now,
                        coupon__valid_end_date__gt=now,
                        coupon__content_type_id=13,
                        coupon__object_id=course_id)

                    if coupon_record_list and coupon_record_id not in [
                            obj.pk for obj in coupon_record_list
                    ]:
                        raise CommonException("课程优惠券异常!", 1006)

                    # 计算循环课程的课程优惠券优惠后的价格
                    coupon_record_obj = CouponRecord.objects.get(
                        pk=coupon_record_id)
                    rebate_price = self.cal_coupon_price(
                        price_policy_obj.price, coupon_record_obj)
                    course_price_list.append(rebate_price)
                    course_dict['rebate_price'] = rebate_price
                else:
                    course_price_list.append(price_policy_obj.price)

            # 2.2 校验通用优惠券id
            if global_coupon_id:
                global_coupon_record_list = CouponRecord.objects.filter(
                    account=request.user,
                    status=0,
                    coupon__valid_begin_date__lt=now,
                    coupon__valid_end_date__gt=now,
                    coupon__content_type_id=13,
                    coupon__object_id=None)
                if global_coupon_record_list and global_coupon_id not in [
                        obj.pk for obj in global_coupon_record_list
                ]:
                    raise CommonException("通用优惠券异常", 1006)

                global_coupon_record_obj = CouponRecord.objects.get(
                    pk=global_coupon_id)
                final_price = self.cal_coupon_price(sum(course_price_list),
                                                    global_coupon_record_obj)
            else:
                final_price = sum(course_price_list)
            # 2.3 计算实际支付价格与money做校验
            cost_beli_num = 0
            if is_beli:
                price = final_price - request.user.beli / 10
                cost_beli_num = request.user.beli
                if price < 0:
                    price = 0
                    cost_beli_num = final_price * 10
                final_price = price

            if final_price != float(pay_money):
                raise CommonException(1008, "支付总价格异常!")

            # 3 生成订单记录
            order_number = self.get_order_num()
            order_obj = Order.objects.create(payment_type=1,
                                             order_number=order_number,
                                             account=request.user,
                                             status=1,
                                             order_type=1,
                                             actual_amount=pay_money)

            for course_item in course_list:
                OrderDetail.objects.create(
                    order=order_obj,
                    content_type_id=7,
                    object_id=course_item.get('course_id'),
                    original_price=course_item.get('original_price'),
                    price=course_item.get('rebate_price')
                    or course_item.get('original_price'),
                    valid_period=course_item.get('valid_period'),
                    valid_period_display=course_item.get(
                        'valid_period_display'))

            request.user.beli = request.user.beli - cost_beli_num
            request.user.save()
            cache.set(order_number + '|' + str(cost_beli_num), '', 20)
            account_key = settings.ACCOUNT_KEY % (user_id, "*")
            cache.delete(*cache.keys(account_key))
            '''
              [
                 {  course_id:1
                    default_price_policy_id:1,
                    coupon_record_id:2
                  },
                 {
                    course_id:2
                    default_price_policy_id:4,
                    coupon_record_id:6
                  }
              ]
            '''
            res.data = self.get_pay_url(request, order_number, final_price)
        except ObjectDoesNotExist as e:
            res.code = 1001
            res.msg = "课程不存在!"
        except CommonException as e:
            res.code = e.code
            res.msg = e.msg
        except Exception as e:
            res.code = 500
            res.msg = str(e)

        return Response(res.dict)