def get_ym_params(self, amount, pattern, order_id, success_uri, fail_uri, type=PAYMENT_BY_CARD): """Запрос параметров от ym""" request_options = { "pattern_id": pattern, "sum": amount, "customerNumber": order_id, } if type == PaymentCard.PAYMENT_BY_CARD: ym = ExternalPayment(YandexMoneyConfig.INSTANCE_ID) payment = ym.request(request_options) elif type == PaymentCard.PAYMENT_BY_YM: return False else: return False if payment['status'] == "success": request_id = payment['request_id'] else: return False process_options = { "request_id": request_id, 'ext_auth_success_uri': success_uri, 'ext_auth_fail_uri': fail_uri } result = ym.process(process_options) return dict( url=result['acs_uri'], params=result['acs_params'] )
def makeRequest(self): instance_id = ExternalPayment.get_instance_id(CLIENT_ID)['instance_id'] api = ExternalPayment(instance_id) options = { "instance_id": instance_id, "pattern_id": "p2p", "to": "410011161616877", "amount_due": "0.02", "comment": "test payment comment from yandex-money-python", "message": "test payment message from yandex-money-python", "label": "testPayment", "test_payment": True, "test_result": "success" } return api.request(options), api
def request_external_payment(instance_id, amount, wallet): logger.debug('Requesting exteranl payment') external_payment = ExternalPayment(instance_id) payment_options = { 'pattern_id': 'p2p', 'instance_id': instance_id, 'to': wallet, 'amount': amount, 'message': 'Оплата бота' } request_id = None response = external_payment.request(payment_options) logger.debug('Reposnse from external_payment.request : {0}'.format(response)) if response['status'] == "success": request_id = response['request_id'] else: logger.error('Failed to get request_id. Reason: {0}'.format(response)) return request_id
def get_ym_params(self, amount, pattern, order_id, success_uri, fail_uri, type=PAYMENT_BY_CARD): """Запрос параметров от ym""" request_options = { "pattern_id": pattern, "sum": amount, "customerNumber": order_id, } if type == PaymentCard.PAYMENT_BY_CARD: ym = ExternalPayment(YandexMoneyConfig.INSTANCE_ID) payment = ym.request(request_options) elif type == PaymentCard.PAYMENT_BY_YM: return False else: return False if payment['status'] == "success": request_id = payment['request_id'] else: return False process_options = { "request_id": request_id, 'ext_auth_success_uri': success_uri, 'ext_auth_fail_uri': fail_uri } result = ym.process(process_options) return dict(url=result['acs_uri'], params=result['acs_params'])
class TestExternalPayment(unittest.TestCase): client_id = '1' @classmethod def request_callback(cls, request): payload = dict(parse_qsl(request.body)) success = payload['client_id'] == cls.client_id resp_body = {'status': 'success' if success else 'refused'} if success: resp_body['instance_id'] = '123' else: resp_body['error'] = 'illegal_param_client_id' return 200, {}, json.dumps(resp_body) def setUp(self): self.api = ExternalPayment(self.client_id) responses.add_callback( responses.POST, re.compile('https?://.*/api/instance-id'), callback=self.request_callback, content_type='application/json', ) @responses.activate def test_invalid_client_id(self): api = ExternalPayment(client_id=self.client_id+'some_data') with self.assertRaises(exceptions.YandexPaymentError) as context: api.instance_id self.assertEqual(exceptions._errors['illegal_param_client_id'].encode('utf-8'), str(context.exception)) self.assertEqual(len(responses.calls), 1) @responses.activate def test_instance_id(self): self.assertEqual(self.api.instance_id, '123') self.assertEqual(len(responses.calls), 1) api2 = ExternalPayment(client_id=self.client_id) self.assertEqual(api2.instance_id, '123') self.assertEqual(len(responses.calls), 1) @responses.activate def test_request(self): def callback(request): payload = dict(parse_qsl(request.body)) success = all(i in payload for i in ['amount', 'to', 'message', 'instance_id']) if success: return 200, {}, json.dumps({'status': 'success', 'request_id': 1, 'contract_amount': payload['amount']}) return 200, {}, json.dumps({'status': 'refused', 'error': 'illegal_params'}) responses.add_callback( responses.POST, re.compile('https?://.*/api/request-external-payment'), callback=callback, content_type='application/json', ) resp = self.api.request({'amount': 100, 'to': 'test', 'message': 'message'}) self.assertEqual(resp.request_id, 1) self.assertEqual(int(resp.contract_amount), 100) with self.assertRaises(exceptions.YandexPaymentError) as context: resp = self.api.request({'message': 'message'}) self.assertEqual(exceptions._errors['illegal_params'].encode('utf-8'), str(context.exception)) self.assertEqual(len(responses.calls), 3) @responses.activate def test_process(self): def callback(request): payload = dict(parse_qsl(request.body)) success = True if payload['request_id'] != 1: success = False success = all(i in payload for i in ['ext_auth_success_uri', 'ext_auth_fail_uri', 'request_token', 'instance_id']) if success: return 200, {}, json.dumps({'status': 'success', 'invoice_id': '0'}) return 200, {}, json.dumps({'status': 'refused', 'error': 'illegal_params'}) responses.add_callback( responses.POST, re.compile('https?://.*/api/process-external-payment'), callback=callback, content_type='application/json', ) resp = self.api.process({'request_id': 1, 'ext_auth_success_uri': 'test', 'ext_auth_fail_uri': 'test_fail', 'request_token': 'request_token', 'instance_id': '123', }) self.assertEqual(resp.status, 'success') self.assertEqual(resp.invoice_id, '0') self.assertEqual(len(responses.calls), 2) def tearDown(self): self.api.zero_cache()
from yandex_money.api import Wallet, ExternalPayment client_id = '6D3FD82502F95CC490D4297F871AB2B934597432FE48B681025011F50C079' response = ExternalPayment.get_instance_id(client_id) if reponse.status == "success": instance_id = response.instance_id; else: # throw exception with reponse->error message # make instance external_payment = ExternalPayment(instance_id); payment_options = { # pattern_id, etc.. } response = external_payment.request(payment_options) if response.status == "success": request_id = response.request_id else: # throw exception with response->message process_options = { "request_id": request_id # other params.. } result = external_payment.process(process_options) # process result according to docs
def background_payment(report_id): """Проводим фоновый платеж""" log = logging.getLogger('payment') report = Report.query.get(report_id) if not report: message = 'Payment: Not found report with id %s' % report_id log.error(message) return message if report.is_payment_busy(): return False wallet = PaymentWallet.get_by_payment_id(report.payment_id) if not wallet: message = 'Payment: Not found wallet with pid %s' % report.payment_id log.error(message) return message PaymentHistory.remove_braked(report.id) history = PaymentHistory.query.filter_by(report_id=report.id).first() if history: return False history = PaymentHistory().from_report(report, wallet) if not history: message = 'Payment: Fail in history add, report_id=%s' % report_id log.error(message) return message card = PaymentCard.get_payment_card(wallet.id) if not card: PaymentTask.set_fail(report_id, wallet) history.delete() message = 'Payment: Not found card, for wallet_id=%s' % wallet.id log.error(message) return False term = Term.query.get(report.term_id) if not term: log.error('Payment: Not found term %s' % report.term_id) firm = Firm.query.get(report.term_firm_id) if not firm: log.error( 'Payment: Not found firm, with term %s' % report.term_id) request_options = { "pattern_id": firm.pattern_id, "sum": float(report.amount) / int(Term.DEFAULT_FACTOR), "customerNumber": history.id, } try: if card.system == PaymentCard.SYSTEM_MPS: history.system = PaymentHistory.SYSTEM_MPS ym = ExternalPayment(YandexMoneyConfig.INSTANCE_ID) payment = ym.request(request_options) elif card.system == PaymentCard.SYSTEM_YANDEX: history.system = PaymentHistory.SYSTEM_YANDEX ym = Wallet(card.token) payment = ym.request_payment(request_options) else: return False except Exception as e: log.error(e) return False else: if not payment or 'request_id' not in payment: PaymentTask.set_fail(report_id, wallet) message = 'Payment: Fail in request payment, report_id %s, request %s' % ( report_id, payment) log.error(message) history.delete() return message history.request_id = payment['request_id'] history.save() return True