コード例 #1
0
ファイル: work.py プロジェクト: lisongwei1593/demo
    def query_and_set_order(cls, trade):
        if trade.transaction_id:
            resp_data = AliPayApi.query_single_trade({'transaction_id': trade.transaction_id})
        else:
            resp_data = AliPayApi.query_single_trade({'out_trade_no': trade.trade_no})
        if resp_data['is_success'] == 'T':

            if checkSign(resp_data) != 0:
                logging.error('from ali pay single order query: sign error: ' + trade.trade_no)
                logging.error(resp_data)
                return None

            trade.transaction_id = resp_data['trade_no']
            trade.gmt_create = resp_data['gmt_create']
            if 'gmt_payment' in resp_data:
                trade.gmt_payment = resp_data['gmt_payment']
            if 'gmt_last_modified_time' in resp_data:
                trade.gmt_last_modified_time = resp_data['gmt_last_modified_time']
            if 'time_out' in resp_data:
                trade.time_out = resp_data['time_out']
            if 'gmt_close' in resp_data:
                trade.gmt_close = resp_data['gmt_close']
            if 'time_out_type' in resp_data:
                trade.time_out_type = resp_data['time_out_type']

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

            trade.ali_result_code = resp_data['result_code']
            trade.ali_err_code = resp_data.get('error', '')
            trade.ali_trade_status = resp_data.get('trade_status', '')
            if trade.ali_trade_status == 'TRADE_SUCCESS':   # 支付成功
                trade.order_status = 3
            with transaction.atomic():  # 支付成功
                if trade.order_status in (3,9) and trade.is_order_over is False:
                    trade.ali_response = resp_data
                    trade.is_order_over = True
                    trade.save(force_update=True)
                    # 通知订单支付成功
                    product_order = ProductOrder.objects.select_for_update().get(order_no=trade.order_no)
                    # product_order.status = 2
                    # product_order.pay_type = 2
                    notify_order_pay_success(product_order)
                else:
                    trade.save(force_update=True)
            return trade
        else:
            return None
コード例 #2
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
コード例 #3
0
ファイル: views.py プロジェクト: lisongwei1593/demo
    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)
コード例 #4
0
ファイル: views.py プロジェクト: lisongwei1593/demo
    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')
コード例 #5
0
ファイル: work.py プロジェクト: lisongwei1593/demo
    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
コード例 #6
0
ファイル: views.py プロジェクト: lisongwei1593/demo
    def post(self, request, format=None):
        """
        接收微信支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给微信支付后台
        根据支付结果修改交易单,通知订单状态发生改变
        :param format:
        :return:
        """

        try:
            logging.info(request.data)

            notify_data = self.get_notify_data(request.data)
            if isinstance(notify_data, HttpResponse):
                return notify_data

            transaction_id = notify_data.get('transaction_id')
            if not transaction_id:
                return HttpResponse('<xml><return_code><![CDATA[FAIL]]></return_code>'
                                    '<return_msg><![CDATA[支付结果中微信订单号不存在]]></return_msg></xml>')
            elif self.__query_order(transaction_id) == False:
                logging.error(u'订单查询失败' + str(notify_data))
                return HttpResponse('<xml><return_code><![CDATA[FAIL]]></return_code>'
                                    '<return_msg><![CDATA[订单查询失败]]></return_msg></xml>')

            if notify_data["return_code"] != "SUCCESS":
                data = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[通信失败]]></return_msg></xml>'
                return HttpResponse(data)

            trade_no = notify_data.get('out_trade_no')
            if not trade_no:
                logging.error(u'订单通知失败,缺少必要参数out_trade_no : ' + str(notify_data))
                return HttpResponse('<xml><return_code><![CDATA[FAIL]]></return_code>'
                                '<return_msg><![CDATA[缺少必要的参数:out_trade_no]]></return_msg></xml>')

            need_notify_order_success = False
            with transaction.atomic():
                trade = WxPaymentTradeOrder.objects.select_for_update().get(trade_no=trade_no)

                if trade.order_status not in (0, 2):
                    # 已经处理过,直接返回成功接收
                    return Response(data=self.__success_data, status=status.HTTP_200_OK)

                product_order = ProductOrder.objects.select_for_update().get(order_no=trade.product_id)
                trade.transaction_id = notify_data.get('transaction_id')
                if not trade.prepay_id and notify_data.get('prepay_id'):
                    trade.prepay_id = notify_data.get('prepay_id')
                if notify_data['result_code'] == 'SUCCESS':
                    trade.order_status = 3
                    product_order.status = 2
                    product_order.pay_type = 2
                else:
                    trade.order_status = 1
                    product_order.status = 3
                if notify_data.get('time_end'):
                    trade.end_time = datetime.strptime(notify_data['time_end'], '%Y%m%d%H%M%S')
                trade.wx_result_code = notify_data['result_code']
                trade.wx_err_code = notify_data.get('err_code', '')
                trade.wx_err_code_des = notify_data.get('err_code_des', '')
                trade.wx_response = notify_data

                if trade.order_status == 3 and trade.is_order_over is False:
                    trade.is_order_over = True
                    need_notify_order_success = True

                trade.save(force_update=True)
                product_order.save()

            if need_notify_order_success:
                # 通知订单支付成功
                notify_order_pay_success(product_order)
            content = '<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>'
            return HttpResponse(content)
        except WxPaymentTradeOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse('<xml><return_code><![CDATA[FAIL]]></return_code>'
                                '<return_msg><![CDATA[该订单号不存在]]></return_msg></xml>')
        except ProductOrder.DoesNotExist as e:
            logging.exception(e)
            return HttpResponse('<xml><return_code><![CDATA[FAIL]]></return_code>'
                                '<return_msg><![CDATA[该订单不存在]]></return_msg></xml>')
        except Exception as e:
            logging.exception(e)
            return HttpResponse(body='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg></return_msg></xml>', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
コード例 #7
0
ファイル: views.py プロジェクト: lisongwei1593/demo
    def get(self, request, data_format=None, *args, **kwargs):
        # user = request.user
        data = request.GET
        if data_format == 'json' or data.get('data_format') == 'json':
            is_json = True
        else:
            is_json = False

        # ①不存在----记录,
        # ②已经撤单---记录   ---- 购买不能撤单
        try:
            order_no = data['order_no']
            # order_no = '123'
            if not order_no:
                raise ValueError
        except (KeyError, ValueError):
            return HttpResponseBadRequest(u'缺少订单号')

        try:

            with transaction.atomic():
                # 根据订单号取订单
                product_order = ProductOrder.objects.select_for_update().get(order_no=order_no)
                # ③已经支付---不做处理
                if self.has_payed(product_order):
                    if is_json:
                        return JsonResponse({'msg': u'订单已支付', 'code': 1,})
                    else:
                        return HttpResponseBadRequest(u'订单已支付')
                # ④支付中
                # elif self.is_paying(product_order):
                #     return HttpResponseBadRequest(u'订单支付进行中')
                # ⑤未支付----修改交易单状态,记录,通知
                # 生成交易单
                wx_trade_order = self.__get_or_create_trade(product_order,
                                                            appid=WxNativePaymentConstData.APP_ID,
                                                            mch_id=WxNativePaymentConstData.MCH_ID,
                                                            spbill_create_ip=WxNativePaymentConstData.IP)
                wx_trade_order = WxPaymentTradeOrder.objects.select_for_update().get(pk=wx_trade_order.pk)

                now = datetime.today() if wx_trade_order.time_expire.tzinfo is None else django.utils.timezone.now()
                if wx_trade_order.order_status==9 or (wx_trade_order.order_status in (0,1,4) and (not wx_trade_order.code_url or wx_trade_order.time_expire < now)):
                    try:
                        if wx_trade_order.time_expire <= now:
                            wx_trade_order.start_time = django.utils.timezone.now()
                            wx_trade_order.time_expire = wx_trade_order.start_time + timedelta(seconds=self.__REMAINING_SECONDS)
                            wx_trade_order.code_url = ''
                            wx_trade_order.save()
                        # 调用统一下单api
                        fromWxData = self.__unified_order(wx_trade_order)

                        wx_trade_order.wx_return_code = fromWxData['return_code']
                        wx_trade_order.wx_return_msg = fromWxData['return_msg']
                        wx_trade_order.wx_response = fromWxData
                        if fromWxData['return_code'] == 'SUCCESS':  #通信成功 #交易成功
                            if not fromWxData.get("appid") or not fromWxData.get("mch_id") or not fromWxData.get("code_url"):
                                raise Exception(message='统一下单失败,返回值缺少必要参数')
                            if fromWxData['result_code'] == 'SUCCESS':
                                wx_trade_order.order_status = 2
                                wx_trade_order.wx_prepay_id = fromWxData.get('prepay_id', '')
                                wx_trade_order.code_url = fromWxData.get('code_url')
                                # product_order.status = 2
                                product_order.pay_type = 2
                                product_order.save()
                            else:
                                wx_trade_order.order_status = 9

                            wx_trade_order.wx_result_code = fromWxData['result_code']
                            wx_trade_order.wx_err_code = fromWxData.get('err_code', '')
                            wx_trade_order.wx_err_code_des = fromWxData.get('err_code_des', '')
                        else:
                            wx_trade_order.order_status = 9

                        wx_trade_order.save()
                    except Exception as e:
                        print '1'
                        logging.exception(u'统一下单失败 :' + e.message)
                        wx_trade_order.comment = u'统一下单失败'
                        wx_trade_order.order_status = 9
                        wx_trade_order.save()
                        if is_json:
                            print '2'
                            return JsonResponse({'msg': u'二维码生成失败', 'code': -1,})
                        else:
                            print '3'
                            return HttpResponse(u'二维码生成失败')

                    if not wx_trade_order.code_url or wx_trade_order.order_status == 9:
                        if wx_trade_order.wx_err_code in ['ORDERPAID', 'ORDERCLOSED', 'OUT_TRADE_NO_USED']:
                            return HttpResponse(WxNativePaymentConstData.UnifiedOrderErrorCodeMsg[wx_trade_order.wx_err_code])
                        else:
                            logging.exception('统一下单失败')
                            if is_json:
                                print '4'
                                return JsonResponse({'msg': u'二维码生成失败', 'code': -1,})
                            else:
                                print '5'
                                return HttpResponse(u'二维码生成失败')
                elif wx_trade_order.order_status == 2: #预支付中,查询订单状态
                    r = WxOrderQueryPayStatusView.query_and_set_order(wx_trade_order)
                    if r:
                        wx_trade_order = r

                if wx_trade_order.order_status == 3:  # 已经支付
                    notify_order_pay_success(product_order)
                    if is_json:
                        return JsonResponse({'msg': u'已经支付', 'code': 1,})
                    else:
                        return HttpResponse(u'已经支付')

                ctx = {'msg': '', 'code': 0,}
                ctx['order_no'] = order_no
                ctx['price'] = product_order.amount
                now = datetime.today() if wx_trade_order.time_expire.tzinfo is None else django.utils.timezone.now()
                ctx['remaining_seconds'] = (wx_trade_order.time_expire-now).seconds
                if ctx['remaining_seconds']<0:
                    ctx['remaining_seconds'] = 0
                if not wx_trade_order.code_url_img_url or wx_trade_order.time_expire >= django.utils.timezone.now() or not os.path.exists(wx_trade_order.code_url_img_path):
                    prepay_url = wx_trade_order.code_url
                    wx_trade_order.code_url_img_url, wx_trade_order.code_url_img_path = generate_qrcode(prepay_url)
                    wx_trade_order.save()

            ctx['qr_code_url'] = wx_trade_order.code_url_img_url

            tpl = 'customer/finance/wx/pay/pay_home.html'

            if is_json:
                return JsonResponse(ctx)
            else:
                return render(request, tpl, ctx)
        except ProductOrder.DoesNotExist:
            if is_json:
                return JsonResponse({'msg': u'订单不存在', 'code': -2,})
            else:
                return HttpResponseBadRequest(u'订单不存在')