def reload_settings(**kwargs): """ Обновление настроек, если они изменились. """ if kwargs['setting'] == 'YANDEX_KASSA': settings.update(kwargs['value']) Configuration.configure(settings.SHOP_ID, settings.SECRET_KEY)
def refresh_payment(payment): Configuration.configure(settings.YANDEX_CHECKOUT_CLIENT_ID, settings.YANDEX_CHECKOUT_SECRET_KEY) yandex_payment = YandexPayment.find_one(payment.yandex_id) need_to_set_payed = False if payment.status == Payment.PENDING and yandex_payment.status in ( Payment.WAITING_FOR_CAPTURE, Payment.SUCCEEDED): need_to_set_payed = True payment.status = yandex_payment.status if yandex_payment.cancellation_details: payment.cancellation_reason = yandex_payment.cancellation_details.reason payment.save(update_fields=['status', 'cancellation_reason']) if need_to_set_payed: set_order_payed(payment.order) return payment
def __init__(self): self.configuration = Configuration.instantiate() self.shop_id = self.configuration.account_id self.shop_password = self.configuration.secret_key self.auth_token = self.configuration.auth_token self.timeout = self.configuration.timeout self.max_attempts = self.configuration.max_attempts self.user_agent = UserAgent() if self.configuration.agent_framework: self.user_agent.framework = self.configuration.agent_framework if self.configuration.agent_cms: self.user_agent.cms = self.configuration.agent_cms if self.configuration.agent_module: self.user_agent.module = self.configuration.agent_module
def create_payment(order): Configuration.configure(settings.YANDEX_CHECKOUT_CLIENT_ID, settings.YANDEX_CHECKOUT_SECRET_KEY) idempotence_key = str(uuid.uuid4()) yandex_payment = YandexPayment.create( { 'amount': { 'value': str(order.total_cost), 'currency': 'RUB', }, 'description': f'Платеж по заказу {order.id}', 'confirmation': { 'type': 'embedded' } }, idempotence_key) payment = Payment.objects.create( order=order, yandex_id=yandex_payment.id, status=yandex_payment.status, amount=yandex_payment.amount.value, currency=yandex_payment.amount.currency, confirmation_token=yandex_payment.confirmation.confirmation_token) return payment
return value def __setitem__(self, key, value): self.settings[key] = value def __delitem__(self, key): del self.settings[key] def __iter__(self): return iter(self.settings) def __len__(self): return len(self.settings) def __getattr__(self, name): return self.__getitem__(name) settings = YandexKassaSettings(getattr(_settings, 'YANDEX_KASSA', {})) Configuration.configure(settings.SHOP_ID, settings.SECRET_KEY) @receiver(setting_changed) def reload_settings(**kwargs): """ Обновление настроек, если они изменились. """ if kwargs['setting'] == 'YANDEX_KASSA': settings.update(kwargs['value']) Configuration.configure(settings.SHOP_ID, settings.SECRET_KEY)
class ApiClient: endpoint = Configuration.api_endpoint() def __init__(self): self.configuration = Configuration.instantiate() self.shop_id = self.configuration.account_id self.shop_password = self.configuration.secret_key self.auth_token = self.configuration.auth_token self.timeout = self.configuration.timeout self.max_attempts = self.configuration.max_attempts self.user_agent = UserAgent() if self.configuration.agent_framework: self.user_agent.framework = self.configuration.agent_framework if self.configuration.agent_cms: self.user_agent.cms = self.configuration.agent_cms if self.configuration.agent_module: self.user_agent.module = self.configuration.agent_module def request(self, method="", path="", query_params=None, headers=None, body=None): if isinstance(body, RequestObject): body.validate() body = dict(body) request_headers = self.prepare_request_headers(headers) raw_response = self.execute(body, method, path, query_params, request_headers) if raw_response.status_code != 200: self.__handle_error(raw_response) return raw_response.json() def execute(self, body, method, path, query_params, request_headers): session = self.get_session() raw_response = session.request(method, self.endpoint + path, params=query_params, headers=request_headers, json=body) return raw_response def get_session(self): session = requests.Session() retries = Retry(total=self.max_attempts, backoff_factor=self.timeout / 1000, method_whitelist=['POST'], status_forcelist=[202]) session.mount('https://', HTTPAdapter(max_retries=retries)) return session def prepare_request_headers(self, headers): request_headers = {'Content-type': 'application/json'} if self.auth_token is not None: auth_headers = {"Authorization": "Bearer " + self.auth_token} else: auth_headers = { "Authorization": _basic_auth_str(self.shop_id, self.shop_password) } request_headers.update(auth_headers) request_headers.update( {"YM-User-Agent": self.user_agent.get_header_string()}) if isinstance(headers, dict): request_headers.update(headers) return request_headers def __handle_error(self, raw_response): http_code = raw_response.status_code if http_code == BadRequestError.HTTP_CODE: raise BadRequestError(raw_response.json()) elif http_code == ForbiddenError.HTTP_CODE: raise ForbiddenError(raw_response.json()) elif http_code == NotFoundError.HTTP_CODE: raise NotFoundError(raw_response.json()) elif http_code == TooManyRequestsError.HTTP_CODE: raise TooManyRequestsError(raw_response.json()) elif http_code == UnauthorizedError.HTTP_CODE: raise UnauthorizedError(raw_response.json()) elif http_code == ResponseProcessingError.HTTP_CODE: raise ResponseProcessingError(raw_response.json()) else: raise ApiError(raw_response.text)
def __init__(self): Configuration.configure(settings.YANDEX_CHECKOUT_ACCOUNT_ID, settings.YANDEX_CHECKOUT_SECRET_KEY)
import uuid from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 import yandex_checkout from django.urls import reverse import mainapp from mainapp import utils from mainapp.models import Category, Product, Order, OrderItem, Sort from yandex_checkout import Configuration, Payment Configuration.configure('707095', 'test_ZlfSv-xgCIBSKohaHNcifWgXrkaO3CTfEtt7sbj5FWk') def main(request): categories = Category.objects.all() new_products = Product.objects.all().order_by('-date')[:3] top_products = Product.objects.all().order_by('-rating')[:6] sorts = Sort.objects.all() try: order = Order.objects.get(user=request.session.session_key, status=Order.PENDING) items = OrderItem.objects.filter( order=order, order__status=Order.PENDING, ) total = sum([item.item.price * item.quantity for item in items]) except Exception as err:
) from .serializer import ( course_full_serializer, course_list_serializer, course_short_serializer, course_create_serializer, course_update_serializer, course_super_update_serializer, ) from typing import Dict, List from Everland.exceptions import ServerException from Everland.Courses.utils import UserType from yandex_checkout import Configuration, Payment Configuration.configure(632146, 'test_gI1kHce3enAfVcCwkn4FhsW0xEKGsjD5EuMZWGI4a68') async def get_course_authors(course_id): from Everland import rpc_client course = await CourseModel.get(course_id) if course is None: raise ServerException( 1, 'Курс не найден', '' ) serialized_authors = list() for author in await course.authors: body = json.dumps({