From 11762e3c4088de630f33019a829b7a9edf60846f Mon Sep 17 00:00:00 2001 From: Ivan Shamatov Date: Sat, 20 Nov 2021 14:57:38 +0300 Subject: [PATCH] Paouts and Deals endpoints support (#26) --- lib/yookassa/deals.rb | 24 ++++++++ lib/yookassa/entity/card.rb | 4 +- lib/yookassa/entity/collection.rb | 5 +- lib/yookassa/entity/deal.rb | 56 +++++++++++++++++ lib/yookassa/entity/payment.rb | 16 ++--- lib/yookassa/entity/payout.rb | 71 ++++++++++++++++++++++ lib/yookassa/entity/payout_destinations.rb | 26 ++++++++ lib/yookassa/payouts.rb | 19 ++++++ 8 files changed, 209 insertions(+), 12 deletions(-) create mode 100644 lib/yookassa/deals.rb create mode 100644 lib/yookassa/entity/deal.rb create mode 100644 lib/yookassa/entity/payout.rb create mode 100644 lib/yookassa/entity/payout_destinations.rb create mode 100644 lib/yookassa/payouts.rb diff --git a/lib/yookassa/deals.rb b/lib/yookassa/deals.rb new file mode 100644 index 0000000..e296da2 --- /dev/null +++ b/lib/yookassa/deals.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require_relative "./client" +require_relative "./entity/deal" +require_relative "./entity/collection" + +module Yookassa + class Deals < Client + def find(deal_id:) + data = get("deals/#{deal_id}") + Entity::Deal.new(**data) + end + + def create(payload:, idempotency_key: SecureRandom.hex(10)) + data = post("deals", payload: payload, idempotency_key: idempotency_key) + Entity::Deal.new(**data.merge(idempotency_key: idempotency_key)) + end + + def list + data = get("deals") + Entity::DealCollection.new(**data) + end + end +end diff --git a/lib/yookassa/entity/card.rb b/lib/yookassa/entity/card.rb index 27ec0f9..30c2561 100644 --- a/lib/yookassa/entity/card.rb +++ b/lib/yookassa/entity/card.rb @@ -17,11 +17,11 @@ module Yookassa # expiry_month [string, required] # Expiration date, month, MM. - attribute :expiry_month, Types::Coercible::Integer + attribute? :expiry_month, Types::Coercible::Integer # expiry_year [string, required] # Expiration date, year, YYYY. - attribute :expiry_year, Types::Coercible::Integer + attribute? :expiry_year, Types::Coercible::Integer # card_type [string, required] # Type of bank card. Possible values: MasterCard (for Mastercard and Maestro cards), Visa (for Visa and Visa Electron cards), diff --git a/lib/yookassa/entity/collection.rb b/lib/yookassa/entity/collection.rb index a5d0c9a..a3e20f8 100644 --- a/lib/yookassa/entity/collection.rb +++ b/lib/yookassa/entity/collection.rb @@ -5,6 +5,7 @@ require_relative "./payment" require_relative "./receipt" require_relative "./refund" require_relative "./webhook" +require_relative "./deal" module Yookassa module Entity @@ -25,8 +26,8 @@ module Yookassa attribute :items, Types::Array.of(Receipt) end - class WebhookCollection < Collection - attribute :items, Types::Array.of(Webhook) + class DealsCollection < Collection + attribute :items, Types::Array.of(Deal) end end end diff --git a/lib/yookassa/entity/deal.rb b/lib/yookassa/entity/deal.rb new file mode 100644 index 0000000..a68adb0 --- /dev/null +++ b/lib/yookassa/entity/deal.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require_relative "./types" +require_relative "./amount" + +module Yookassa + module Entity + class Deal < Dry::Struct + attribute? :idempotency_key, Types::String + # id [string, required] + # Deals's ID in YooMoney + attribute :id, Types::String + + # Момент перечисления вам вознаграждения платформы. Возможные значения: + # payment_succeeded — после успешной оплаты; + # deal_closed — при закрытии сделки после успешной выплаты. + attribute :fee_moment, Types::String.enum("payment_succeeded", "deal_closed") + + # Описание сделки (не более 128 символов). Используется для фильтрации при получении списка сделок. + attribute? :description, Types::String.constrained(max_size: 128) + + # Баланс сделки. + attribute :balance, Amount + + # Сумма вознаграждения продавца. + attribute :payout_balance, Amount + + # Статус сделки. Возможные значения: + # opened — сделка открыта; можно выполнять платежи, возвраты и выплаты в составе сделки; + # closed — сделка закрыта — вознаграждение перечислено продавцу и платформе или оплата возвращена покупателю; + # нельзя выполнять платежи, возвраты и выплаты в составе сделки. + attribute :status, Types::String.enum("opened", "closed") + + # Время создания сделки. Указывается по UTC и передается в формате ISO 8601. Пример: 2017-11-03T11:52:31.827Z + attribute :created_at, Types::JSON::DateTime + + # Время автоматического закрытия сделки. Если в указанное время сделка всё еще в статусе opened, + # ЮKassa вернет деньги покупателю и закроет сделку. По умолчанию время жизни сделки составляет 90 дней. + # Время указывается по UTC и передается в формате ISO 8601. Пример: 2017-11-03T11:52:31.827Z + attribute :expires_at, Types::JSON::DateTime + + # metadata [object, optional] + # Any additional data you might require for processing payments (for example, order number), specified as a “key-value” pair + # and returned in response from YooMoney. + # Limitations: + # - no more than 16 keys, + # - no more than 32 characters in the key’s title, + # - no more than 512 characters in the key’s value, + # - data type is a string in the UTF-8 format. + attribute? :metadata, Types::Hash + + # Признак тестовой операции. + attribute :test, Types::Bool + end + end +end diff --git a/lib/yookassa/entity/payment.rb b/lib/yookassa/entity/payment.rb index 486f025..fe60828 100644 --- a/lib/yookassa/entity/payment.rb +++ b/lib/yookassa/entity/payment.rb @@ -25,13 +25,13 @@ module Yookassa # amount [object, required] # Payment amount. Sometimes YooMoney's partners charge additional commission from the users that is not included in this amount. - attribute :amount, Entity::Amount + attribute :amount, Amount # income_amount [object, optional] # Amount of payment to be received by the store: the amount value minus the YooMoney commission. # If you're a partner using an OAuth token for request authentication, make a request to the store for a right # to get information about commissions on payments. - attribute? :income_amount, Entity::Amount + attribute? :income_amount, Amount # description [string, optional] # Description of the transaction (maximum 128 characters) displayed in your YooMoney Merchant Profile, @@ -40,11 +40,11 @@ module Yookassa # recipient [object, required] # Payment recipient. - attribute :recipient, Entity::Recipient + attribute :recipient, Recipient # payment_method [object, optional] # Payment method used for this payment. - attribute? :payment_method, Entity::PaymentMethods + attribute? :payment_method, PaymentMethods # captured_at [datetime, optional] # Time of payment capture, based on UTC and specified in the ISO 8601 format. "2018-07-18T10:51:18.139Z" @@ -62,7 +62,7 @@ module Yookassa # confirmation [object, optional] # Selected payment confirmation scenario. For payments requiring confirmation from the user. # More about confirmation scenarios https://yookassa.ru/en/developers/api#:~:text=confirmation,from%20the%20user.%20More%20about%20confirmation%20scenarios%C2%A0 - attribute? :confirmation, Entity::Confirmations + attribute? :confirmation, Confirmations # test [boolean, required] # The attribute of a test transaction. @@ -70,7 +70,7 @@ module Yookassa # refunded_amount [object, optional] # The amount refunded to the user. Specified if the payment has successful refunds. - attribute? :refunded_amount, Entity::Amount + attribute? :refunded_amount, Amount # paid [boolean, required] # The attribute of a paid order. @@ -97,11 +97,11 @@ module Yookassa # cancellation_details [object, optional] # Commentary to the canceled status: who and why canceled the payment. # More about canceled payments https://yookassa.ru/en/developers/api#:~:text=cancellation_details,about%20canceled%20payments%C2%A0 - attribute? :cancellation_details, Entity::CancellationDetails + attribute? :cancellation_details, CancellationDetails # authorization_details [object, optional] # Payment authorization details. - attribute? :authorization_details, Entity::AuthorizationDetails + attribute? :authorization_details, AuthorizationDetails # transfers [array, optional] # Information about money distribution: the amounts of transfers and the stores to be transferred to. diff --git a/lib/yookassa/entity/payout.rb b/lib/yookassa/entity/payout.rb new file mode 100644 index 0000000..f2e6ed1 --- /dev/null +++ b/lib/yookassa/entity/payout.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +require_relative "./types" +require_relative "./amount" +require_relative "./payout_destinations" + +module Yookassa + module Entity + class Payout < Dry::Struct + attribute? :idempotency_key, Types::String + # id [string, required] + # Deals's ID in YooMoney + attribute :id, Types::String + + # Сумма выплаты + attribute :amount, Amount + + # Статус выплаты. Возможные значения: + # pending — только для выплат на банковские карты: выплата создана и ожидает подтверждения от эмитента, + # что деньги можно перевести на указанную банковскую карту; + # succeeded — выплата успешно завершена, оплата переведена на платежное средство продавца + # (финальный и неизменяемый статус); + # canceled — выплата отменена, инициатор и причина отмены указаны в объекте cancellation_details + # (финальный и неизменяемый статус). + attribute :status, Types::String.enum("pending", "succeeded", "canceled") + + attribute :payout_destination, PayoutDestinations + + # Описание сделки (не более 128 символов). Используется для фильтрации при получении списка сделок. + attribute? :description, Types::String.constrained(max_size: 128) + + # Время создания сделки. Указывается по UTC и передается в формате ISO 8601. Пример: 2017-11-03T11:52:31.827Z + attribute :created_at, Types::JSON::DateTime + + # Сделка, в рамках которой нужно провести выплату. Присутствует, если вы проводите Безопасную сделку + attribute? :deal do + # Идентификатор сделки. + attribute :id, Types::String + end + + # Комментарий к статусу canceled: кто отменил выплату и по какой причине. + attribute? :cancellation_details do + # Участник процесса выплаты, который принял решение об отмене транзакции. Может принимать значения + # yoo_money, payment_network и merchant https://yookassa.ru/developers/solutions-for-platforms/safe-deal/integration/payouts#declined-payouts-cancellation-details-party + attribute? :party, Types::String.enum("yoo_money", "payment_network", "merchant") + + # Причина отмены выплаты + # fraud_suspected Выплата заблокирована из-за подозрения в мошенничестве + # general_decline Причина не детализирована. Пользователю следует обратиться к инициатору отмены выплаты за уточнением подробностей + # one_time_limit_exceeded Превышен лимит на разовое зачисление. Подробнее о лимитах + # periodic_limit_exceeded Превышен лимит выплат за период времени (сутки, месяц). Подробнее о лимитах + # rejected_by_payee Эмитент отклонил выплату по неизвестным причинам + attribute :reason, + Types::String.enum("fraud_suspected", "general_decline", "one_time_limit_exceeded", "periodic_limit_exceeded", "rejected_by_payee") + end + + # metadata [object, optional] + # Any additional data you might require for processing payments (for example, order number), specified as a “key-value” pair + # and returned in response from YooMoney. + # Limitations: + # - no more than 16 keys, + # - no more than 32 characters in the key’s title, + # - no more than 512 characters in the key’s value, + # - data type is a string in the UTF-8 format. + attribute? :metadata, Types::Hash + + # Признак тестовой операции. + attribute :test, Types::Bool + end + end +end diff --git a/lib/yookassa/entity/payout_destinations.rb b/lib/yookassa/entity/payout_destinations.rb new file mode 100644 index 0000000..ea9a829 --- /dev/null +++ b/lib/yookassa/entity/payout_destinations.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require_relative "./types" +require_relative "./card" + +module Yookassa + module Entity + module PayoutDestination + class BankCard < Base + attribute :type, Types.Value("bank_card") + + attribute? :card, Card + end + + class YooMoney < Base + attribute :type, Types.Value("yoo_money") + + # account_number [string, optional] + # The number of the YooMoney wallet used for making the payment. + attribute? :account_number, Types::String.constrained(min_size: 11, max_size: 33) + end + end + + PayoutDestinations = PayoutDestination::BankCard | PayoutDestination::YooMoney + end +end diff --git a/lib/yookassa/payouts.rb b/lib/yookassa/payouts.rb new file mode 100644 index 0000000..8e5b3ed --- /dev/null +++ b/lib/yookassa/payouts.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +require_relative "./client" +require_relative "./entity/payout" +require_relative "./entity/collection" + +module Yookassa + class Payouts < Client + def find(payout_id:) + data = get("payouts/#{payout_id}") + Entity::Payout.new(**data) + end + + def create(payload:, idempotency_key: SecureRandom.hex(10)) + data = post("payouts", payload: payload, idempotency_key: idempotency_key) + Entity::Payout.new(**data.merge(idempotency_key: idempotency_key)) + end + end +end