Example #1
0
    def get(self, request, format=None):
        """
        下载对账单
        :param format:
        :return: '成功’:0;'没有权限.',1;"参数错误.",-2;4:订单不存在.
        """
        try:
            bill_date = request.GET['bill_date']
            datetime.strptime(bill_date, '%Y%m%d')
            bill_type = request.GET.get('bill_type','ALL')
            if bill_type not in ['ALL', 'SUCCESS', 'REFUND', 'REVOKE']:
                raise ValueError
        except (KeyError, ValueError):
            return HttpResponseBadRequest(u'缺少必要的参数')

        # ALL,返回当日所有订单信息,默认值
        # SUCCESS,返回当日成功支付的订单
        # REFUND,返回当日退款订单
        # REVOKED,已撤销的订单
        bill_type = 'ALL'
        if bill_type == 'ALL':
            bill_types = ['SUCCESS', 'REFUND']  # 没有REVOKED类型下载
        else:
            bill_types = [bill_type]

        try:

            bills = []
            for bill_type in bill_types:
                params = {}
                params['bill_date'] = bill_date
                params['bill_type'] = bill_type

                # 向微信查询
                r = WxNativePayApi.download_bill(params)
                if isinstance(r, dict):
                    if r.get('return_msg') == 'No Bill Exist':
                        continue
                        # return HttpResponse(u'当天没有指定类型的对账单.')
                    else:
                        logging.exception(u'下载对账单({})失败:'.format(bill_type) + str(r))
                        return HttpResponse(u'下载对账单错误.', status=status.HTTP_500_INTERNAL_SERVER_ERROR)

                content = r.decode('utf-8')

                ls = content.splitlines()
                if len(ls) >= 4:
                    ls.pop()
                    ls.pop()
                    head = ls.pop(0)
                    head = head.split()
                    col_name = []
                    for item in head:
                        if self.__BILL_HAED_COL_NAME.get(item) and hasattr(WxPaymentBill, item):
                            col_name.append(self.__BILL_HAED_COL_NAME.get(item))

                    for l in ls:
                        bill = WxPaymentBill()
                        items = dict(zip(col_name, l.split(',`')))
                        for p in items.items():
                            setattr(bill, p[0], p[1])
                        bills.append(bill)

            if bills:
                WxPaymentBill.objects.bulk_create(bills)

                return HttpResponse(u'下载成功')
            else:
                return HttpResponse(u'当天没有指定类型的对账单.')

        except Exception as e:
            logging.exception(e)
            return HttpResponse(u'下载对账单错误.', status=status.HTTP_500_INTERNAL_SERVER_ERROR)