예제 #1
0
파일: views.py 프로젝트: lisongwei1593/demo
 def __query_order(self, transaction_id):
     data = {"transaction_id": transaction_id}
     res = WxNativePayApi.order_query(data)
     if (res.get("return_code") == "SUCCESS" and res.get("result_code") == "SUCCESS"):
         return True
     else:
         return False
예제 #2
0
파일: views.py 프로젝트: lisongwei1593/demo
    def __get_or_create_trade(self, product_order, *args, **kwargs):
        """
        生成微信支付单
        :return:
        """
        try:
            trade = WxPaymentTradeOrder.objects.get(product_id=product_order.order_no)
            return trade
        except WxPaymentTradeOrder.DoesNotExist:
            pass

        now = django.utils.timezone.now()
        expire_time = now + timedelta(seconds=self.__REMAINING_SECONDS)
        trade_no = WxNativePayApi.generate_out_trade_no(product_order.user_id)
        trade = WxPaymentTradeOrder(appid=kwargs['appid'],
                                    mch_id=kwargs['mch_id'],
                                    trade_no=trade_no,
                                    product_id=product_order.order_no,
                                    uid=product_order.user_id,
                                    total_fee=int(product_order.amount * 100),
                                    device_info=self.__DEVICE_INFO,
                                    body=product_order.description if product_order.description else u'蓝图商品',
                                    detail=product_order.detail,
                                    spbill_create_ip=kwargs['spbill_create_ip'],
                                    start_time=now,
                                    time_expire=expire_time,
                                    trade_type=self.__TRADE_TYPE,
                                    original_source=0
                                    )

        trade.save(force_insert=True)
        return trade
예제 #3
0
파일: views.py 프로젝트: lisongwei1593/demo
    def query_and_set_order(trade):
        if trade.transaction_id:
            fromWxData = WxNativePayApi.order_query({'transaction_id': trade.transaction_id})
        else:
            fromWxData = WxNativePayApi.order_query({'out_trade_no': trade.trade_no})
        if fromWxData['return_code'] == 'SUCCESS':

            if fromWxData["result_code"] == "SUCCESS":
                if checkSign(fromWxData) == 0:

                    trade.order_status = WxOrderQueryPayStatusView.__wx_pay_trade_status.get(fromWxData['trade_state'], 1)

                    trade.trade_status_desc = fromWxData.get('trade_state_desc', '')
                    if not trade.transaction_id and 'transaction_id' in fromWxData:
                        trade.transaction_id = fromWxData['transaction_id']
                else:
                    logging.error('from weixin order query: sign error: ' + trade.trade_no)
                    logging.error(fromWxData)
                    return None
            else:
                trade.order_status = 1

            if fromWxData.get('time_end'):
                trade.end_time = datetime.strptime(fromWxData['time_end'], '%Y%m%d%H%M%S')
            trade.wx_result_code = fromWxData['result_code']
            trade.wx_err_code = fromWxData.get('err_code', '')
            trade.wx_err_code_des = fromWxData.get('err_code_des', '')

            with transaction.atomic():  # 支付成功
                if trade.order_status == 3 and trade.is_order_over is False:
                    trade.wx_response = fromWxData
                    trade.is_order_over = True
                    # 通知订单支付成功
                    product_order = ProductOrder.objects.select_for_update().get(order_no=trade.product_id)
                    # product_order.status = 2
                    # product_order.pay_type = 2
                    # product_order.save()
                    notify_order_pay_success(product_order)

                trade.save(force_update=True)
            return trade
        else:
            return None
예제 #4
0
파일: views.py 프로젝트: lisongwei1593/demo
    def __unified_order(self, trade_order, open_id=''):
        m = {}
        # 必需
        m['body'] = trade_order.body if trade_order.body else u'蓝图商品'   # 商品或支付单简要描述
        m['out_trade_no'] = trade_order.trade_no  # 商户系统内部的订单号,32个字符内、可包含字母
        m['total_fee'] = trade_order.total_fee  # 总金额,整数。交易金额默认为人民币交易,接口中参数支付金额单位为【分】,参数值不能带小数。对账单中的交易金额单位为【元】
        m['trade_type'] = 'NATIVE'
        m['spbill_create_ip'] = trade_order.spbill_create_ip

        # 非必要
        m['device_info'] = trade_order.device_info  # 终端设备号(门店号或收银设备ID),注意:PC网页或公众号内支付请传"WEB"
        m['detail'] = trade_order.detail  # 商品名称明细列表
        m['attach'] = ''  # 附加数据,在查询trade_orderAPI和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
        m['fee_type'] = 'CNY'
        m['time_start'] = django.utils.timezone.localtime(trade_order.start_time).strftime('%Y%m%d%H%M%S')  # 订单生成时间,格式为yyyyMMddHHmmss
        m['time_expire'] = django.utils.timezone.localtime(trade_order.time_expire).strftime('%Y%m%d%H%M%S')  # 订单失效时间,格式为yyyyMMddHHmmss。最短失效时间间隔必须大于5分钟
        m['product_id'] = trade_order.product_id  # trade_type=NATIVE,此参数必传。此id为二维码中包含的商品ID,商户自行定义。
        # m['openid'] =   # String(128)  trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。下单前需要调用【网页授权获取用户信息】接口获取到用户的Openid。
        m['limit_pay'] = 'no_credit'

        # 签名
        result = WxNativePayApi.unified_order(m)
        return result
예제 #5
0
파일: views.py 프로젝트: lisongwei1593/demo
    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)