Exemplo n.º 1
0
    def alipay_query(cls, out_trade_no, trade_no, receipt, trade_type):
        '''alipay query'''
        try:
            config_dict = {
                VIPOrder.PAY_TYPE_BY_ALIPAY_APP: settings.ALIPAY_APP_INFO,
                VIPOrder.PAY_TYPE_BY_ALIPAY: settings.ALIPAY_APP_INFO,
            }
            config = config_dict[trade_type]
            alipay_client_config = AlipayClientConfig()
            alipay_client_config.app_id = smart_str(config['basic_info']['APP_ID'])
            alipay_client_config.sign_type = smart_str(config['other_info']['SIGN_TYPE'])
            with open(config['basic_info']['APP_PRIVATE_KEY'], 'r') as fp:
                alipay_client_config.app_private_key = fp.read()
            client = DefaultAlipayClient(alipay_client_config=alipay_client_config)

            model = AlipayTradeQueryModel()
            model.out_trade_no = smart_str(out_trade_no)
            if trade_no:
                model.trade_no = smart_str(trade_no)
            request = AlipayTradeQueryRequest(biz_model=model)

            request_params = client.sdk_execute(request)
            resp = requests.get('{}?{}'.format(SERVER_URL, request_params)).json()
            log.info('********** alipay query result ***********')
            log.info(resp)
            query_resp = resp['alipay_trade_query_response']
            return {
                'trade_status': query_resp.get('trade_status') == 'TRADE_SUCCESS',
                'total_fee': float(query_resp.get('total_amount', 0)),
                'refno': query_resp.get('trade_no', ''),
            }
        except Exception, e:
            log.exception(e)
Exemplo n.º 2
0
 def precreate(self):
     for res in self:
         client = self.env['alipay.transfer'].get_config_client()
         alipay_model = AlipayTradeQueryModel()
         alipay_model.out_trade_no = res.out_biz_no  # 编号
         alipay_request = AlipayTradeQueryRequest(alipay_model)
         result = client.execute(alipay_request)
         logging.info(">>>支付宝查询交易结果:{}".format(result))
         result = json.loads(result, 'utf-8')
         if result.get('code') == '10000':
             if result.get('trade_status') == 'WAIT_BUYER_PAY':
                 res.precreate_id.message_post(body="等待买家付款", message_type='notification')
             elif result.get('trade_status') == 'TRADE_CLOSED':
                 res.precreate_id.message_post(body="未付款交易超时关闭,或支付完成后全额退款", message_type='notification')
                 res.precreate_id.write({
                     'state': '03',
                     'pay_time': datetime.datetime.now(),
                 })
             elif result.get('trade_status') == 'TRADE_SUCCESS':
                 res.precreate_id.message_post(body="交易支付成功", message_type='notification')
                 user = self.create_alipay_user(result)
                 res.precreate_id.write({
                     'state': '02',
                     'pay_time': datetime.datetime.now(),
                     'trade_no': result.get('trade_no'),
                     'alipay_user': user.id,
                 })
             elif result.get('trade_status') == 'TRADE_FINISHED':
                 res.precreate_id.message_post(body="交易结束,不可退款", message_type='notification')
         else:
             res.precreate_id.message_post(body="等待扫码付款...", message_type='notification')
Exemplo n.º 3
0
    def query(self, out_trade_no):
        '''
        系统接口示例:alipay.trade.query
        '''
        # 对照接口文档,构造请求对象
        query_model = AlipayTradeQueryModel()
        query_model.out_trade_no = out_trade_no

        query_request = AlipayTradeQueryRequest(biz_model=query_model)
        query_response_content = None
        ret_dict = {}
        try:
            query_response_content = self.client.execute(query_request)
        except Exception as e:
            print(traceback.format_exc())

        if not query_response_content:
            print("failed execute query")
        else:
            query_response = AlipayTradeQueryResponse()
            # 解析响应结果
            query_response.parse_response_content(query_response_content)
            if query_response.is_success():
                # 如果业务成功,则通过respnse属性获取需要的值
                ret_dict['out_trade_no'] = query_response.out_trade_no
                ret_dict['buyer_logon_id'] = query_response.buyer_logon_id
                ret_dict['trade_status'] = query_response.trade_status
                ret_dict['total_amount'] = query_response.total_amount
            else:
                # 如果业务失败,则从错误码中可以得知错误情况,具体错误码信息可以查看接口文档
                print(query_response.code + "," + query_response.msg + "," +
                      query_response.sub_code + "," + query_response.sub_msg)
        return ret_dict
Exemplo n.º 4
0
 def order_status_query(self, order_id):
     model = AlipayTradeQueryModel()
     model.out_trade_no = order_id
     request = AlipayTradeQueryRequest(biz_model=model)
     response_content = self.client.execute(request)
     response = AlipayTradeQueryResponse()
     response.parse_response_content(response_content)
     return response
Exemplo n.º 5
0
    def post(self):

        bid = self.get_argument('bid')
        out_trade_no = self.get_argument('out_trade_no')
        payConfig = self.DefaultValues[bid]

        # 设置配置信息
        alipay_client_config = AlipayClientConfig()
        alipay_client_config.server_url = payConfig['zfbpay']['url']
        alipay_client_config.app_id = payConfig['zfbpay']['appId']
        alipay_client_config.app_private_key = payConfig['zfbpay']['app_private_key']
        alipay_client_config.alipay_public_key = payConfig['zfbpay']['alipay_public_key']

        # 客户端对象
        client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)

        # 构造请求对象
        model = AlipayTradeQueryModel()
        model.out_trade_no = out_trade_no
        request = AlipayTradeQueryRequest(biz_model=model)
        response_content = None
        try:
            response_content = client.execute(request)
        except Exception as e:
            print('1-' + traceback.format_exc())
        if not response_content:
            print( "2-failed execute")
        else:
            response = AlipayTradeQueryResponse()
            # 解析响应结果
            response.parse_response_content(response_content)
            print(response.body)
            if response.is_success():
                # 业务成功,则通过respnse属性获取需要的值
                print("业务成功- get response trade_no:" + response.trade_no)
                info = {
                    'errCode': '0',
                    'errMsg':  '',
                    'detail': {
                        'trade_no': response.trade_no
                    }
                }
                result = {
                    'result': info
                }
                self.write(json.dumps(result, ensure_ascii=False))
            else:
                # 业务失败
                print('业务失败-' + response.code + "," + response.msg + "," + response.sub_code + "," + response.sub_msg)
                info = {
                    'errCode': response.code,
                    'errMsg':  response.sub_msg
                }
                result = {
                    'result': info
                }
                self.write(json.dumps(result, ensure_ascii=False))
Exemplo n.º 6
0
    def post(self, request):
        """查询POST请求"""
        while True:
            # 检测订单状态
            if order.order_status > 1:
                print('支付宝内部修改成功!')
                return JsonResponse({'res': 0, 'msg': '支付成功!'})
            # 发送查询请求
            client = AlipayView.sign(AlipayView.logger())

            # 构造请求对象
            model = AlipayTradeQueryModel()
            model.out_trade_no = order_id
            req = AlipayTradeQueryRequest(biz_model=model)

            # 执行请求操作
            try:
                response_content = client.execute(req)
            except Exception as e:
                return JsonResponse({'res': -1, 'msg': e})
            if response_content:
                # 解析响应结果
                response = AlipayTradeQueryResponse()
                response.parse_response_content(response_content)
                # 响应成功的业务处理
                if response.is_success():
                    # 成功
                    if response.trade_status == 'TRADE_SUCCESS':
                        return JsonResponse({'res': 0, 'msg': '支付成功!'})
                    # 等待付款
                    elif response.trade_status == 'WAIT_BUYER_PAY':
                        time.sleep(settings.ALIPAY_TIMEOUT_SLEEP_SECS)
                        continue
                    else:
                        return JsonResponse({'res': -1, 'msg': '支付失败'})
                # 等待创建交易
                elif response.code == '40004':
                    # 创建交易超时
                    if (expire_time > settings.ALIPAY_TIMEOUT_MINUTE * 60):
                        return JsonResponse({'res': -1, 'msg': '创建交易超时'})
                    expire_time += settings.ALIPAY_TIMEOUT_SLEEP_SECS
                    time.sleep(settings.ALIPAY_TIMEOUT_SLEEP_SECS)
                    continue
                else:
                    return JsonResponse({'res': -1, 'msg': '支付失败'})
Exemplo n.º 7
0
    def get_pay_status(cls, order_id):
        # 获取内容
        with open(ALIPAY_KEY_PATH) as f:
            alipay_public_key = f.read()

        with open(APP_KEY_PRIVATE_PATH) as f:
            app_private_key = f.read()

        #  设置配置,包括支付宝网关地址、app_id、应用私钥、支付宝公钥;
        config = AlipayClientConfig()
        config.server_url = settings.SERVER_URL
        config.app_id = settings.APP_ID
        config.app_private_key = app_private_key
        config.alipay_public_key = alipay_public_key

        # 得到
        client = DefaultAlipayClient(alipay_client_config=config)
        model = AlipayTradeQueryModel()
        model.out_trade_no = order_id
        request = AlipayTradeQueryRequest(biz_model=model)
        # 得到构造的请求,获取返回内容
        import time
        i = 1
        while True:
            time.sleep(10)
            response_content = None
            try:
                response_content = client.execute(request)
            except Exception as ex:
                print(ex)
            if not response_content:
                return None
            else:
                # 解析相应结果
                response = AlipayTradeQueryResponse()
                response.parse_response_content(response_content)
                if response.is_success(
                ) and response.trade_status == 'TRADE_SUCCESS':
                    return response.trade_no
                i += 1
                if i == 30:
                    # 五分钟后还是失败
                    # 判定支付失败
                    return None
Exemplo n.º 8
0
def alipay_trade_query(order):
    """查询订单结果"""
    client = alipay_base_config()
    # 对照接口文档,构造请求对象
    model = AlipayTradeQueryModel()
    # 通过先前提交的订单号(非支付宝订单号),查询支付结果
    model.out_trade_no = order.order_id
    request = AlipayTradeQueryRequest(biz_model=model)

    response_content = None
    try:
        # 执行请求,返回结果是一个字符串,实际这个值已经够用了
        response_content = client.execute(request)
    except Exception as e:
        print(traceback.format_exc())

    if not response_content:
        print("failed execute")
    else:
        # 将响应结果的字符串数据转化未JSON数据,应该不会再发送请求!!!
        response = AlipayTradeQueryResponse()
        # 解析响应结果
        response.parse_response_content(response_content)
        return response
Exemplo n.º 9
0
    def post(self, request):
        """查看订单支付状态"""
        # 判断用户登录
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': '用户未登陆'})

        # 接收参数
        order_id = request.POST.get('order_id')

        # 校验参数
        if not order_id:
            return JsonResponse({'res': 1, 'errmsg': '参数不完整'})

        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=user,
                                          pay_method=3,
                                          order_status=1)
        except OrderInfo.DoesNotExist:
            return JsonResponse({'res': 2, 'errmsg': '无效的订单id'})

        """
        设置配置,包括支付宝网关地址、app_id、应用私钥、支付宝公钥等,其他配置值可以查看AlipayClientConfig的定义。
        """
        alipay_client_config = AlipayClientConfig()
        alipay_client_config.server_url = 'https://openapi.alipaydev.com/gateway.do'
        alipay_client_config.app_id = '2016100100641374'
        app_private_key = ''
        with open(os.path.join(settings.BASE_DIR, 'apps/order/app_private_key.pem'), 'r') as f:
            for line in f:
                app_private_key += line
        alipay_client_config.app_private_key = app_private_key
        alipay_public_key = ''
        with open(os.path.join(settings.BASE_DIR, 'apps/order/alipay_public_key.pem'), 'r') as f:
            for line in f:
                alipay_public_key += line
        alipay_client_config.alipay_public_key = alipay_public_key
        """
        得到客户端对象。
        注意,一个alipay_client_config对象对应一个DefaultAlipayClient,定义DefaultAlipayClient对象后,alipay_client_config不得修改,如果想使用不同的配置,请定义不同的DefaultAlipayClient。
        logger参数用于打印日志,不传则不打印,建议传递。
        """
        client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)

        total_pay = order.transit_price + order.total_price
        total_pay = round(float(total_pay), 2)
        model = AlipayTradePagePayModel()
        model.out_trade_no = order_id
        model.total_amount = total_pay
        model.subject = "天天生鲜{0}".format(order_id)
        model.product_code = "FAST_INSTANT_TRADE_PAY"

        while True:
            request = AlipayTradeQueryRequest(biz_model=model)
            response = client.page_execute(request, http_method="GET")
            data = requests.get(response)
            data = json.loads(data.text)
            code = data.get('alipay_trade_query_response').get('code')

            trade_status = data.get('alipay_trade_query_response').get('trade_status')
            print(code, trade_status)

            if code == '10000' and trade_status == 'TRADE_SUCCESS':
                # 支付成功
                # 获取支付宝交易号
                trade_no = data.get('alipay_trade_query_response').get('code')
                # 更新订单状态
                order.trade_no = trade_no
                order.order_status = 4
                order.save()
                # 返回结果
                return JsonResponse({'res': 3, 'message': '支付成功'})

            elif code=='40004' or (code == '10000' and trade_status == 'WAIT_BUYER_PAY'):
                # 等待卖家付款
                import time
                time.sleep(5)
                continue
            else:
                # 支付出错
                return JsonResponse({'res': 4, 'errmsg': '支付失败'})
Exemplo n.º 10
0
    def post(self, request):
        """查询支付结果"""
        # 校验用户是否登录'
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': '用户未登录'})

        # 接收参数
        order_id = request.POST.get('order_id')

        # 校验参数
        if not order_id:
            return JsonResponse({'res': 1, 'errmsg': '无效的订单id'})

        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=user,
                                          pay_method=3,
                                          order_status=1)
        except OrderInfo.DoesNotExist:
            return JsonResponse({'res': 2, 'errmsg': '订单错误'})

        # todo: 业务处理 使用python的SDK 调用支付宝的支付接口
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s %(levelname)s %(message)s',
            filemode='a',
        )
        logger = logging.getLogger('')
        """
            设置配置,包括支付宝网关地址、app_id、应用私钥、支付宝公钥等,其他配置值可以查看AlipayClientConfig的定义。
        """
        alipay_client_config = AlipayClientConfig(sandbox_debug=True)
        alipay_client_config.server_url = 'https://openapi.alipaydev.com/gateway.do'
        alipay_client_config.app_id = '2016101900724693'  # 应用id 这里是沙箱id
        alipay_client_config.charset = 'utf-8'

        with open(
                os.path.join(settings.BASE_DIR,
                             'apps/order/app_private_key.txt')) as f:
            alipay_client_config.app_private_key = f.read()

        with open(
                os.path.join(settings.BASE_DIR,
                             'apps/order/alipay_public_key.txt')) as f:
            alipay_client_config.alipay_public_key = f.read()

        alipay_client_config.sign_type = 'RSA2'  # RSA或RSA2
        """
            得到客户端对象。
            注意,一个alipay_client_config对象对应一个DefaultAlipayClient,定义DefaultAlipayClient对象后,
            alipay_client_config不得修改,如果想使用不同的配置,请定义不同的DefaultAlipayClient。
            logger参数用于打印日志,不传则不打印,建议传递。
            """
        client = DefaultAlipayClient(alipay_client_config=alipay_client_config,
                                     logger=logger)

        while True:
            # 对照接口文档,构造请求对象
            model = AlipayTradeQueryModel()
            model.out_trade_no = order_id

            query_request = AlipayTradeQueryRequest(biz_model=model)
            response = self.str_to_dict(client.execute(query_request))
            """
                response:
                {
                    "code":"10000",  # 接口调用是否成功
                    "msg":"Success",
                    "buyer_logon_id":"mnd***@sandbox.com",
                    "buyer_pay_amount":"0.00",
                    "buyer_user_id":"2088102180300991",
                    "buyer_user_type":"PRIVATE",
                    "invoice_amount":"0.00",
                    "out_trade_no":"2020010122413118",
                    "point_amount":"0.00",
                    "receipt_amount":"0.00",
                    "total_amount":"39.90",
                    "trade_no":"2020010422001400991000047401",  # 支付宝交易号
                    "trade_status":"WAIT_BUYER_PAY" # 支付结果
                }
            """

            code = response.get('code')
            if code == '10000' and response.get(
                    'trade_status') == 'TRADE_SUCCESS':
                # 支付成功
                # 获取支付宝交易号
                trade_no = response.get('trade_no')
                # 更新订单状态
                order.trade_no = trade_no
                order.order_status = 4  # 待评价
                order.save()
                # 返回结果
                return JsonResponse({'res': 3, 'message': '支付成功'})
            elif code == '40004' or code == '10000' and response.get(
                    'trade_status') == 'WAIT_BUYER_PAY':
                # 等待买家付款
                # 业务处理失败 可能一会会成功
                time.sleep(5)
                continue
            else:
                # 支付出错
                return JsonResponse({'res': 4, 'errmsg': '支付失败'})