Esempio n. 1
0
 def __init__(self, current_app):
     self.alipay_url_prefix = 'https://openapi.alipaydev.com/gateway.do?'
     a = current_app.config['ALIPAY_PUBLIC_KEY']
     self.alipay = AliPay(
         appid=current_app.config['APP_ID'],
         app_notify_url=None,
         alipay_public_key_string=current_app.config['ALIPAY_PUBLIC_KEY'],
         app_private_key_string=current_app.config['ALIPAY_PRIVATE_KEY'],
         sign_type="RSA2",
         debug=True)
Esempio n. 2
0
    def post(self, request):
        """
        处理支付宝的notify_url
        :param request:
        :return:
        """
        processed_dict = {}
        for key, value in request.POST.items():
            processed_dict[key] = value

        sign = processed_dict.pop("sign", None)

        alipay = AliPay(
            appid="",
            app_notify_url="http://127.0.0.1:8000/alipay/return/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=
            ali_pub_key_path,  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://127.0.0.1:8000/alipay/return/")

        verify_re = alipay.verify(processed_dict, sign)

        if verify_re is True:
            order_sn = processed_dict.get('out_trade_no', None)
            trade_no = processed_dict.get('trade_no', None)
            trade_status = processed_dict.get('trade_status', None)

            existed_orders = OrderInfo.objects.filter(order_sn=order_sn)
            for existed_order in existed_orders:
                order_goods = existed_order.goods.all()
                for order_good in order_goods:
                    goods = order_good.goods
                    goods.sold_num += order_good.goods_num
                    goods.save()

                existed_order.pay_status = trade_status
                existed_order.trade_no = trade_no
                existed_order.pay_time = datetime.now()
                existed_order.save()

            return Response("success")
Esempio n. 3
0
    def get(self, request):
        """
        处理支付宝的return_url返回
        :param request:
        :return:
        """
        processed_dict = {}
        for key, value in request.GET.items():
            processed_dict[key] = value

        sign = processed_dict.pop("sign", None)

        alipay = AliPay(
            appid="",
            app_notify_url="http://127.0.0.1:8000/alipay/return/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=ali_pub_key_path,  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://127.0.0.1:8000/alipay/return/"
        )

        verify_re = alipay.verify(processed_dict, sign)

        if verify_re is True:
            order_sn = processed_dict.get('out_trade_no', None)
            trade_no = processed_dict.get('trade_no', None)
            trade_status = processed_dict.get('trade_status', None)

            existed_orders = OrderInfo.objects.filter(order_sn=order_sn)
            for existed_order in existed_orders:
                existed_order.pay_status = trade_status
                existed_order.trade_no = trade_no
                existed_order.pay_time = datetime.now()
                existed_order.save()

            response = redirect("index")
            response.set_cookie("nextPath", "pay", max_age=3)
            return response
        else:
            response = redirect("index")
            return response
Esempio n. 4
0
    def get(self, request):
        """
        处理支付宝的return_url返回
        :param request:
        :return:
        """
        processed_dict = {}
        for key, value in request.GET.items():
            processed_dict[key] = value
        sign = processed_dict.pop("sign", None)
        alipay = AliPay(
            app_id=ALI_APP_ID,
            notify_url="http://118.31.60.22:8000/user/ali_pay/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=
            ali_pub_key_path,  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://118.31.60.22:8000/user/ali_pay")

        verify_re = alipay.verify(processed_dict, sign)
        if verify_re is True:
            order_sn = processed_dict.get('out_trade_no', None)
            trade_no = processed_dict.get('trade_no', None)
            existed_order = OrderInfo.objects.filter(order_sn=order_sn).first()
            try:
                existed_order.trade_no = trade_no
                existed_order.pay_time = datetime.datetime.now()
                existed_order.save()
                response = redirect(reverse('apps.user:index'))
                # response.set_cookie("nextPath", "pay", max_age=3)
                return response
            except:
                response = redirect('apps.user:index')
                return response
        else:
            response = redirect('apps.user:index')
            return response
Esempio n. 5
0
    def post(self, request):
        """
        处理支付宝的notify_url
        :param request:
        :return:
        """
        processed_dict = {}
        for key, value in request.POST.items():
            processed_dict[key] = value
        sign = processed_dict.pop("sign", None)
        alipay = AliPay(
            app_id=ALI_APP_ID,
            notify_url="http://118.31.60.22:8000/user/ali_pay/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=
            ali_pub_key_path,  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://118.31.60.22:8000/user/ali_pay/")
        verify_re = alipay.verify(processed_dict, sign)
        if verify_re is True:
            order_sn = processed_dict.get('out_trade_no', None)
            trade_no = processed_dict.get('trade_no', None)
            trade_status = processed_dict.get('trade_status', None)
            existed_order = OrderInfo.objects.filter(order_sn=order_sn).first()
            existed_order.trade_no = trade_no
            existed_order.pay_time = datetime.datetime.now()
            existed_order.pay_status = trade_status
            # 判断是充值会员
            if existed_order.subject in ['年', '季', '月', '双周']:
                if existed_order.subject == '年':
                    days = 365
                    vip_num = 4
                elif existed_order.subject == '季':
                    days = 90
                    vip_num = 3
                elif existed_order.subject == '月':
                    days = 30
                    vip_num = 2
                elif existed_order.subject == '双周':
                    days = 14
                    vip_num = 1
                else:
                    days = 0
                    vip_num = 0
                vip = VipExpire.objects.filter(
                    user_id=existed_order.user_id).first()
                user = Users.objects.filter(id=existed_order.user_id).first()
                # 是否vip
                if vip:
                    # 如果没到期
                    if vip.expire_time.replace(tzinfo=pytz.timezone(
                            'UTC')) > datetime.datetime.now().replace(
                                tzinfo=pytz.timezone('UTC')):
                        vip.expire_time = vip.expire_time.replace(
                            tzinfo=pytz.timezone('UTC')) + datetime.timedelta(
                                days=days)
                        vip.save()
                    else:
                        vip.expire_time = existed_order.pay_time.replace(
                            tzinfo=pytz.timezone('UTC')) + datetime.timedelta(
                                days=days)
                        vip.save()
                    if user.vip_num <= vip_num:
                        user.vip_num = vip_num
                        user.save()
                    else:
                        user.vip_num = user.vip_num
                        user.save()
                else:
                    VipExpire.objects.create(
                        user_id=existed_order.user_id,
                        expire_time=existed_order.pay_time.replace(
                            tzinfo=pytz.timezone('UTC')) +
                        datetime.timedelta(days=days))
                    user.vip_num = vip_num
                    user.save()
                if existed_order.subject == '月':
                    give_jifen = 368
                elif existed_order.subject == '季':
                    give_jifen = 1198
                elif existed_order.subject == '年':
                    give_jifen = 5988
                else:
                    give_jifen = 0
                user.integration += give_jifen
                user.save()
                IntegralRecord.objects.create(integral_type='开通' +
                                              existed_order.subject + '度超级VIP',
                                              integral=give_jifen,
                                              user_id=existed_order.user_id)
                content = '恭喜您获得超级' + existed_order.subject + '度VIP特权,全场土地信息任意看,本月沙龙、月报会免费报名,榜单和数据无限下载。本次消费金额'\
                          + str(existed_order.order_mount) + '元,额外获得' + str(give_jifen) + '积分。'
                system_notice = SystemMessageModel.objects.filter(
                    trade_no=existed_order.trade_no).first()
                # 发送会员通知短信
                # s_vip = SingleVip(user.mobile, str(existed_order.order_mount), existed_order.subject)
                # print(s_vip.one())
                if not system_notice:
                    try:
                        SystemMessageModel.objects.create(
                            content=content,
                            sys_type='会员充值',
                            user_id=existed_order.user_id)
                    except:
                        return Response({'msg': '系统消息创建失败', 'status': '0'})

            else:
                fabu = ReleaseRecord.objects.filter(
                    land_id=existed_order.land_id,
                    luyou=existed_order.luyou).first()
                if not Contact.objects.filter(user_id=existed_order.user_id,
                                              land_id=existed_order.land_id,
                                              contacted_id=fabu.user_id,
                                              luyou=existed_order.luyou):
                    Contact.objects.create(user_id=existed_order.user_id,
                                           land_id=existed_order.land_id,
                                           contacted_id=fabu.user_id,
                                           luyou=existed_order.luyou)
                user = Users.objects.filter(id=existed_order.user_id).first()
                content = '恭喜您成功购买' + existed_order.subject + ',消费' + str(
                    existed_order.order_mount) + '元'
                # if existed_order.luyou == '/tudimessage/zhuanrang':
                # TODO:退款
                contented = '恭喜您,您的' + existed_order.subject + '订单,已被' + user.username + '购买'
                system_notice = SystemMessageModel.objects.filter(
                    trade_no=existed_order.trade_no).first()
                if not system_notice:
                    SystemMessageModel.objects.create(
                        content=content,
                        sys_type='购买信息',
                        user_id=existed_order.user_id,
                        trade_no=existed_order.trade_no)
                    SystemMessageModel.objects.create(
                        content=contented,
                        sys_type='售出信息',
                        user_id=fabu.user_id,
                        trade_no=existed_order.trade_no)
            existed_order.save()
            today = datetime.date.today()
            today_data = AdminUserChart.objects.filter(create_on=today).first()
            if today_data:
                today_data.today_fufei += existed_order.order_mount
                today_data.save()
            else:
                user_num = Users.objects.count()
                AdminUserChart.objects.create(
                    today_fufei=existed_order.order_mount, user_all=user_num)
            return Response("success")
Esempio n. 6
0
    def get(self, request):
        user_id = request.GET.get('user_id', 1)
        user = Users.objects.filter(id=user_id).first()
        land_id = request.GET.get('land_id', 133)
        luyou = request.GET.get('luyou', 'userinfo2')
        order_sn = "{time_str}{userid}{ranstr}".format(
            time_str=time.strftime("%Y%m%d%H%M%S"),
            userid=user_id,
            ranstr=random.randint(10, 99))
        pay = self.get_is_pay(luyou, land_id, user_id)
        if pay:
            return Response({'msg': '该订单已支付', 'status': '0'})
        if luyou == '/tudimessage/nitui' or luyou == '/tudimessage/paimai' or luyou == '/tudimessage/guapai' or luyou == '/tudimessage/xiancheng':
            land = LandInfo.objects.filter(id=land_id).first()
            reward_price = land.reward_price
            title = land.title

        elif luyou == '/tudimessage/zhaoshang':
            land = AttractInfo.objects.filter(id=land_id).first()
            reward_price = land.reward_price
            title = land.title

        elif luyou == '/tudimessage/zhuanrang':
            land = TransInfo.objects.filter(id=land_id).first()
            reward_price = land.reward_price
            title = land.title

        elif luyou == '/activity/shalong' or luyou == '/activity/yuebao' or luyou == '/activity/tuijie' or luyou == '/activity/kuanian':
            land = Activity.objects.filter(id=land_id).first()
            reward_price = land.reward_price
            title = land.title

        elif luyou == "/tudilist/nadi" or luyou == "/tudilist/gongdi" or luyou == "/tudilist/shoulou" or luyou == "/tudilist/loupan":
            land = PropertyList.objects.filter(id=land_id).first()
            reward_price = land.reward_price
            title = land.title

        elif luyou == "/Investment/zhoubao" or luyou == "/Investment/yuebao" or luyou == "/Investment/jibao" or luyou == "/Investment/bannnianbao" or luyou == "/Investment/nianbao":
            land = InvestmentData.objects.filter(id=land_id).first()
            reward_price = land.reward_price
            title = land.title
        elif luyou == 'userinfo2':
            vip_type = request.GET.get('vip_type', '年')
            if vip_type == '年':
                reward_price = 12988
            elif vip_type == '季':
                reward_price = 3568
            elif vip_type == '月':
                reward_price = 1298
            elif vip_type == '双周':
                reward_price = 0.01
            else:
                return Response({'status': '0'})
            alipay = AliPay(
                app_id=ALI_APP_ID,
                notify_url="http://118.31.60.22:8000/user/ali_pay/",
                app_private_key_path=private_key_path,
                alipay_public_key_path=
                ali_pub_key_path,  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
                debug=True,  # 默认False,
                return_url="http://118.31.60.22:8000/user/ali_pay")
            url = alipay.direct_pay(
                subject=vip_type + '会员',
                out_trade_no=order_sn,
                total_amount=reward_price,
                return_url="http://118.31.60.22:8000/user/ali_pay")
            OrderInfo.objects.create(user_id=user_id,
                                     order_mount=reward_price,
                                     order_sn=order_sn,
                                     subject=vip_type,
                                     luyou=luyou,
                                     order_type=1)
            # re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
            re_url = "https://openapi.alipay.com/gateway.do?{data}".format(
                data=url)
            return Response({'re_url': re_url, 'msg': '成功', 'status': '1'})
        else:
            return Response({'msg': '路由错了'})

        alipay = AliPay(
            app_id=ALI_APP_ID,
            notify_url="http://118.31.60.22:8000/user/ali_pay/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=
            ali_pub_key_path,  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            debug=False,  # 默认False,
            return_url="http://118.31.60.22:8000/user/ali_pay")
        url = alipay.direct_pay(
            subject=title,
            out_trade_no=order_sn,
            total_amount=reward_price,
            return_url="http://118.31.60.22:8000/user/ali_pay")
        OrderInfo.objects.create(user_id=user_id,
                                 order_mount=reward_price,
                                 order_sn=order_sn,
                                 subject=title,
                                 land_id=land_id,
                                 luyou=luyou,
                                 order_type=1)
        # re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
        re_url = "https://openapi.alipay.com/gateway.do?{data}".format(
            data=url)
        return Response({'re_url': re_url, 'msg': '成功', 'status': '1'})
Esempio n. 7
0
class OrderAlipay(object):
    def __init__(self, current_app):
        self.alipay_url_prefix = 'https://openapi.alipaydev.com/gateway.do?'
        a = current_app.config['ALIPAY_PUBLIC_KEY']
        self.alipay = AliPay(
            appid=current_app.config['APP_ID'],
            app_notify_url=None,
            alipay_public_key_string=current_app.config['ALIPAY_PUBLIC_KEY'],
            app_private_key_string=current_app.config['ALIPAY_PRIVATE_KEY'],
            sign_type="RSA2",
            debug=True)

    def web_pay(self):
        pass

    def mobile_pay(self):
        pass

    def app_pay(self):
        pass

    def refund(self, refund_amount, out_trade_no, trade_no):
        result = self.alipay.api_alipay_trade_refund(refund_amount,
                                                     out_trade_no=out_trade_no,
                                                     trade_no=trade_no)
        if result["code"] == "10000":
            return True
        else:
            return False

    def get_pay_url(self,
                    type,
                    out_trade_no,
                    total_amount,
                    subject,
                    return_url,
                    notify_url=None):
        # 手机/PC网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        # 判断支付类型
        pay_function = self._get_pay_type(type)
        order_string = pay_function(
            out_trade_no=out_trade_no,  # 订单编号 不重复
            total_amount=total_amount,  # 支付金额  0.01小数两位
            subject=subject,  # 订单标题
            return_url=return_url,  # 返回链接地址 http://127.0.0.1:5000/order.html
            notify_url=notify_url  # 可选, 不填则使用默认notify url
        )

        # 构建跳转到的支付地址
        pay_url = self.alipay_url_prefix + order_string
        return json.dumps({'code': '200', 'pay_url': pay_url})

    def verify(self, data):
        # data = request.form.to_dict()
        # sign 不能参与签名验证
        signature = data.pop("sign")
        # verify
        success = self.alipay.verify(data, signature)
        if success and data["trade_status"] in ("TRADE_SUCCESS",
                                                "TRADE_FINISHED"):
            print("trade succeed")

    def paid(self, out_trade_no):
        # 向alipay发起查询
        result = self.alipay.api_alipay_trade_query(out_trade_no=out_trade_no)
        # 这里的out_trade_no可以用GET到的
        if result.get("trade_status", "") == "TRADE_SUCCESS":
            return result.get('trade_no')  # 这里使用支付宝返回的订单号来显示支付成功
        return 'fail'

    def _get_pay_type(self, type):
        """
        判断支付方式
        """
        pay_type = None
        if type == 'wap':
            pay_type = getattr(self.alipay, 'api_alipay_trade_wap_pay')
        elif type == 'pc':
            pay_type = getattr(self.alipay, 'api_alipay_trade_page_pay')
        elif type == 'app':
            pay_type = getattr(self.alipay, 'api_alipay_trade_app_pay')

        return pay_type