def test_purchase_no_fitting_order(self):
        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            62000,  # total fee
            10,  # expire_minute
            'heepay',
            None,  # no payment account should let it go through initial check
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='人民币充值测试-没有合适卖单',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()
        request_str = request.getPayload()
        print('send request {0}'.format(request_str))
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')

        print('response is {0}'.format(
            json.dumps(json.loads(response.content.decode('utf-8')),
                       ensure_ascii=False)))

        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(resp_json['return_code'], 'FAIL')
        self.assertEqual(resp_json['return_msg'], '无卖单提供充值')
Exemple #2
0
    def test_redeem_api_call(self):
        if not settings.TEST_REAL_CALL:
            print('Donot run real call test')
            return
        app_id = TEST_API_USER1_APPKEY
        secret_key = TEST_API_USER1_SECRET
        test_out_trade_no = 'order_test_redeem'
        test_purchase_amount = TEST_PURCHASE_AMOUNT
        test_user_heepay_from_account = '13910978598'
        test_attach = 'userid:1'
        test_subject = '人民币提现成功测试'
        test_notify_url = 'http://52.43.117.129/api/v1/api_notify_test/'
        test_return_url = 'http://52.43.117.129/api/v1/api_notify_test/'
        request = TradeAPIRequest(
            API_METHOD_REDEEM,
            app_id,
            secret_key,
            test_out_trade_no,  # out_trade_no
            total_fee=test_purchase_amount,  # total fee
            expire_minute=10,  # expire_minute
            payment_provider='heepay',
            payment_account=test_user_heepay_from_account,
            client_ip='127.0.0.1',  #client ip
            attach=test_attach,
            subject=test_subject,
            notify_url=test_notify_url,
            return_url=test_return_url)

        c = APIClient('http://52.43.117.129/api/v1/applyredeem/')
        request_str = request.getPayload()
        resp_json = c.send_json_request(json.loads(request_str))
        print('reply is {0}'.format(json.dumps(resp_json, ensure_ascii=False)))
    def test_purchase_bad_user_account(self):
        #self.create_no_fitting_order()
        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            'user_does_not_exist',
            'secret_key_not_exist',
            'order_no_order',  # order id
            None,  # trx_id
            620,  # total fee
            10,  # expire_minute
            'heepay',
            '12738456',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='人民币充值测试-账号不存在',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()
        request_str = request.getPayload()
        print('send request {0}'.format(request_str))
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')

        print('response is {0}'.format(
            json.dumps(json.loads(response.content.decode('utf-8')),
                       ensure_ascii=False)))

        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(2, len(resp_json))
        self.assertEqual(resp_json['return_code'], 'FAIL')
        self.assertEqual(resp_json['return_msg'], '用户不存在')
Exemple #4
0
def parseUserInput(request_json):
    logger.debug('parseUserInput {0}'.format(request_json))
    logger.debug('parseUserInput to string {0}'.format(
        json.dumps(request_json, ensure_ascii=False)))
    request_obj = TradeAPIRequest.parseFromJson(request_json)
    api_user = APIUserManager.get_api_user_by_apikey(request_obj.apikey)
    return request_obj, api_user
Exemple #5
0
    def test_validate_request(self):
        request_json = {
            "method": "wallet.trade.buy",
            "version": "1.0",
            "api_key": "L2CLMSBYJAPF0HX0PY4VIW0XFPCNT6Y8",
            "charset": "utf-8",
            "sign_type": "MD5",
            "timestamp": "20180630064937",
            "biz_content":
            "{\"api_account_type\":\"Account\",\"attach\":\"1235\",\"client_ip\":\"42.96.158.70\",\"expire_minute\":\"0\",\"meta_option\":\"123\",\"notify_url\":\"http://game.p2pinfo.cn/api_notify.php\",\"out_trade_no\":\"2018063006493725900\",\"payment_account\":\"13910978598\",\"payment_provider\":\"heepay\",\"return_url\":\"http://game.p2pinfo.cn/api_notify.php\",\"subject\":\"test\",\"total_fee\":\"1\"}",
            "sign": "E5AFC1466C676A2277DA3DC218480256"
        }
        request_obj = TradeAPIRequest.parseFromJson(request_json)

        str1 = 'api_key=L2CLMSBYJAPF0HX0PY4VIW0XFPCNT6Y8&biz_content={"api_account_type":"Account","attach":"1235","client_ip":"42.96.158.70","expire_minute":"0","meta_option":"123","notify_url":"http://game.p2pinfo.cn/api_notify.php","out_trade_no":"2018063006493725900","payment_account":"13910978598","payment_provider":"heepay","return_url":"http://game.p2pinfo.cn/api_notify.php","subject":"测试","total_fee":"1"}&charset=utf-8&method=wallet.trade.buy&sign_type=MD5&timestamp=20180630064937&version=1.0&key=6521126bd7b0907aa2671c547db671f0'
        str2 = 'api_key=L2CLMSBYJAPF0HX0PY4VIW0XFPCNT6Y8&biz_content={"api_account_type":"Account","attach":"1235","client_ip":"42.96.158.70","expire_minute":"0","meta_option":"123","notify_url":"http://game.p2pinfo.cn/api_notify.php","out_trade_no":"2018063006493725900","payment_account":"13910978598","payment_provider":"heepay","return_url":"http://game.p2pinfo.cn/api_notify.php","subject":"测试","total_fee":"1"}&charset=utf-8&method=wallet.trade.buy&sign_type=MD5&timestamp=20180630064937&version=1.0&key=6521126bd7b0907aa2671c547db671f0'
        self.maxDiff = None
        self.assertEqual(str1, str2)
        m = hashlib.md5()
        m.update(str1.encode('utf-8'))
        print("signature str 1 is {0}".format(m.hexdigest()))
        m = hashlib.md5()
        m.update(str2.encode('utf-8'))
        print("signature str 2 is {0}".format(m.hexdigest()))
        self.assertTrue(
            request_obj.is_valid('6521126bd7b0907aa2671c547db671f0'))
        """
Exemple #6
0
def handle_pend_api_trans(api_trans):
    tradex = TradeExchangeManager()
    logger.info("handle_pend_api_trans: {0}".format(
        api_trans.original_request))
    request_obj = TradeAPIRequest.parseFromJson(
        json.loads(api_trans.original_request))
    tradex.post_sell_order(request_obj, api_trans.api_user, api_trans)
Exemple #7
0
def cancel_order(request):
    try:
        logger.debug('receive request from: {0}'.format(request.get_host()))
        logger.info('receive request {0}'.format(request.body.decode('utf-8')))
        try:
            request_json = json.loads(request.body.decode('utf-8'))
        except:
            raise ValueError(ERR_INVALID_JSON_INPUT)

        request_obj = TradeAPIRequest.parseFromJson(request_json)
        api_user = APIUserManager.get_api_user_by_apikey(request_obj.api_key)
        validate_request(request_obj, api_user, 'wallet.trade.cancel')
        tradeex = TradeExchangeManager()
        api_trans = tradeex.find_transaction(request_obj.trx_bill_no)
        sitesettings = context_processor.settings(request)['settings']
        appId = sitesettings.heepay_app_id
        appKey = sitesettings.heepay_app_key

        # if trade status is alreadu in failed state, just return the status
        if api_trans.trade_status in [
                'ExpiredInvalid', 'DevClose', 'UserAbandon', 'PaidSuccess',
                'PaidSuccess'
        ]:
            return JsonResponse(
                create_cancel_response(api_trans, api_user).to_json())

        if api_trans.payment_status in ['Unknow', 'NotStart', 'PaySuccess']:
            if api_trans.payment_provider != 'heepay':
                logger.error(
                    'query_order_status(): found unsupported payment provider {0}'
                    .format(api_trans.payment_provider))
                raise ValueError('PAYMENT_PROVIDER_NOT_SUPPORTED')
            logger.info(
                'api trans id {0}, reference_order {1}: payment_status: {2}. Query heepay for status...'
                .format(api_trans.transactionId,
                        api_trans.reference_order.order_id,
                        api_trans.payment_status))
            heepay = HeePayManager()
            json_response = heepay.get_payment_status(
                api_trans.reference_order.order_id,
                api_trans.reference_bill_no, appId, appKey)
            ordermanager.update_order_with_heepay_notification(
                json_response, 'admin')
            api_trans.refresh_from_db()
            if api_trans.payment_status in ['Unknow', 'NotStart']:
                APIUserTransactionManager.abandon_trans(api_trans)
                api_trans.refresh_from_db()
        return JsonResponse(
            create_query_status_response(api_trans, api_user).to_json())
    #TODO: should handle different error here.
    # what if network issue, what if the return is 30x, 40x, 50x
    except:
        error_msg = 'query_order_status()遇到错误: {0}'.format(sys.exc_info()[0])
        logger.exception(error_msg)
        resp = create_error_trade_response(request_obj, api_user, '系统错误',
                                           '系统错误', '')
        return JsonResponse(resp.to_json())
Exemple #8
0
    def test_user_api_call(self):
        pass
        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            'L2CLMSBYJAPF0HX0PY4VIW0XFPCNT6Y8',
            '6521126bd7b0907aa2671c547db671f0',
            '201806251012458960',  # out_trade_no
            total_fee=1,  # total fee
            payment_provider='heepay',
            payment_account='13910978598',
            client_ip='42.96.158.70',  #client ip
            timestamp=20180625101245,
            attach='1235',
            subject='测试',
            notify_url='http://game.p2pinfo.cn/api_notify.php',
            return_url='http://game.p2pinfo.cn/api_notify.php')

        c = APIClient('http://52.43.117.129/api/v1/applypurchase/')
        request_str = request.getPayload()
        resp_json = c.send_json_request(json.loads(request_str))
        print('reply is {0}'.format(json.dumps(resp_json, ensure_ascii=False)))
    def test_redeem_no_payment_account(self):
        request = TradeAPIRequest(
            API_METHOD_REDEEM,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            62000,  # total fee
            10,  # expire_minute
            'heepay',
            '12345',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='人民币提现测试-没有付款账号',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()

        # remove payment account from the request to see whether
        # server side return right error
        request_json = json.loads(request.getPayload())
        biz_content_json = json.loads(request_json['biz_content'])
        del biz_content_json['payment_account']
        request_json['biz_content'] = json.dumps(biz_content_json,
                                                 ensure_ascii=False)
        request_str = json.dumps(request_json, ensure_ascii=False)

        print('send request {0}'.format(request_str))
        response = c.post('/api/v1/applyredeem/',
                          request_str,
                          content_type='application/json')

        print('response is {0}'.format(
            json.dumps(json.loads(response.content.decode('utf-8')),
                       ensure_ascii=False)))

        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(resp_json['return_code'], 'FAIL')
        self.assertEqual(resp_json['return_msg'], '提现请求缺少payment_account字段')
Exemple #10
0
    def test_signature_failure(self):
        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            total_fee=100,
            expire_minute=10,  # expire_minute
            payment_provider='heepay',
            payment_account='123456',
            client_ip='127.0.0.1',  #client ip
            attach='userid:1',
            subject='签名不符测试',
            notify_url='http://notify_url',
            return_url='http://return_url')
        request_json = json.loads(request.getPayload())
        # disturb the sign

        request_json['sign'] = request_json['sign'][:len(request_json['sign']
                                                         ) - 2]
        request_str = json.dumps(request_json, ensure_ascii=False)
        c = Client()
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')
        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual('FAIL', resp_json['return_code'])
        self.assertEqual('签名不符', resp_json['return_msg'])

        request = TradeAPIRequest(
            API_METHOD_REDEEM,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            total_fee=100,
            expire_minute=10,  # expire_minute
            payment_provider='heepay',
            payment_account='123456',
            client_ip='127.0.0.1',  #client ip
            attach='userid:1',
            subject='签名不符测试',
            notify_url='http://notify_url',
            return_url='http://return_url')
        request_json = json.loads(request.getPayload())
        # disturb the sign
        request_json['sign'] = request_json['sign'][:len(request_json['sign']
                                                         ) - 2]
        request_str = json.dumps(request_json, ensure_ascii=False)
        c = Client()
        response = c.post('/api/v1/applyredeem/',
                          request_str,
                          content_type='application/json')
        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual('FAIL', resp_json['return_code'])
        self.assertEqual('签名不符', resp_json['return_msg'])

        request = TradeAPIRequest(
            API_METHOD_QUERY,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            trx_bill_no='FAKETRANSID',
            timestamp=timegm(dt.datetime.utcnow().utctimetuple()))

        request_json = json.loads(request.getPayload())
        # disturb the sign
        request_json['sign'] = request_json['sign'][:len(request_json['sign']
                                                         ) - 2]
        request_str = json.dumps(request_json, ensure_ascii=False)
        c = Client()
        response = c.post('/api/v1/checkstatus/',
                          request_str,
                          content_type='application/json')
        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual('FAIL', resp_json['return_code'])
        self.assertEqual('签名不符', resp_json['return_msg'])
Exemple #11
0
    def test_heepay_request_failure(self, send_json_request_function):
        create_axfund_sell_order('*****@*****.**', 'user@123', 200, 0.51,
                                 'CNY')
        create_axfund_sell_order('*****@*****.**', 'user@123', 2, 0.5,
                                 'CNY')
        request = TradeAPIRequest(
            API_METHOD_REDEEM,
            TEST_API_USER2_APPKEY,
            TEST_API_USER2_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            10000,  # total fee
            10,  # expire_minute
            'heepay',
            '12345',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='To_be_skipped',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()
        request_str = request.getPayload()
        response = c.post('/api/v1/applyredeem/',
                          request_str,
                          content_type='application/json')

        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            total_fee=10000,
            expire_minute=10,  # expire_minute
            payment_provider='heepay',
            payment_account='123456',
            client_ip='127.0.0.1',  #client ip
            attach='userid:1',
            subject='heepay_return_503',
            notify_url='http://notify_url',
            return_url='http://return_url')
        request_str = request.getPayload()
        c = Client()
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')
        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual('FAIL', resp_json['return_code'])
        self.assertEqual('支付系统回复错误码,请询问供应商', resp_json['return_msg'])

        # immediately try to make another purchase there should be none to
        # sell, as the previous error locked the balance of the good sell order
        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            total_fee=200,
            expire_minute=10,  # expire_minute
            payment_provider='heepay',
            payment_account='123456',
            client_ip='127.0.0.1',  #client ip
            attach='userid:1',
            subject='heepay_throw_exception',
            notify_url='http://notify_url',
            return_url='http://return_url')
        request_str = request.getPayload()
        c = Client()
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')
        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual('FAIL', resp_json['return_code'])
        self.assertEqual('无卖单提供充值', resp_json['return_msg'])

        # create new eligible order to continue test
        create_axfund_sell_order('*****@*****.**', 'user@123', 10, 0.5,
                                 'CNY')
        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            total_fee=200,
            expire_minute=10,  # expire_minute
            payment_provider='heepay',
            payment_account='123456',
            client_ip='127.0.0.1',  #client ip
            attach='userid:1',
            subject='heepay_throw_exception',
            notify_url='http://notify_url',
            return_url='http://return_url')
        request_str = request.getPayload()
        c = Client()
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')
        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual('FAIL', resp_json['return_code'])
        self.assertEqual('无法连接支付系统,请询问供应商', resp_json['return_msg'])
    def test_redeem_with_notify_of_bad_account_with_failure_response(
            self, send_json_request_function, send_buy_apply_request_function):
        resp = create_axfund_sell_order('*****@*****.**', 'user@123',
                                        2, 0.5, 'CNY')
        api_seller = APIUserAccount.objects.get(apiKey=TEST_API_USER2_APPKEY)
        AXFWallet = Wallet.objects.get(cryptocurrency__currency_code='AXFund')
        CNYWallet = Wallet.objects.get(cryptocurrency__currency_code='CNY')
        seller_axf_wallet = UserWallet.objects.get(
            user__username=api_seller.user.username, wallet__id=AXFWallet.id)
        seller_cny_wallet = UserWallet.objects.get(
            user__username=api_seller.user.username, wallet__id=CNYWallet.id)

        axf_wallet_balance_begin = seller_axf_wallet.balance
        axf_wallet_locked_balance_begin = seller_axf_wallet.locked_balance
        axf_wallet_available_balance_begin = seller_axf_wallet.available_balance

        cny_wallet_balance_begin = seller_cny_wallet.balance
        cny_wallet_locked_balance_begin = seller_cny_wallet.locked_balance
        cny_wallet_available_balance_begin = seller_cny_wallet.available_balance

        request = TradeAPIRequest(
            API_METHOD_REDEEM,
            TEST_API_USER2_APPKEY,
            TEST_API_USER2_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            10000,  # total fee
            10,  # expire_minute
            'heepay',
            '12345',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='人民币提现测试-无效付款账号',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()
        request_json = json.loads(request.getPayload())
        request_str = json.dumps(request_json, ensure_ascii=False)
        response = c.post('/api/v1/applyredeem/',
                          request_str,
                          content_type='application/json')

        try:
            redeem_order = Order.objects.get(order_type='SELL',
                                             order_source='API')
        except:
            self.fail('Could not get the only redeem sell order {0}'.format(
                sys.exc_info[0]))

        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            10000,  # total fee
            10,  # expire_minute
            'heepay',
            '23456',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='购买无效付款账号的提现订单',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()
        request_json = json.loads(request.getPayload())
        request_str = json.dumps(request_json, ensure_ascii=False)
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')

        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content)
        self.assertEqual('FAIL', resp_json['return_code'])
        self.assertEqual('无卖单提供充值', resp_json['return_msg'])
        send_json_request_function.assert_called_once()
        send_buy_apply_request_function.assert_called_once()
        try:
            purchase_order = Order.objects.get(order_type='BUY',
                                               order_source='API')
        except:
            self.fail('Could not get the only purchase sell order {0}'.format(
                sys.exc_info[0]))

        redeem_order.refresh_from_db()
        self.assertEqual(TRADE_STATUS_BADRECEIVINGACCOUNT, redeem_order.status)
        self.assertEqual(TRADE_STATUS_BADRECEIVINGACCOUNT,
                         purchase_order.status)

        purchase_api_trans = APIUserTransactionManager.get_trans_by_reference_order(
            purchase_order.order_id)
        self.assertTrue(purchase_api_trans,
                        'There should be api transaction for purchase order')
        self.assertEqual(TRADE_STATUS_BADRECEIVINGACCOUNT,
                         purchase_api_trans.trade_status)
        self.assertEqual(TRADE_STATUS_BADRECEIVINGACCOUNT,
                         purchase_api_trans.payment_status)

        redeem_api_trans = APIUserTransactionManager.get_trans_by_reference_order(
            redeem_order.order_id)
        self.assertTrue(redeem_api_trans,
                        'There should be api transaction for redeem order')
        self.assertEqual(TRADE_STATUS_BADRECEIVINGACCOUNT,
                         redeem_api_trans.trade_status)
        self.assertEqual(TRADE_STATUS_BADRECEIVINGACCOUNT,
                         redeem_api_trans.payment_status)

        # after both sell and purchase trans flagged as bad account, axf wallet of seller should
        # not change
        seller_axf_wallet.refresh_from_db()
        axf_wallet_balance_cancel = seller_axf_wallet.balance
        axf_wallet_locked_balance_cancel = seller_axf_wallet.locked_balance
        axf_wallet_available_balance_cancel = seller_axf_wallet.available_balance
        self.assertEqual(axf_wallet_balance_begin, axf_wallet_balance_cancel)
        self.assertEqual(axf_wallet_locked_balance_begin,
                         axf_wallet_locked_balance_cancel)
        self.assertEqual(axf_wallet_available_balance_begin,
                         axf_wallet_available_balance_cancel)

        # after both sell and purchase trans flagged as bad account, cny wallet of seller should
        # not change
        seller_cny_wallet.refresh_from_db()
        cny_wallet_balance_cancel = seller_cny_wallet.balance
        cny_wallet_locked_balance_cancel = seller_cny_wallet.locked_balance
        cny_wallet_available_balance_cancel = seller_cny_wallet.available_balance
        self.assertEqual(cny_wallet_balance_begin, cny_wallet_balance_cancel)
        self.assertEqual(cny_wallet_locked_balance_begin,
                         cny_wallet_locked_balance_cancel)
        self.assertEqual(cny_wallet_available_balance_begin,
                         cny_wallet_available_balance_cancel)
    def test_purchase_skip_sell_order_with_bad_account(
            self, send_json_request_function, send_buy_apply_request_function):
        # this one will be skipped
        create_axfund_sell_order('*****@*****.**', 'user@123', 2, 0.5,
                                 'CNY')
        # this one will be picked after the bad redeem sell order is skipped
        create_axfund_sell_order('*****@*****.**', 'user@123', 200, 0.51,
                                 'CNY')

        api_seller = APIUserAccount.objects.get(apiKey=TEST_API_USER2_APPKEY)
        AXFWallet = Wallet.objects.get(cryptocurrency__currency_code='AXFund')
        CNYWallet = Wallet.objects.get(cryptocurrency__currency_code='CNY')
        seller_axf_wallet = UserWallet.objects.get(
            user__username=api_seller.user.username, wallet__id=AXFWallet.id)
        seller_cny_wallet = UserWallet.objects.get(
            user__username=api_seller.user.username, wallet__id=CNYWallet.id)

        axf_wallet_balance_begin = seller_axf_wallet.balance
        axf_wallet_locked_balance_begin = seller_axf_wallet.locked_balance
        axf_wallet_available_balance_begin = seller_axf_wallet.available_balance

        cny_wallet_balance_begin = seller_cny_wallet.balance
        cny_wallet_locked_balance_begin = seller_cny_wallet.locked_balance
        cny_wallet_available_balance_begin = seller_cny_wallet.available_balance

        request = TradeAPIRequest(
            API_METHOD_REDEEM,
            TEST_API_USER2_APPKEY,
            TEST_API_USER2_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            10000,  # total fee
            10,  # expire_minute
            'heepay',
            '12345',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='人民币提现测试-无效付款账号',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()
        request_json = json.loads(request.getPayload())
        request_str = json.dumps(request_json, ensure_ascii=False)
        response = c.post('/api/v1/applyredeem/',
                          request_str,
                          content_type='application/json')

        try:
            redeem_order = Order.objects.get(order_type='SELL',
                                             order_source='API')
        except:
            self.fail('Could not get the only redeem sell order {0}'.format(
                sys.exc_info[0]))

        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            10000,  # total fee
            10,  # expire_minute
            'heepay',
            '23456',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='跳过无效付款账号的提现订单',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()
        request_json = json.loads(request.getPayload())
        request_str = json.dumps(request_json, ensure_ascii=False)
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')

        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content)
        resp_json = json.loads(response.content.decode('utf-8'))

        self.assertEqual('SUCCESS', resp_json['return_code'])
        self.assertEqual('执行完成', resp_json['return_msg'])
        self.assertEqual('SUCCESS', resp_json['result_code'])
        self.assertEqual('下单申请成功', resp_json['result_msg'])
        self.assertEqual('UNKNOWN', resp_json['trade_status'])

        # after both sell and purchase trans flagged as bad account, axf wallet of seller should
        # not change
        seller_axf_wallet.refresh_from_db()
        axf_wallet_balance_cancel = seller_axf_wallet.balance
        axf_wallet_locked_balance_cancel = seller_axf_wallet.locked_balance
        axf_wallet_available_balance_cancel = seller_axf_wallet.available_balance
        self.assertEqual(axf_wallet_balance_begin, axf_wallet_balance_cancel)
        self.assertEqual(axf_wallet_locked_balance_begin,
                         axf_wallet_locked_balance_cancel)
        self.assertEqual(axf_wallet_available_balance_begin,
                         axf_wallet_available_balance_cancel)

        # after both sell and purchase trans flagged as bad account, cny wallet of seller should
        # not change
        seller_cny_wallet.refresh_from_db()
        cny_wallet_balance_cancel = seller_cny_wallet.balance
        cny_wallet_locked_balance_cancel = seller_cny_wallet.locked_balance
        cny_wallet_available_balance_cancel = seller_cny_wallet.available_balance
        self.assertEqual(cny_wallet_balance_begin, cny_wallet_balance_cancel)
        self.assertEqual(cny_wallet_locked_balance_begin,
                         cny_wallet_locked_balance_cancel)
        self.assertEqual(cny_wallet_available_balance_begin,
                         cny_wallet_available_balance_cancel)
    def test_bad_payment_provider(self):
        # first create a normal redeem request
        request = TradeAPIRequest(
            API_METHOD_REDEEM,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            62000,  # total fee
            10,  # expire_minute
            'heepay',
            '12345',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='人民币提现测试-没有付款账号',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()

        # change payment provider from the request to see whether
        # server side return right error
        request_json = json.loads(request.getPayload())
        biz_content_json = json.loads(request_json['biz_content'])
        biz_content_json['payment_provider'] = 'unsupported'
        request_json['biz_content'] = json.dumps(biz_content_json,
                                                 ensure_ascii=False)
        request_str = json.dumps(request_json, ensure_ascii=False)

        print('send request {0}'.format(request_str))
        response = c.post('/api/v1/applyredeem/',
                          request_str,
                          content_type='application/json')

        print('response is {0}'.format(
            json.dumps(json.loads(response.content.decode('utf-8')),
                       ensure_ascii=False)))

        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(resp_json['return_code'], 'FAIL')
        self.assertEqual(resp_json['return_msg'], '缺失支付方式或提供的支付方式系统不支持')

        # second create a normal purchase request
        request = TradeAPIRequest(
            API_METHOD_PURCHASE,
            TEST_API_USER1_APPKEY,
            TEST_API_USER1_SECRET,
            'order_no_order',  # order id
            None,  # trx_id
            62000,  # total fee
            10,  # expire_minute
            'heepay',
            '12345',
            '127.0.0.1',  #client ip
            attach='userid:1',
            subject='人民币提现测试-没有付款账号',
            notify_url='http://testurl',
            return_url='http://retururl')
        c = Client()

        # change payment provider from the request to see whether
        # server side return right error
        request_json = json.loads(request.getPayload())
        biz_content_json = json.loads(request_json['biz_content'])
        biz_content_json['payment_provider'] = 'unsupported'
        request_json['biz_content'] = json.dumps(biz_content_json,
                                                 ensure_ascii=False)
        request_str = json.dumps(request_json, ensure_ascii=False)

        print('send request {0}'.format(request_str))
        response = c.post('/api/v1/applypurchase/',
                          request_str,
                          content_type='application/json')

        print('response is {0}'.format(
            json.dumps(json.loads(response.content.decode('utf-8')),
                       ensure_ascii=False)))

        self.assertEqual(200, response.status_code)
        resp_json = json.loads(response.content.decode('utf-8'))
        self.assertEqual(resp_json['return_code'], 'FAIL')
        self.assertEqual(resp_json['return_msg'], '缺失支付方式或提供的支付方式系统不支持')