Exemplo n.º 1
0
    def download(self, bill_date):
        """
        下载对账单,保存到数据库
        :param bill_date: 账单日期,格式:YYYYMMDD
        :return:
        """
        start_time = datetime.strptime(bill_date, '%Y%m%d')
        end_time = start_time + timedelta(days=1)

        try:
            bills = []

            # 向支付宝查询
            for rs in AliPayApi.query_trade(gmt_start_time=start_time, gmt_end_time=end_time):
                for r in rs:
                    bill = AliPaymentBill()
                    bill.transaction_id = r.get('trade_no', '')
                    for ele in self.__MUST_ITEMS:
                        setattr(bill,ele, r[ele])

                    for ele in self.__NOT_MUST_ITEMS:
                        if r.get(ele) is not None and r.get(ele) != '':
                            setattr(bill,ele, r[ele])
                    bills.append(bill)

            if bills:
                AliPaymentBill.objects.bulk_create(bills)

            return len(bills)

        except Exception as e:
            logging.exception(e)
            return -1
Exemplo n.º 2
0
def make_dict_from_xml(content):
    xh = XMLHandler()
    try:
        xml.sax.parseString(content, xh)
        fromWxData = xh.getDict()
        if 'xml' in fromWxData:
            del fromWxData['xml']
    except Exception as e:
        logging.exception(e)
        raise AliPayException(AliPayException.ERROR_XML_FORMAT, e.message)
    return fromWxData
Exemplo n.º 3
0
def checkSign(data):
    temp = {k: v for k,v in data.items()}
    sign = temp.pop('sign')
    sign_type = temp.pop('sign_type')
    if not sign_type or sign_type.lower() == 'md5':
        mysign = makeSign(temp, sign_type)
        ret = 0 if sign == mysign else 1
    elif sign_type.lower() == 'rsa':
        ks = temp.keys()
        ks.sort()
        ls = []
        for k in ks:
            if temp[k] not in (None, ''):
                if isinstance(temp[k], unicode):
                    ls.append('{k}={v}'.format(k=k, v=temp[k].encode('utf8')))
                else:
                    ls.append('{k}={v}'.format(k=k, v=temp[k]))
        s = '&'.join(ls)
        try:
            sh = base64.b64decode(urllib.unquote(sign))
            public_key = rsa.PublicKey.load_pkcs1_openssl_pem(AliPayConfig.ALI_RSA_PUBLIC_KEY)
            ret = 0 if rsa.verify(s, sh, public_key) else 1
        except VerificationError as e:
            logging.exception(e)
            ret = 1
    else:
        raise ValueError()

    if ret != 0:
        logging.exception('check sign faied')
        logging.exception(data)
        logging.exception('the other sign:' + sign)
    return ret
Exemplo n.º 4
0
    def post(self, request, format=None):
        """
        接收支付宝支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给支付宝支付后台
        根据支付结果修改交易单
        :param format:
        :return:
        """
        try:
            logging.info(request.POST)
            notify_data = self.get_notify_data_and_verify(request.POST)

            out_trade_no = notify_data.get('out_trade_no')
            if not out_trade_no:
                return HttpResponse(u'需要out_trade_no')
            with transaction.atomic():
                trade = AliPaymentTradeOrder.objects.select_for_update().get(out_trade_no=out_trade_no)

                if trade.ali_trade_status in ['TRADE_SUCCESS', 'TRADE_FINISHED']:
                    # 已经处理过,直接返回成功接收
                    return Response('success')

                product_order = ProductOrder.objects.select_for_update().get(order_no=trade.order_no)

                trade.order_status = 1
                trade.is_order_over = False
                trade.ali_err_code = notify_data.get('error', '')

                trade.ali_response = notify_data

                trade.save(force_update=True)

                if product_order.status in (0, 1):
                    product_order.status = 3
                product_order.save()

            url = reverse('customer:finance-pay-result', kwargs={'order_pk': product_order.pk})
            return redirect(url)
        except AliPayException as e:
            return HttpResponse('failed')

        except AliPaymentTradeOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse('failed>')
        except ProductOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse('failed')
        except Exception as e:
            logging.exception(e)
            return HttpResponse(body='failed')
Exemplo n.º 5
0
    def get(self, request, format=None):
        """
        接收支付宝支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给前台页面
        根据支付结果修改交易单,通知订单状态发生改变
        :param format:
        :return:
        """

        try:
            logging.info(request.GET)

            notify_data = self.get_notify_data_and_verify(request.GET)

            transaction_id = notify_data.get('trade_no')
            if not transaction_id:
                return HttpResponse('failed')

            out_trade_no = notify_data.get('out_trade_no')
            if not out_trade_no:
                return HttpResponse(u'需要out_trade_no')
            need_notify_order_success = False
            with transaction.atomic():
                trade = AliPaymentTradeOrder.objects.select_for_update().get(out_trade_no=out_trade_no)

                if trade.order_status in (3, 9):
                    # 已经处理过,直接返回成功接收
                    return Response('success')

                product_order = ProductOrder.objects.select_for_update().get(order_no=trade.order_no)

                trade.notify_id = notify_data['notify_id']
                trade.notify_type = notify_data['notify_type']
                trade.notify_time = notify_data['notify_time']

                trade.transaction_id = notify_data.get('trade_no')

                if 'gmt_create' in notify_data:
                    trade.gmt_create = notify_data['gmt_create']
                if 'gmt_payment' in notify_data:
                    trade.gmt_payment = notify_data['gmt_payment']
                if 'gmt_close' in notify_data:
                    trade.gmt_close = notify_data['gmt_close']

                if 'bank_seq_no' in notify_data:
                    trade.bank_seq_no = notify_data['bank_seq_no']

                trade.ali_result_code = notify_data.get('result_code', '')
                trade.ali_err_code = notify_data.get('error', '')
                trade.ali_trade_status = notify_data.get('trade_status', '')
                if trade.ali_trade_status in ['TRADE_SUCCESS', 'TRADE_FINISHED']:
                    trade.order_status = 3
                    need_notify_order_success = True
                    product_order.status = 2
                    product_order.pay_type = 2
                else:
                    trade.order_status = 1
                    product_order.status = 3

                trade.ali_response = notify_data
                trade.is_order_over = True
                trade.save(force_update=True)
                product_order.save()

            if need_notify_order_success:
                # 通知订单支付成功
                notify_order_pay_success(product_order)

            # ctx = {}
            # tpl = ''
            #PayResultView
            # return render(request, tpl, ctx)
            # return PayResultView.render_result(request, order_pk=product_order.pk)
            url = reverse('customer:finance-pay-result', kwargs={'order_pk': product_order.pk})
            return redirect(url)
        except AliPayException as e:
            return HttpResponse(status=status.HTTP_400_BAD_REQUEST)

        except AliPaymentTradeOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse(status=status.HTTP_400_BAD_REQUEST)
        except ProductOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse(status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logging.exception(e)
            return HttpResponse(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 6
0
    def post(self, request, format=None):
        """
        接收支付宝支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给支付宝支付后台
        根据支付结果修改交易单,通知订单状态发生改变
        :param format:
        :return:
        """

        try:
            logging.info(request.data)

            notify_data = self.get_notify_data_and_verify(request.data)

            transaction_id = notify_data.get('trade_no')
            if not transaction_id:
                return HttpResponse('failed')

            out_trade_no = notify_data.get('out_trade_no')
            if not out_trade_no:
                return HttpResponse(u'需要out_trade_no')
            need_notify_order_success = False
            product_order = None
            with transaction.atomic():
                trade = AliPaymentTradeOrder.objects.select_for_update().get(out_trade_no=out_trade_no)

                if trade.order_status in (3, 9):
                    # 已经处理过,直接返回成功接收
                    return Response('success')

                product_order = ProductOrder.objects.select_for_update().get(order_no=trade.order_no)

                trade.notify_id = notify_data['notify_id']
                trade.notify_type = notify_data['notify_type']
                trade.notify_time = notify_data['notify_time']

                trade.transaction_id = notify_data.get('trade_no')

                if 'gmt_create' in notify_data:
                    trade.gmt_create = notify_data['gmt_create']
                if 'gmt_payment' in notify_data:
                    trade.gmt_payment = notify_data['gmt_payment']
                if 'gmt_close' in notify_data:
                    trade.gmt_close = notify_data['gmt_close']

                if 'bank_seq_no' in notify_data:
                    trade.bank_seq_no = notify_data['bank_seq_no']

                trade.ali_result_code = notify_data.get('result_code', '')
                trade.ali_err_code = notify_data.get('error', '')
                trade.ali_trade_status = notify_data.get('trade_status', '')
                if trade.ali_trade_status in ['TRADE_SUCCESS', 'TRADE_FINISHED']:
                    trade.order_status = 3
                    need_notify_order_success = True
                    product_order.status = 2
                    product_order.pay_type = 2
                else:
                    trade.order_status = 1
                    product_order.status = 3

                trade.ali_response = notify_data
                trade.is_order_over = True
                trade.save(force_update=True)
                product_order.save()

            if need_notify_order_success:
                # 通知订单支付成功
                notify_order_pay_success(product_order)

            content = 'success'
            return HttpResponse(content)
        except AliPayException as e:
            return HttpResponse('failed')

        except AliPaymentTradeOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse('failed>')
        except ProductOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse('failed')
        except Exception as e:
            logging.exception(e)
            return HttpResponse(body='failed')
Exemplo n.º 7
0
    def get(self, order_no, user, pay_service_type, sign_type='MD5', bank_code=''):
        """

        :param order_no: 市场订单号
        :param user: user,用于检索订单条件
        :param pay_service_type: 支付业务类型。即时到账,网银支付,移动支付等
        :param bank_code: pay_service_type为网银支付时为默认银行代码,其他类型无意义
        :param sign_type: 加密类型
        :return: dict  'pay_status':0,未支付;1:已支付。
                        'form': 'actions': form action
                                params:input value,key:name;value:value.
        """
        # ①不存在----记录,
        # ②已经撤单---记录   ---- 购买不能撤单
        ctx = {}
        try:
            # order_no = '123'
            if not order_no or pay_service_type not in ('direct_pay', 'bank_pay', 'mobile'):
                raise ValueError
            # 根据订单号取订单
            with transaction.atomic():
                product_order = ProductOrder.objects.select_for_update().get(order_no=order_no, user=user)
                # ③已经支付---不做处理
                if self.has_payed(product_order):
                    ctx['pay_status'] = 1
                    return ctx
                # ④支付中
                # elif self.is_paying(product_order):
                #     return HttpResponseBadRequest(u'订单支付进行中')
                # ⑤未支付----修改交易单状态,记录,通知
                else:
                    pass
        except (KeyError, ValueError):
            return ValueError(u'缺少订单号')
        except ProductOrder.DoesNotExist as e:
            logging.exception(e)
            return ValueError(u'订单不存在')

        # 生成交易单
        ali_trade_order = None
        for ele in AliPaymentTradeOrder.objects.filter(order_no=product_order.order_no):

            if ele.order_status == 10:    #预支付中,查询订单状态
                r = self.query_and_set_order(ele)
            else:
                r = ele

            if r and r.order_status in [3,9]:  # 已经支付
                notify_order_pay_success(product_order)
                ctx['pay_status'] = 1
                return ctx
            elif r and r.pay_service_type == pay_service_type:
                ali_trade_order = r

        ctx['bank_code'] = bank_code
        ctx['pay_status'] = 0
        if not ali_trade_order:
            ali_trade_order = self.__create_trade(product_order, pay_service_type, bank_code=bank_code)

        # ali_trade_order = self.__get_or_create_trade(product_order, pay_service_type)
        # if ali_trade_order.order_status in (0,1,2):
        #     pass
        # elif ali_trade_order.order_status == 10:    #预支付中,查询订单状态
        #     r = self.query_and_set_order(ali_trade_order)
        #     if not r:
        #         ali_trade_order = r
        #
        # if ali_trade_order.order_status in (3,9):  # 已经支付
        #     notify_order_pay_success(product_order)
        #     ctx['pay_status'] = 1
        #     return ctx
        # else:
        #     ctx['pay_status'] = 0

        ctx['form'] = self.create_form_input_value(ali_trade_order, pay_service_type, bank_code, sign_type)

        return ctx