lunixi-sdk 1.2.2 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -0
  3. data/README.md +262 -9
  4. data/README.tr.md +266 -7
  5. data/lib/lunixi/bank_connect.rb +340 -0
  6. data/lib/lunixi/bank_connect_filters.rb +114 -0
  7. data/lib/lunixi/bank_connect_values.rb +205 -0
  8. data/lib/lunixi/bank_transfer.rb +106 -0
  9. data/lib/lunixi/card_requests.rb +150 -0
  10. data/lib/lunixi/client.rb +57 -16
  11. data/lib/lunixi/direct_method_payment_request.rb +243 -0
  12. data/lib/lunixi/enabled_installments.rb +28 -0
  13. data/lib/lunixi/errors.rb +69 -3
  14. data/lib/lunixi/fraud.rb +81 -5
  15. data/lib/lunixi/identity.rb +94 -0
  16. data/lib/lunixi/identity_values.rb +28 -0
  17. data/lib/lunixi/insurance.rb +294 -0
  18. data/lib/lunixi/insurance_request.rb +134 -0
  19. data/lib/lunixi/insurance_values.rb +200 -0
  20. data/lib/lunixi/kyc.rb +189 -0
  21. data/lib/lunixi/kyc_values.rb +158 -0
  22. data/lib/lunixi/marketplace.rb +264 -0
  23. data/lib/lunixi/marketplace_values.rb +86 -0
  24. data/lib/lunixi/method_fields.rb +142 -0
  25. data/lib/lunixi/money.rb +7 -4
  26. data/lib/lunixi/payment_link_filters.rb +32 -0
  27. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  28. data/lib/lunixi/payment_link_rules.rb +132 -0
  29. data/lib/lunixi/payment_link_values.rb +134 -0
  30. data/lib/lunixi/payment_links.rb +152 -0
  31. data/lib/lunixi/payment_values.rb +86 -0
  32. data/lib/lunixi/payments.rb +154 -5
  33. data/lib/lunixi/physical_pos.rb +183 -0
  34. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  35. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  36. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  37. data/lib/lunixi/physical_pos_filters.rb +58 -0
  38. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  39. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  40. data/lib/lunixi/physical_pos_management.rb +326 -0
  41. data/lib/lunixi/physical_pos_money.rb +46 -0
  42. data/lib/lunixi/physical_pos_request.rb +126 -0
  43. data/lib/lunixi/physical_pos_responses.rb +102 -0
  44. data/lib/lunixi/physical_pos_results.rb +52 -0
  45. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  46. data/lib/lunixi/physical_pos_value.rb +43 -0
  47. data/lib/lunixi/physical_pos_values.rb +203 -0
  48. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  49. data/lib/lunixi/product_webhooks.rb +106 -0
  50. data/lib/lunixi/promissory_note.rb +155 -0
  51. data/lib/lunixi/reference.rb +41 -0
  52. data/lib/lunixi/route_request.rb +121 -0
  53. data/lib/lunixi/route_response.rb +101 -0
  54. data/lib/lunixi/route_table.rb +128 -0
  55. data/lib/lunixi/route_value.rb +60 -0
  56. data/lib/lunixi/sanction.rb +244 -0
  57. data/lib/lunixi/sanction_values.rb +132 -0
  58. data/lib/lunixi/split_payment.rb +145 -0
  59. data/lib/lunixi/subscription_resources.rb +355 -0
  60. data/lib/lunixi/subscription_values.rb +220 -0
  61. data/lib/lunixi/subscriptions.rb +202 -0
  62. data/lib/lunixi/version.rb +1 -1
  63. data/lib/lunixi/wallet.rb +153 -0
  64. data/lib/lunixi/wallet_resources.rb +402 -0
  65. data/lib/lunixi/wallet_routes.rb +123 -0
  66. data/lib/lunixi/wallet_values.rb +71 -0
  67. data/lib/lunixi/wire_money.rb +67 -0
  68. data/lib/lunixi.rb +57 -0
  69. metadata +58 -1
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Para Transferi (BANK_TRANSFER): the buyer sends the money from their own bank to the merchant's
5
+ # bank account; the incoming transaction is matched to the payment by the payment code in the
6
+ # description (or by the exact amount when there is no code).
7
+ #
8
+ # The "Other banks" option of the bankCode field: the buyer pays by EFT/FAST from a bank not listed.
9
+ BANK_TRANSFER_OTHER_BANKS_CODE = '9999'
10
+ # Most items payments.list_bank_transfer_exceptions returns per call.
11
+ BANK_TRANSFER_EXCEPTION_LIMIT_MAX = 200
12
+
13
+ # Kind of a bank transfer exception.
14
+ module PaymentBankTransferExceptionKind
15
+ # Arrived after the deadline.
16
+ LATE = 'LATE'
17
+ # The deadline passed with less than expected; the payment waits for your decision.
18
+ UNDERPAID = 'UNDERPAID'
19
+ # More than expected arrived; refund the excess.
20
+ OVERPAID = 'OVERPAID'
21
+
22
+ ALL = [LATE, UNDERPAID, OVERPAID].freeze
23
+ end
24
+
25
+ # Status of a bank transfer exception.
26
+ module PaymentBankTransferExceptionStatus
27
+ PENDING_DECISION = 'PENDING_DECISION'
28
+ ACCEPTED = 'ACCEPTED'
29
+ REFUND_PENDING = 'REFUND_PENDING'
30
+ REFUNDED = 'REFUNDED'
31
+
32
+ ALL = [PENDING_DECISION, ACCEPTED, REFUND_PENDING, REFUNDED].freeze
33
+ end
34
+
35
+ # Webhook events of a BANK_TRANSFER payment (payment.* envelope, payload bankTransfer). They do not
36
+ # change the payment status: the outcome is still payment.captured / payment.failed.
37
+ module PaymentBankTransferEvents
38
+ PARTIALLY_RECEIVED = 'payment.bank_transfer.partially_received'
39
+ UNDERPAID = 'payment.bank_transfer.underpaid'
40
+ OVERPAID = 'payment.bank_transfer.overpaid'
41
+ LATE_ARRIVAL = 'payment.bank_transfer.late_arrival'
42
+
43
+ ALL = [PARTIALLY_RECEIVED, UNDERPAID, OVERPAID, LATE_ARRIVAL].freeze
44
+ end
45
+
46
+ # Transfer instruction of a BANK_TRANSFER payment (DISPLAY action, data.action.bankTransfer): the
47
+ # merchant's bank account to show the buyer. other_bank is true when the buyer chose "Other banks".
48
+ BankTransferInstruction = Struct.new(:bank_code, :bank_name, :holder_name, :iban, :amount_minor, :currency,
49
+ :payment_code, :expires_at, :other_bank, keyword_init: true) do
50
+ # Reads data.action.bankTransfer of a gateway response envelope (or of its data hash). Returns nil
51
+ # when there is no action, the action is not DISPLAY or it carries no transfer instruction.
52
+ def self.from_response(response)
53
+ return nil unless response.is_a?(Hash)
54
+
55
+ data = response.key?('data') ? response['data'] : response
56
+ action = data.is_a?(Hash) ? data['action'] : nil
57
+ return nil unless action.is_a?(Hash) && action['type'] == PaymentActionType::DISPLAY
58
+
59
+ instruction = action['bankTransfer']
60
+ return nil unless instruction.is_a?(Hash)
61
+
62
+ new(bank_code: instruction['bankCode'], bank_name: instruction['bankName'], holder_name: instruction['holderName'],
63
+ iban: instruction['iban'], amount_minor: instruction['amountMinor'], currency: instruction['currency'],
64
+ payment_code: instruction['paymentCode'], expires_at: instruction['expiresAt'], other_bank: instruction['otherBank'] == true)
65
+ end
66
+ end
67
+
68
+ # Query and path rules of the bank transfer exception endpoints.
69
+ module BankTransferExceptions
70
+ ENVIRONMENTS = %w[TEST LIVE].freeze
71
+ UUID_PATTERN = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i
72
+
73
+ module_function
74
+
75
+ # Query of GET /payments/bank-transfer/exceptions; empty filters are not sent.
76
+ def query!(environment: nil, status: nil, limit: nil)
77
+ query = {}
78
+ unless environment.nil?
79
+ raise ConfigurationError, "environment must be one of #{ENVIRONMENTS.join(', ')}" unless ENVIRONMENTS.include?(environment)
80
+
81
+ query['environment'] = environment
82
+ end
83
+ unless status.nil?
84
+ unless PaymentBankTransferExceptionStatus::ALL.include?(status)
85
+ raise ConfigurationError, "status must be one of #{PaymentBankTransferExceptionStatus::ALL.join(', ')}"
86
+ end
87
+
88
+ query['status'] = status
89
+ end
90
+ unless limit.nil?
91
+ unless limit.is_a?(Integer) && limit.between?(1, BANK_TRANSFER_EXCEPTION_LIMIT_MAX)
92
+ raise ConfigurationError, "limit must be an integer between 1 and #{BANK_TRANSFER_EXCEPTION_LIMIT_MAX}"
93
+ end
94
+
95
+ query['limit'] = limit.to_s
96
+ end
97
+ query
98
+ end
99
+
100
+ def exception_id!(value)
101
+ return value if value.is_a?(String) && value.match?(UUID_PATTERN)
102
+
103
+ raise ConfigurationError, 'exception_id must be the UUID of a bank transfer exception (items[].id)'
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Checks of the BIN, installment and stored-card bodies. Card numbers, BINs and security codes never
5
+ # appear in an error message.
6
+ module CardRules
7
+ BIN_OR_PAN_PATTERN = /\A[0-9]{6,19}\z/
8
+ INSTALLMENT_MAX = 36
9
+ TEXT_MAX_BYTES = 255
10
+
11
+ module_function
12
+
13
+ # A 6 or 8 digit BIN or a card number prefix, digits only.
14
+ def bin_or_pan!(value)
15
+ raise ConfigurationError, 'binOrPan must be 6 to 19 digits (a BIN or a card number prefix)' unless value.is_a?(String) && value.match?(BIN_OR_PAN_PATTERN)
16
+
17
+ value
18
+ end
19
+
20
+ def installment!(value)
21
+ raise ConfigurationError, "installment must be an integer from 1 to #{INSTALLMENT_MAX}" unless value.is_a?(Integer) && value.between?(1, INSTALLMENT_MAX)
22
+
23
+ value
24
+ end
25
+
26
+ def currency!(value)
27
+ raise ConfigurationError, 'Currency must be a three-letter uppercase code' unless value.is_a?(String) && value.match?(/\A[A-Z]{3}\z/)
28
+
29
+ value
30
+ end
31
+
32
+ def text!(value, field)
33
+ unless value.is_a?(String) && !value.strip.empty? && value.bytesize <= TEXT_MAX_BYTES && !value.match?(/[\x00-\x1f\x7f]/)
34
+ raise ConfigurationError, "#{field} must be a nonempty string of at most #{TEXT_MAX_BYTES} bytes"
35
+ end
36
+
37
+ value
38
+ end
39
+
40
+ # Body of POST /api/v1/bin/installments: amount (or intentId), currency and the optional binOrPan,
41
+ # installment, cardBrand and enabledInstallments (sent in ascending order).
42
+ def installment_options_body!(body)
43
+ data = plain!(body, 'Installment options request')
44
+ raise ConfigurationError, 'Installment options need amount or intentId' if data['amount'].nil? && data['intentId'].nil?
45
+
46
+ Money.minor(data['amount']) unless data['amount'].nil?
47
+ text!(data['intentId'], 'intentId') unless data['intentId'].nil?
48
+ currency!(data['currency']) unless data['currency'].nil?
49
+ bin_or_pan!(data['binOrPan']) unless data['binOrPan'].nil?
50
+ installment!(data['installment']) unless data['installment'].nil?
51
+ data['enabledInstallments'] = EnabledInstallments.check!(data['enabledInstallments']) if data.key?('enabledInstallments')
52
+ data
53
+ end
54
+
55
+ # Body of POST /api/v1/payments/cards: card, cardUserKey, an HTTPS callbackUrl and an optional currency.
56
+ def store_card_body!(body)
57
+ data = plain!(body, 'Store card request')
58
+ raise ConfigurationError, 'Store card request requires the card object' unless data['card'].is_a?(Hash) && !data['card'].empty?
59
+
60
+ text!(data['cardUserKey'], 'cardUserKey')
61
+ callback_url!(data['callbackUrl'])
62
+ currency!(data['currency']) unless data['currency'].nil?
63
+ data
64
+ end
65
+
66
+ def callback_url!(url)
67
+ uri = URI.parse(url)
68
+ raise ConfigurationError, 'callbackUrl must use HTTPS' unless uri.is_a?(URI::HTTPS) && uri.host && !uri.userinfo && !uri.fragment && url.bytesize <= 2048
69
+
70
+ url
71
+ rescue URI::InvalidURIError, TypeError
72
+ raise ConfigurationError, 'Invalid callbackUrl', cause: nil
73
+ end
74
+
75
+ def plain!(body, name)
76
+ body = body.to_h if body.is_a?(InstallmentOptionsRequest) || body.is_a?(StoreCardRequest)
77
+ raise ConfigurationError, "#{name} must be an object" unless body.is_a?(Hash)
78
+
79
+ JSON.parse(JsonBody.dump(body))
80
+ end
81
+ end
82
+
83
+ # Body of payments.installment_options: the installment table for an amount and, with a BIN, the
84
+ # binding quote token of installment > 1. Its inspect output never shows the card number.
85
+ class InstallmentOptionsRequest
86
+ def initialize(amount, currency)
87
+ @payload = { 'amount' => Money.minor(amount), 'currency' => CardRules.currency!(currency.to_s.upcase) }
88
+ end
89
+
90
+ # A 6 or 8 digit BIN or a card number prefix.
91
+ def with_bin_or_pan(value)
92
+ @payload['binOrPan'] = CardRules.bin_or_pan!(value)
93
+ self
94
+ end
95
+
96
+ # With an intent the intent's own enabledInstallments list applies first.
97
+ def with_intent_id(value)
98
+ @payload['intentId'] = CardRules.text!(value, 'intentId')
99
+ self
100
+ end
101
+
102
+ def with_installment(value)
103
+ @payload['installment'] = CardRules.installment!(value)
104
+ self
105
+ end
106
+
107
+ def with_card_brand(value)
108
+ @payload['cardBrand'] = CardRules.text!(value, 'cardBrand')
109
+ self
110
+ end
111
+
112
+ # Limits the table to these counts (e.g. [1, 2, 3]); the rules of the intent's enabledInstallments.
113
+ def with_enabled_installments(counts)
114
+ @payload['enabledInstallments'] = EnabledInstallments.check!(counts)
115
+ self
116
+ end
117
+
118
+ def to_h
119
+ @payload.dup
120
+ end
121
+
122
+ def inspect
123
+ "#<#{self.class.name} amount=#{@payload['amount']} currency=#{@payload['currency']}>"
124
+ end
125
+ end
126
+
127
+ # Body of payments.store_card (verify and store a card for cardUserKey). Its inspect output never
128
+ # shows the card.
129
+ class StoreCardRequest
130
+ def initialize(card, card_user_key, callback_url)
131
+ raise ConfigurationError, 'card must be an object' unless card.is_a?(Hash) && !card.empty?
132
+
133
+ @payload = { 'card' => card, 'cardUserKey' => CardRules.text!(card_user_key, 'cardUserKey'),
134
+ 'callbackUrl' => CardRules.callback_url!(callback_url) }
135
+ end
136
+
137
+ def with_currency(value)
138
+ @payload['currency'] = CardRules.currency!(value.to_s.upcase)
139
+ self
140
+ end
141
+
142
+ def to_h
143
+ @payload.dup
144
+ end
145
+
146
+ def inspect
147
+ "#<#{self.class.name} card=[REDACTED]>"
148
+ end
149
+ end
150
+ end
data/lib/lunixi/client.rb CHANGED
@@ -8,7 +8,11 @@ module Lunixi
8
8
  class Client
9
9
  AUTH_PATH = '/api/v1/auth/token'
10
10
  METHODS = %w[GET HEAD POST PUT PATCH DELETE].freeze
11
- attr_reader :payments, :fraud
11
+ ACCEPT_JSON = 'application/json'
12
+ # The customer-portal link routes of subscriptions live under the panel API.
13
+ PANEL_PORTAL_PATH = %r{\A/api/panel/v1/subscriptions/portal(?:/|\z)}
14
+ attr_reader :payments, :fraud, :reference, :payment_links, :physical_pos, :physical_pos_management, :wallet, :bank_connect, :sanction,
15
+ :insurance, :subscriptions, :kyc, :identity, :marketplace
12
16
 
13
17
  def initialize(base_url:, key_id:, private_key:, timeout: 30, max_retries: 2, transport: nil,
14
18
  clock: -> { Time.now.utc }, sleeper: ->(seconds) { sleep(seconds) }, ca_file: nil)
@@ -28,17 +32,35 @@ module Lunixi
28
32
  @token_expires_at = Time.at(0)
29
33
  @payments = Payments.new(self)
30
34
  @fraud = Fraud.new(self)
35
+ @reference = Reference.new(self)
36
+ @payment_links = PaymentLinks.new(self, storage_transport: @transport)
37
+ physical_pos_gateway = PhysicalPosGateway.new(self, max_retries: max_retries, backoff: ->(attempt) { pause(attempt, {}) })
38
+ @physical_pos = PhysicalPos.new(physical_pos_gateway)
39
+ @physical_pos_management = PhysicalPosManagement.new(physical_pos_gateway)
40
+ @wallet = Wallet.new(self)
41
+ @bank_connect = BankConnect.new(self, max_retries: max_retries, backoff: ->(attempt) { pause(attempt, {}) })
42
+ @sanction = Sanction.new(self)
43
+ @insurance = Insurance.new(self)
44
+ @subscriptions = Subscriptions.new(self)
45
+ @kyc = Kyc.new(self)
46
+ @identity = Identity.new(self)
47
+ @marketplace = Marketplace.new(self)
31
48
  end
32
49
 
33
50
  # Advanced, signed transport for other documented gateway surfaces. It does
34
- # not invent field schemas, interpret financial results or retry an unsafe POST.
35
- def request(method, path, body: nil, query: {}, idempotency_key: nil, signed: true, binary: false)
51
+ # not invent field schemas, interpret financial results or retry an unsafe POST. With binary: true a
52
+ # 2xx body is returned as frozen bytes; accept: names the media types the endpoint answers with.
53
+ # max_retries: lowers the client's retry budget for this call (0 sends a single attempt).
54
+ def request(method, path, body: nil, query: {}, idempotency_key: nil, signed: true, binary: false, accept: ACCEPT_JSON,
55
+ max_retries: nil)
36
56
  method = method.to_s.upcase
37
57
  raise ConfigurationError, 'Unsupported HTTP method' unless METHODS.include?(method)
38
58
  raise ConfigurationError, 'GET and HEAD cannot have a body' if %w[GET HEAD].include?(method) && !body.nil?
59
+ raise ConfigurationError, 'Invalid Accept header' unless accept.is_a?(String) && accept.match?(%r{\A[a-z0-9.+/*-]+(?:, ?[a-z0-9.+/*-]+)*\z})
39
60
 
61
+ retries = retry_budget(max_retries)
40
62
  path = safe_path(path, query)
41
- key = self.class.idempotency_key!(idempotency_key) if idempotency_key
63
+ key = request_idempotency_key(path, idempotency_key) if idempotency_key
42
64
  Money.validate_operation_amount(path, body)
43
65
  if Money.fiat_route?(path)
44
66
  Money.validate_fields(body)
@@ -47,7 +69,7 @@ module Lunixi
47
69
  bytes = body.nil? ? nil : JsonBody.dump(body)
48
70
  raise ConfigurationError, 'Request body exceeds the size limit' if bytes && bytes.bytesize > 1024 * 1024
49
71
 
50
- perform_request(method, path, bytes, key, signed, binary)
72
+ perform_request(method, path, bytes, key, signed, binary, accept, retries)
51
73
  end
52
74
 
53
75
  # Validates caller-owned durable keys; a generated key on every retry is unsafe.
@@ -65,34 +87,53 @@ module Lunixi
65
87
 
66
88
  private
67
89
 
68
- def perform_request(method, path, bytes, key, signed, binary)
90
+ # Physical POS, bank-connect and insurance routes take 8–200 printable ASCII characters (sent as
91
+ # given); wallet routes 1–128 characters without control characters; subscription, KYC, identity and
92
+ # marketplace routes any non-empty key without control characters (sent trimmed).
93
+ def request_idempotency_key(path, key)
94
+ return PhysicalPosIdentifiers.idempotency_key!(key) if path.match?(PhysicalPosRequest::ROUTE)
95
+ return RouteRequest.printable_idempotency_key!(key) if path.match?(RouteRequest::PRINTABLE_KEY_ROUTE)
96
+ return WalletInvoker.idempotency_key!(key) if path.match?(WalletInvoker::ROUTE)
97
+ return RouteTable.idempotency_key!(key) if path.match?(RouteTable::KEY_ROUTE)
98
+
99
+ self.class.idempotency_key!(key)
100
+ end
101
+
102
+ def retry_budget(max_retries)
103
+ return @max_retries if max_retries.nil?
104
+ raise ConfigurationError, "max_retries must be between 0 and #{@max_retries}" unless max_retries.is_a?(Integer) && max_retries.between?(0, @max_retries)
105
+
106
+ max_retries
107
+ end
108
+
109
+ def perform_request(method, path, bytes, key, signed, binary, accept, max_retries)
69
110
  safe_to_retry = %w[GET HEAD].include?(method) || !key.nil?
70
111
  retries = 0
71
112
  reauthenticated = false
72
113
  loop do
73
114
  token = access_token
74
- response = transmit(method, path, bytes, key, token, signed)
115
+ response = transmit(method, path, bytes, key, token, signed, accept)
75
116
  if response.status == 401 && !reauthenticated && safe_to_retry
76
117
  invalidate_token(token)
77
118
  reauthenticated = true
78
119
  next
79
120
  end
80
- if retryable_response?(response, safe_to_retry, retries)
121
+ if retryable_response?(response, safe_to_retry, retries, max_retries)
81
122
  pause(retries, response.headers)
82
123
  retries += 1
83
124
  next
84
125
  end
85
126
  return decode_response(response, binary: binary, fiat: Money.fiat_route?(path), running_split: method == 'POST' && path == '/api/v1/payments/split')
86
127
  rescue TransportError
87
- raise unless safe_to_retry && retries < @max_retries
128
+ raise unless safe_to_retry && retries < max_retries
88
129
 
89
130
  pause(retries, {})
90
131
  retries += 1
91
132
  end
92
133
  end
93
134
 
94
- def retryable_response?(response, safe_to_retry, retries)
95
- [429, 502, 503, 504].include?(response.status) && safe_to_retry && retries < @max_retries
135
+ def retryable_response?(response, safe_to_retry, retries, max_retries)
136
+ [429, 502, 503, 504].include?(response.status) && safe_to_retry && retries < max_retries
96
137
  end
97
138
 
98
139
  def validate_origin(value)
@@ -107,8 +148,8 @@ module Lunixi
107
148
  end
108
149
 
109
150
  def safe_path(path, query)
110
- unless path.is_a?(String) && path.start_with?('/api/v1/') && path.match?(%r{\A/[a-zA-Z0-9_~./%-]+\z})
111
- raise ConfigurationError, 'Only relative /api/v1/ gateway paths are accepted'
151
+ unless path.is_a?(String) && (path.start_with?('/api/v1/') || path.match?(PANEL_PORTAL_PATH)) && path.match?(%r{\A/[a-zA-Z0-9_~./%-]+\z})
152
+ raise ConfigurationError, 'Only relative /api/v1/ gateway paths (and the subscription portal panel routes) are accepted'
112
153
  end
113
154
 
114
155
  path.split('/').each do |segment|
@@ -147,8 +188,8 @@ module Lunixi
147
188
  headers
148
189
  end
149
190
 
150
- def transmit(method, path, body, key, token, signed)
151
- headers = { 'Accept' => 'application/json', 'User-Agent' => "lunixi-sdk-ruby/#{VERSION}" }
191
+ def transmit(method, path, body, key, token, signed, accept = ACCEPT_JSON)
192
+ headers = { 'Accept' => accept, 'User-Agent' => "lunixi-sdk-ruby/#{VERSION}" }
152
193
  headers['Authorization'] = "Bearer #{token}" if token
153
194
  headers['Content-Type'] = 'application/json' unless body.nil?
154
195
  headers['Idempotency-Key'] = key if key
@@ -216,7 +257,7 @@ module Lunixi
216
257
  end
217
258
  error = error_class.new(status: response.status, code: payload['code'],
218
259
  request_id: response.headers['x-request-id'] || response.headers['X-Request-Id'],
219
- retry_after: response.headers['retry-after'])
260
+ retry_after: response.headers['retry-after'], details: payload['details'])
220
261
  # Running split sessions are successful protocol responses, not completed payments.
221
262
  running = %w[COMPOSING AUTHORIZING AWAITING_3DS AWAITING_ACTION AWAITING_CREDIT_APPROVAL AWAITING_REPLACEMENT_CARD AUTHORIZED CAPTURING]
222
263
  return payload if running_split && response.status == 400 && running.include?(payload['code']) && payload.dig('data', 'splitPaymentId').is_a?(String)
@@ -0,0 +1,243 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Body of POST /api/v1/payments/direct/payment (payments.direct_method_payment). amount is the order
5
+ # total as a positive canonical minor-unit string. Choose the method with with_method_fields or
6
+ # with_card; the provider code and the fields of a method come from payments.list_payment_methods.
7
+ class DirectMethodPaymentRequest
8
+ REQUIRED_FIELDS = %w[paymentMethod amount currency orderId].freeze
9
+
10
+ def initialize(amount, currency, order_id)
11
+ @payload = { 'amount' => Money.minor(amount), 'currency' => currency_code(currency), 'orderId' => text(order_id, 'orderId') }
12
+ @payment_method = nil
13
+ @block = nil
14
+ @promissory_note_plan = nil
15
+ end
16
+
17
+ # Pays with a method other than card. fields are the provider's inputFields values ({} when the
18
+ # provider asks for nothing). provider_code is required when the method lists more than one
19
+ # provider (providerSelection REQUIRED); BANK_TRANSFER takes none, only the buyer's { bankCode: }.
20
+ def with_method_fields(payment_method, provider_code, fields = {})
21
+ code = MethodFields.normalize_payment_method(payment_method)
22
+ raise ConfigurationError, 'Use with_card(card) to pay by card' if code == PaymentMethod::CARD
23
+
24
+ block_name = self.class.method_block_name!(code)
25
+ block = MethodFields.method_fields!(plain(fields, block_name), block_name)
26
+ if code == PaymentMethod::PROMISSORY_NOTE
27
+ raise ConfigurationError, 'Pass the promissory-note schedule with with_promissory_note_schedule, not in the fields' if block.key?('schedule')
28
+
29
+ block['noteCount'] = PromissoryNotePlan.note_count!(block['noteCount']) if block.key?('noteCount')
30
+ end
31
+ if code == PaymentMethod::BANK_TRANSFER && !provider_code.nil?
32
+ raise ConfigurationError, "paymentMethod BANK_TRANSFER takes no providerCode: pass nil and the buyer's bank as { bankCode: }"
33
+ end
34
+
35
+ @payment_method = code
36
+ @block = provider_code.nil? ? block : { 'providerCode' => MethodFields.provider_code!(provider_code) }.merge(block)
37
+ self
38
+ end
39
+
40
+ # Promissory-note plan: one note per row, [{ amount:, dueDate: }], adding up to amount. Replaces a note count.
41
+ def with_promissory_note_schedule(schedule)
42
+ @promissory_note_plan = { 'schedule' => PromissoryNotePlan.schedule!(schedule) }
43
+ self
44
+ end
45
+
46
+ # Promissory-note plan: the number of notes (1–24). Replaces a schedule.
47
+ def with_promissory_note_count(count)
48
+ @promissory_note_plan = { 'noteCount' => PromissoryNotePlan.note_count!(count) }
49
+ self
50
+ end
51
+
52
+ # Pays by card: new card fields, or cardUserKey + cardToken for a stored card.
53
+ def with_card(card)
54
+ block = plain(card, 'card')
55
+ raise ConfigurationError, 'with_card requires nonempty card fields' if block.empty?
56
+
57
+ @payment_method = PaymentMethod::CARD
58
+ @block = block
59
+ self
60
+ end
61
+
62
+ # Card only. quote_token binds the charge to a quote from the installment options endpoint.
63
+ def with_installment(count, quote_token = nil)
64
+ raise ConfigurationError, 'installment must be an integer' unless count.is_a?(Integer)
65
+
66
+ @payload['installment'] = count
67
+ @payload['installmentQuoteToken'] = text(quote_token, 'installmentQuoteToken') unless quote_token.nil?
68
+ self
69
+ end
70
+
71
+ # Card only. true charges with 3D Secure: the response carries a REDIRECT action.
72
+ def with_force3d(value)
73
+ @payload['force3D'] = boolean(value, 'force3D')
74
+ self
75
+ end
76
+
77
+ # Pre-authorization: the payment becomes AUTHORIZED; capture or void it later.
78
+ def with_preauth(value)
79
+ @payload['preauth'] = boolean(value, 'preauth')
80
+ self
81
+ end
82
+
83
+ # Where the buyer's browser returns after a REDIRECT action.
84
+ def with_callback_url(value)
85
+ assign('callbackUrl', text(value, 'callbackUrl'))
86
+ end
87
+
88
+ def with_locale(value)
89
+ assign('locale', text(value, 'locale'))
90
+ end
91
+
92
+ def with_description(value)
93
+ assign('description', value)
94
+ end
95
+
96
+ def with_customer_id(value)
97
+ assign('customerId', value)
98
+ end
99
+
100
+ def with_payment_channel(value)
101
+ assign('paymentChannel', value)
102
+ end
103
+
104
+ def with_payment_group(value)
105
+ assign('paymentGroup', value)
106
+ end
107
+
108
+ def with_buyer(value)
109
+ assign('buyer', plain(value, 'buyer'))
110
+ end
111
+
112
+ def with_billing_address(value)
113
+ assign('billingAddress', plain(value, 'billingAddress'))
114
+ end
115
+
116
+ def with_shipping_address(value)
117
+ assign('shippingAddress', plain(value, 'shippingAddress'))
118
+ end
119
+
120
+ def with_metadata(value)
121
+ assign('metadata', value)
122
+ end
123
+
124
+ def with_basket_items(items)
125
+ raise ConfigurationError, 'basketItems must be an array of objects' unless items.is_a?(Array)
126
+
127
+ assign('basketItems', items.map { |item| plain(item, 'basketItems[]') })
128
+ end
129
+
130
+ # The gateway body with string keys, checked with the same rules as a raw body.
131
+ def to_h
132
+ raise ConfigurationError, 'Choose the payment method with with_method_fields(method, provider_code, fields) or with_card(card)' unless @payment_method
133
+
134
+ block = @block.dup
135
+ if @payment_method == PaymentMethod::PROMISSORY_NOTE && @promissory_note_plan
136
+ raise ConfigurationError, 'The promissory-note plan is given twice: noteCount in the fields and a plan method; use one' if block.key?('noteCount')
137
+
138
+ block.merge!(@promissory_note_plan)
139
+ elsif @promissory_note_plan
140
+ raise ConfigurationError, 'A promissory-note plan can only be sent with paymentMethod PROMISSORY_NOTE'
141
+ end
142
+ body = { 'paymentMethod' => @payment_method }.merge(@payload.compact)
143
+ body[MethodFields.block_name_of(@payment_method)] = block
144
+ self.class.payload!(body)
145
+ end
146
+
147
+ # Checks a direct/payment body (a Hash or the result of to_h) before sending and returns a
148
+ # string-keyed copy: known fields only, the chosen method's block and no other, card fields only
149
+ # with CARD, block structure, promissory-note plan, shopping-loan basket, no providerCode for
150
+ # BANK_TRANSFER.
151
+ def self.payload!(body)
152
+ raise ConfigurationError, 'A direct method payment needs a body; use DirectMethodPaymentRequest to build it' unless body.is_a?(Hash)
153
+
154
+ data = JSON.parse(JsonBody.dump(body))
155
+ raise ConfigurationError, 'Removed amount field; use amount in integer minor units' if %w[price paidPrice].any? { |key| data.key?(key) }
156
+
157
+ unknown = data.keys - DIRECT_METHOD_PAYMENT_FIELDS
158
+ raise ConfigurationError, "Unknown direct method payment field(s): #{unknown.join(', ')}" unless unknown.empty?
159
+
160
+ missing = REQUIRED_FIELDS.find { |field| data[field].nil? || data[field] == '' }
161
+ raise ConfigurationError, "Direct method payments require '#{missing}'" if missing
162
+
163
+ Money.minor(data['amount'])
164
+ method = MethodFields.normalize_payment_method(data['paymentMethod'])
165
+ data['paymentMethod'] = method
166
+ block_name = method == PaymentMethod::CARD ? 'card' : method_block_name!(method)
167
+ blocks!(data, method, block_name)
168
+ PromissoryNotePlan.plan!(data['promissoryNote'], data['amount']) if method == PaymentMethod::PROMISSORY_NOTE
169
+ MethodFields.shopping_loan_basket!(method, data['basketItems'])
170
+ %w[preauth force3D].each do |field|
171
+ raise ConfigurationError, "#{field} must be a JSON boolean" if data.key?(field) && ![true, false].include?(data[field])
172
+ end
173
+ data
174
+ end
175
+
176
+ # Block name of a method other than card; a method without a block cannot be paid here yet.
177
+ def self.method_block_name!(code)
178
+ block_name = MethodFields.block_name_of(code)
179
+ return block_name if METHOD_BLOCK_FIELDS.include?(block_name)
180
+
181
+ raise ConfigurationError, "paymentMethod #{code} cannot be paid through direct/payment yet; payments.list_payment_methods lists the methods that can"
182
+ end
183
+
184
+ def self.blocks!(data, method, block_name)
185
+ if method != PaymentMethod::CARD
186
+ card_field = CARD_ONLY_FIELDS.find { |field| !data[field].nil? }
187
+ raise ConfigurationError, "#{card_field} can only be sent with paymentMethod CARD" if card_field
188
+ end
189
+ other = METHOD_BLOCK_FIELDS.find { |field| field != block_name && !data[field].nil? }
190
+ raise ConfigurationError, "paymentMethod #{method} takes only the '#{block_name}' block; '#{other}' must not be sent" if other
191
+
192
+ block = data[block_name]
193
+ raise ConfigurationError, "paymentMethod #{method} requires the '#{block_name}' block" unless block.is_a?(Hash)
194
+ return if method == PaymentMethod::CARD
195
+
196
+ method_block!(block, method, block_name)
197
+ end
198
+
199
+ def self.method_block!(block, method, block_name)
200
+ if block.key?('providerCode')
201
+ raise ConfigurationError, 'paymentMethod BANK_TRANSFER takes no providerCode in the bankTransfer block' if method == PaymentMethod::BANK_TRANSFER
202
+
203
+ MethodFields.provider_code!(block['providerCode'])
204
+ end
205
+ excluded = method == PaymentMethod::PROMISSORY_NOTE ? %w[providerCode schedule] : %w[providerCode]
206
+ MethodFields.method_fields!(block.except(*excluded), block_name)
207
+ end
208
+
209
+ private_class_method :blocks!, :method_block!
210
+
211
+ private
212
+
213
+ def assign(field, value)
214
+ @payload[field] = value
215
+ self
216
+ end
217
+
218
+ def plain(value, field)
219
+ raise ConfigurationError, "#{field} must be an object" unless value.is_a?(Hash)
220
+
221
+ JSON.parse(JsonBody.dump(value))
222
+ end
223
+
224
+ def text(value, field)
225
+ raise ConfigurationError, "#{field} must be a nonempty string" unless value.is_a?(String) && !value.strip.empty?
226
+
227
+ value
228
+ end
229
+
230
+ def boolean(value, field)
231
+ raise ConfigurationError, "#{field} must be a boolean" unless [true, false].include?(value)
232
+
233
+ value
234
+ end
235
+
236
+ def currency_code(value)
237
+ code = value.to_s.upcase
238
+ raise ConfigurationError, 'Currency must be a three-letter code' unless code.match?(/\A[A-Z]{3}\z/)
239
+
240
+ code
241
+ end
242
+ end
243
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # enabledInstallments narrows the installment counts of one payment (intent, marketplace intent and
5
+ # installment options): a nonempty list of distinct integers 1–36 that contains 1. Leaving the field
6
+ # out means no restriction, so an empty list is refused (the gateway answers it with 400).
7
+ module EnabledInstallments
8
+ MIN = 1
9
+ MAX = 36
10
+
11
+ module_function
12
+
13
+ # Returns a frozen copy in ascending order, the order the gateway expects.
14
+ def check!(values, field = 'enabledInstallments')
15
+ unless values.is_a?(Array) && !values.empty?
16
+ raise ConfigurationError, "#{field} must be a nonempty array of installment counts; leave it out for no restriction, " \
17
+ 'or send [1] for a single payment only'
18
+ end
19
+ unless values.all? { |value| value.is_a?(Integer) && value.between?(MIN, MAX) }
20
+ raise ConfigurationError, "#{field} values must be integers from #{MIN} to #{MAX}"
21
+ end
22
+ raise ConfigurationError, "#{field} lists an installment count more than once" unless values.uniq.size == values.size
23
+ raise ConfigurationError, "#{field} must contain 1 (single payment)" unless values.include?(MIN)
24
+
25
+ values.sort.freeze
26
+ end
27
+ end
28
+ end